简体   繁体   中英

Add fields dynamically in drupal depending on selected option using ajax/jquery

I'm trying to create/add textfields dynamically in drupal depending on the selected option for a select list.

if Jack is selected, then create textfield with "Jack" as content.

What I have done so far using Drupal's #ajax property, I managed to create textfields but could not get the select list option as field value.

$form['select_list'] = array(
    '#type' => 'select',
    '#options' => array('jack'=>'Jack', 'ben'=>'Ben'),
    '#ajax' => array(
         'callback' => 'mymodule_ajax_add',
         'wrapper' => 'select_list_fieldset',
         'method' => 'replace',
         'effect' => 'fade'
    )
);

$form['select_list_fieldset'] = array(
      '#type' => 'fieldset',
      '#prefix' => '<div id="select_list_fieldset">',
      '#suffix' => '</div>';
);

$form_state['storage']['num_people'] = isset($form_state['storage']['num_people']) ? $form_state['storage']['num_people'] : 1;

if($form_state['storage']['num_people']){
    for( $i = 1; $i < $form_state['storage']['num_people']; $i++){
        $form['select_list_fieldset'][$i]['person_name'] = array(
            '#title' => 'Name',
            '#type' => 'textfield',
            '#value' => ???????
        );
    }
}

$form_state['storage']['num_people']++;


function mymodule_ajax_add($form, &$form_state){
    return $form['select_list_fieldset'];
}

I got this to work but got frustrated on how to populate the fields with what I want.

I also tried to do it explicitly using jQuery. I managed to re-create fields pre-populated with the values depending on the selected option from the select list.

$('#select_list').change(function(){
    var name_key = $(this).val();
    var name_value = $(this).text();

    $('#select_list_fieldset').append('<input type="text" value="'+name_value+'">');
});

The problem with writing it through jQuery is that once the form is submitted all dynamically created fields are disregarded. I read it somewhere here in stackoverflow.

Can anyone help me and point me to the right direction on how to achieve this? Thanks a lot in advance.

Get selected option of select_list :

$selected_name = isset($form_state['values']['select_list]) ? $form_state['values']['select_list'] :  NULL;

Set default value for person_name :

'#default_value' =>  $selected_name,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM