Would you like to be notified for every new articles? Please click HERE to subscribe for newsletter.

Creating Ajax Dropdown In Drupal 7

  • Posted on: 24 May 2012
  • By: admin

Drupal 7 has a very great Ajax framework which allow us to use Ajax feature when we build the module. One of Ajax feature that we can develop in Drupal module is Ajax dropdown list. In this tutorial, we will see how create it. For the example, we will create two dropdown list, one contains the list of provinces which already populated at page load, and the other one will be filled dynamically with the cities list based on the selected item in province dropdown list.

The #Ajax Attribute

First, we have to define the #ajax attribute to your select element. This attribute will enable Ajax for your form element, in this case is the dropdown list. The #ajax attribute accept array as its value. The array itself require at least three keys, event, callback, and wrapper. For the province dropdown list, we will use change as the value for event which means the Ajax request will be triggered when the selected province is changed. For the callback value we will fill it with the name of function which will be executed on Ajax request. And then, the wrapper must be filled with the ID of the element that will hold the returned result from the Ajax request.

<?php
/**
 * Function for generating form
 */
function sandbox_ajax_dropdown($form, &$form_state) {
  
// Province dropdown list
  
$form['sandbox_ajax_dropdown']['province'] = array(
    
'#title' => t('Province'),
    
'#type' => 'select',
    
'#options' => _load_province(),
    
'#ajax' => array(
      
'event'=>'change',
      
'callback' =>'sandbox_ajax_dropdown_city',
      
'wrapper' => 'city-wrapper',
    ),
  );

  

// Wrapper for city dropdown list
 
$form['sandbox_ajax_dropdown']['wrapper'] = array(
    
'#prefix' => '<div id="city-wrapper">',
    
'#suffix' => '</div>',
  );

  

// Options for city dropdown list
  
$options = array('- Select city -');
  if (isset(
$form_state['values']['province'])) {
    
// Pre-populate options for city dropdown list if province id is set
    
$options _load_city($form_state['values']['province']);
  }

  

// Province dropdown list
  
$form['sandbox_ajax_dropdown']['wrapper']['city'] = array(
    
'#title' => t('City'),
    
'#type' => 'select',
    
'#options' => $options,
  );

  

// Form submit button
  
$form["sandbox_ajax_dropdown"]["submit"] = array(
    
"#value"  => t("Submit"),
    
"#type"   => "submit",
    
"#submit" => array("sandbox_ajax_dropdown_submit"),
  );

  return 

$form;
}
?>

* Note: the city combobox should be created inside the wrapper.

The Callback Function

Remember the callback we have talked about? This function should return HTML code or renderable element like form element. In our case, we will return the dropdown list element which contains the list of city.

<?php
/**
 * Function for handling ajax request
 */
function sandbox_ajax_dropdown_city($form$form_state) {
  
// Return the dropdown list including the wrapper
  
return $form['sandbox_ajax_dropdown']['wrapper'];
}
?>

* Note: the returned dropdown element should include its wrapper.

Prevent The 'Illegal Choice' Error

For you who already try to build the same kind of Ajax dropdown as in this tutorial, you might have the 'Illegal Choice' error for the second Ajax request and after if you put the code to load the city list inside the callback function. The same error might also happen again when you submit the form.

So, the trick to avoid that error is by populating the dropdown list options based on the form state values in the form generation function, not inside the callback function. The callback function only need to return the dropdown list including its wrapper.

<?php
// Options for city dropdown list
$options = array('- Select city -');
if (isset(
$form_state['values']['province'])) {
  
// Pre-populate options for city dropdown list if province id is set
  
$options _load_city($form_state['values']['province']);
}

// Province dropdown list
$form['sandbox_ajax_dropdown']['wrapper']['city'] = array(
  
'#title' => t('City'),
  
'#type' => 'select',
  
'#options' => $options,
);
?>

* Note: this code should be placed inside the function that you use for the form generation process.

Live Demo

You can try the live demo here.

The full source code can be downloaded from the attachment section.

AttachmentSize
Binary Data Complete Source Code2.15 KB
Tags: 

Comments

Fantastic, tutorial ... I tried it in drupal 7 .. and its working ...
How can we achive this in drupal 6 .. ?
will you please guide me ..

Hi, you "attachment" does not contain any file... after extraction its empty folder, will you please upload it again in simple zip format?

I was looking for the solution since the beginning of the week. I've spend hours on it.
Really a big thanks...

I know this article is almost a year old, but I am a drupal newbee and really want to implement this, I just don't know where to start.

How use this module, I'm new to drupal and i want to user this ajax call and show node form on-change of first drop down.
Please help me for the same.

hello! i'm newbee too...i didn't understand, is it connect to 2 cck fields with dropdown list?

Thanks a lot for posting this fantastic tutorial . I would like to show database table data in html table based on selected province id and city id conditional values . I have written code in view button (in your example submit button I modified as view) but I was not successful.
I would be more happy if you can guide me
Thanks in advance .

plzz help me how i can display the products by City drop-down.

Creating Ajax Dropdown In Drupal 7 is one of the best and most important share I have seen on the internet so far and I am happy that you have taken the effort for this. Great and impressive article and I will visit the page again for more.
more here

I need build a module with 5 list with this same functionallity

i have installed this module & enabled it but not getting how to use it please reply back to my mail id anantsk92@gmail.com

i have implemented ajax country city state dropdown drupal7 following this tutorial..sometime it gives when state changes 2nd ajax request..how can i solve it ..i have downloaded the full code from here

Add new comment

Limited HTML

  • Allowed HTML tags: <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.