Search code examples
drupal-7componentsfieldalterdrupal-webform

Drupal 7 - How to alter the "select" component given by Webform?


My need is to add a new custom field "coeff" to the component "Select options" (slug is select) given by Webform.

I create my custom field with the hook_form_alter:

function my_module_form_alter(&$form, &$form_state, $form_id){
    if ($form_id == 'webform_component_edit_form') {
        if ($form['type']['#value'] == 'select') {
            $form['coeff'] = array(
                '#type' => 'textfield',
                '#title' => t('Coefficient'),
                '#default_value' => '1',
                '#description' => t('Set coefficient value for this question.'),
                '#size' => 2,
                '#maxlength' => 2,
            );
        }
    }
}

With that it's OK. My field is visible when I edit a "Select options" component. But my values are not saved in this field.

My questions are :

  • Have I to add a submit callback in this form to save this custom field? If yes how it works ?

  • How can I do If I want to make a loop to create lot of questions ? I know I have to build a node object and finally to call node_save() ... but where I have to put the value of this custom field "coeff" ?

If you don't have the answer it is not bad, just give me clues.

Thanks a lot.


Solution

  • You need to change the field name to $form['extra']['coeff'] and change the default value to show the saved one:

     if ($form_id == 'webform_component_edit_form') {
    
        if ($form['type']['#value'] == 'select') {
          $form['extra']['coeff'] = array(
            '#type' => 'textfield',
            '#title' => t('Coefficient'),
            '#default_value' => $form['#node']->webform['components'][1]['extra']['coeff'],
            '#description' => t('Set coefficient value for this question.'),
            '#size' => 2,
            '#maxlength' => 2,
          );
        }
    
      }