Sign in Registration
ArticlesDownloadServicesAudioContacts
ruen

How to make a dynamic form in Drupal with Ajax, select autocomplete

Sometimes you need to create dynamic forms in Drupal - forms that change without reloading the page. In Drupal there is also such an opportunity, making a dynamic form in Drupal is not difficult at all. Most often, you need to fill in select with option values ​​depending on what is selected in the other field.

drupal-form-dinamic-select

Everyone knows that for creating forms in Drupal there is a special Form API . A dynamic form is also done with it. First, you need to create the required fields, as is usually done. To make the form dynamic, you just need to add additional code.

So, let's see how to make a dynamic form using an example:

  // function for creating a form
function get_select ($ form, & $ form_state) {
// the number of options in select_two, at the first construction of the form is always equal to 1
$ numbers = empty ($ form_state ['values'] ['select_one'])? 1: $ form_state ['values'] ['select_one'];

// filling the array of values ​​for select_two
$ select_two_values ​​= array ();
for ($ i = 1; $ i <= $ numbers; $ i ++) {
$ select_two_values ​​['option _'. $ i] = 'Value'. $ i;
}

$ form ['select_one'] = array (
'#title' => 'First list',
'#description' => 'Select how many values ​​will be in the second list',
'#type' => 'select',
'#options' => array ('1' => '1 value', '2' => '2 values', '3' => '3 values'),
// make the form dynamic
'#ajax' => array (
// function to be called when the select_one value changes
'callback' => 'get_select_one_values',
// id of the element on the page where the results should be written
'wrapper' => 'wrapper',
'method' => 'replace',
'effect' => 'fade',
),
);

$ form ['select_two'] = array (
'#title' => 'Second list',
'#description' => 'Select a value from the second list',
'#type' => 'select',
'#options' => $ select_two_values,
// prefix and suffix wraps select_two with id = wrapper - this is where the results will be written
'#prefix' => '& lt; div id = "wrapper">',
'#suffix' => '& lt / div>',
);

return $ form;
}

// function that will be called when the select_one value changes
function get_select_one_values ​​($ form, $ form_state) {
// the select_two field will be rebuilt
return $ form ['select_two'];
}
 

Thus, the dynamic form on Drupal has been successfully created, now when the value from the first list changes, the values ​​in the second list will be automatically updated.

Comments (0)
For commenting sign in or register.