You are here

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.

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.

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.

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 .

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 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