Learning Ext JS 3

Linked ComboBoxes with ExtJS Más videos

Descripción del tema

Sometimes the information we use in our applications is grouped into categories, in these situations the linked combos will help us to maintain these connections in a simple way. In today's tutorial we will create two combos that are related to each other, we'll use the typical example countries and their respective states, the information of the state's combo will be loaded with Ajax depending on the country selected in the first combo. I recommend you test the demo to be able to see the final result.
Linked ComboBoxes with ExtJS

Tutorial's demo

Resources

Before I start explaning this tutorial you need to download the resources and copy the content into a Web server because we will be using Ajax to load information.

The information source

Let's write the code needed to generate the information the combos will display, for this example the information is in PHP arrays, but remember that you can retrieve it from a database, Web Service, a text file or elsewhere.
 
$countries = array('Argentina','España','México','Perú','United States'); //step 1

$states = array( 			//step 2
	array('Buenos Aires','Córdoba','La Pampa','Mendoza','Santa Fe'),
	array('Asturias','Valencia','Barcelona','Toledo'),
	array('Distrito Federal','Nuevo León','Jalisco'),
	array('Arequipa','Puno','Tacna','Lima'),
	array('Texas','California','New york','Virginia')
);
In step one I have been defined the countries we will use in the first combo, these are five countries but the array can be bigger or smaller. In step two I have defined the states of each country, it is important to mention that the connection is being made by the position in the arrays, let's write the following code to linked both combos:
$id = isset($_POST['id'])?$_POST['id']:-1;	//step 1
	
if($id > -1){					//step 2
	//show states
	echo toJSON($states[$id]);		//step 3
}else{
	//show contries
	echo toJSON($countries);		//step 4
}
In step one we retrieve the parameter "id" and verify the existence, if it hasn't been sent we assign the value "-1" to the variable. In step two we verify that the "id" is greater than "-1", this tells us that our application is requesting the states of a country, the variable "id" must have the position of the requested country so in this part we decide what is going to be displayed: countries or states. Step three is executed if the variable "id" contains the index of the selected country, so we can display the states of the requested index. Step four is only implemented if the "id" is less than or equal to -1, this tells us that the application has requested the countries. You probably noticed that we're invoking the function "toJSON", so let's go ahead an write the function like this:
function toJSON($array){
	$data=array(); $i=0;			//step 1
	$total = count($array);
	foreach($array as $key=>$value){	//step 2
		array_push($data,array(
			'value'=>$i++,		//step 3
			'label'=>$value
		));
	}
	
	return json_encode(array(		//step 4
		'total'=>$total,
		'data'=>$data
	));
}
The purpose of this function is to create the JSON we're going to send to the combos. In step one we created two variables: "data" and "i", in the variable "data" we will store each country or state we will display in the combos, the variable "i" is very important because we will use it to create the connection between the combos, I will explain this in step three. In step two, we create a loop that runs through the array we received as a parameter, this array contains the information we're going to display in the combos. In step three we are storing each element of the array in the variable "data", you can see that we are creating an array with two properties "value" and "label", these properties will be used by the combo, in the property "value" we assigned the value of "i", this is the value sent as a parameter to request the states of the country selected in the first combo, the property "label" is only the text that will display each option in the combo. In step four we return the information we collected previously in JSON format.

Creating JsonStores

Once we have defined the information we need to display we can create the combos, we already know that the combos use a Store to manipulate the information displayed. There is a JS file (linked-cmb.js) in the resources you downloaded at the beginning of this tutorial, so let's go ahead and edit it and within the function "getStore" you would write the following:
getStore: function(){
	var store = new Ext.data.JsonStore({
		url:'linked-cmb.php',
		root:'data',
		fields: ['value','label']
	});
	return store;
}
In here we only created a JsonStore, with the fields we defined on the server, the previous code should be easy to understand because we have used it on several occasions, but I'd like to mention that I have decided to create a function to generate a Store because I need two with the same properties, and I didn't want to rewrite the same code twice, so I just created a function that generates the stores as many time as necessary.

Creating the Linked ComBoxes

In the previous step we created a function that generates one JsonStore, so let's create two of these so we can use them with each of the combos:
this.countryStore = this.getStore();
this.stateStore = this.getStore();
The combo that will display the countries will have the following properties:
this.countryCmb = new Ext.form.ComboBox({
	store: this.countryStore,
	id: 'country',
	valueField: 'value',
	displayField: 'label',
	triggerAction: 'all',
	emptyText: 'Select a Country',
	fieldLabel: 'Country'
});
There's nothing complicated in the previous code, is just a typical configuration of a ComboBox, the next thing we need to do is create a combo that will display the states of the selected country.
this.stateCmb = new Ext.form.ComboBox({
	store: this.stateStore,
	disabled: true,		//Step 1
	id: 'state',
	valueField: 'value',
	displayField: 'label',
	triggerAction: 'all',
	mode: 'local',		//Step 2
	emptyText: 'Select a Contry first',
	fieldLabel: 'State'
});
This configuration has some differences from the previous one, these differences are very important and I will explain you why: In step one we are disabling the combo, in order to force the user to select the country first, this step is optional but improves the usability by ensuring that the user does not make mistakes. Step two is very important, if we don't assign this configuration we will have a strange behavior because by assigning the property "mode: 'local'" we ensure that there is no Ajax requests to the server when the user clicks on the combo to see the options.

Displaying the combos in a window

So far we have written code but still can not see anything on the screen, so now it's time to render the components, for this example I will use a window with the following properties:
this.window = new Ext.Window({
	title: 'Linked ComboBox',
	layout:'form',
	width:300,
	height:200,
	bodyStyle: 'padding:5px;background-color:#fff',
	items: [this.countryCmb,this.stateCmb]
});
this.window.show();
Linked ComboBoxes with ExtJS

Creation of the ComboBoxes

?

Adding the “listener”

At this point we can see the combos, the combo of countries displays the information correctly but the combo of states is disabled and we can not do anything with it. To interact with the components we need to add a "listener" to the first combo, in order to enable the combo of states when the first combo is selected and load the appropriate information.
this.countryCmb.on('select',function(cmb,record,index){	//step 1
	this.stateCmb.enable();			//step 2
	this.stateCmb.clearValue();		//step 3
	this.stateStore.load({			//step 4
		params:{
			id:record.get('value')	//step 5
		}	
	});
},this);
In step one we added a "listener" to the event "select", this event is triggered when the user selects an option from the combo, the function receives three parameters: the combo, the record and the index that has been selected. In step two we only enable the combo of states. In step three we remove the value of the combo of states, if the user has previously selected a country and state and we load new sates, the old value will be removed. En el paso tres limpiamos el valor del combo de estados, esto permitirá que si el usuario ha seleccionado anteriormente un estado, cuando se carguen nuevos estados se limpiará el valor anterior. In step four we are reloading the information of the Store of states with Ajax. In step five we pass the parameter "id" which is going to be used by the server to decided which states must be returned.
Linked ComboBoxes with ExtJS

Linked combos

Conclusions

Following the steps in this tutorial we can create linked combos on the levels we need, we just need to assign a "listener" to the event "select" of the combo and within this "listener" reload the store of the combo. Don't forget to follow us on Twitter (@quizzpot) to be updated of the new tutorials we will be publishing and also if you have any questions or suggestions feel free to leave a comment on this post.

Te gustaría recibir más tutoriales como este en tu correo?

Este tutorial pertenece al curso Learning Ext JS 3, te recomiendo revises el resto de los tutoriales ya que están en secuencia de menor a mayor complejidad.

Si deseas recibir más tutoriales como este en tu correo te recomiendo registrarte al curso, si ya eres miembro solo identifícate y registrate al curso, si no eres miembro te puedes registrar gratuitamente!

Si no gustas registrarte en este momento no es necesario! Aún así puedes recibir los nuevos tutoriales en tu correo! Jamás te enviaremos Spam y puedes cancelar tu suscripción en cualquier momento.

¿Olvidaste tu contraseña?

9Comentarios

  • Avatar-7 Frederick D. 21/11/2009

    Thank you very much for this article. This is a new method to linked combo boxes that I have not seen before. I very VERY much like the style of your tutorials where each step is clearly laid out. I also appreciate the bi-lingual approach as I am an expat viviendo en México en este momento. Have you tried this approach when editing a record that is selected from a grid? Nearly every tutorial I've worked with on combo boxes works when a record is being added to a database, via a grid button for instance, but does not retrieve the de-code value (typically the name) for the id that was selected. I worked on cracking this nut on the ExtJS forums with the thread http://www.extjs.com/forum/showthread.php?t=85356. What do you think of the approach we took on that thread? Please keep up the good work. If permitted, in the future I would like to participate in your project, por favor.

    • Avatar-2 Crysfel 23/11/2009

      Hi Frederick. We'd be grateful if you can join us and share your knowledge. About your question, I didn't understand your point, can you explain a little bit more? also, you can join us in the forums (http://foro.quizzpot.com), it is a spanish forum but you can post in english if you like. Best regards

      • Avatar-9 Ricky Baratan 19/02/2010

        I like your tutorial, JBU.

        • Avatar-9 Ahsan Murshed 28/02/2010

          Hi,nice article,but when I want to use this in asp.net 3.5 its not working. Can you give me any example for asp.net?

          • Avatar-11 Chris Love 29/12/2010

            How about hiding the child combo box until the user selects a value from the parent? How would you got about doing this. Thanks in advance :)

            • Avatar-5 Crysfel 30/12/2010

              You can use the "hide" and "show" method ;)

              • Avatar-5 codenerd 12/02/2011

                nice article,but i dunno exactly wr to use the code in between,so pls post the complete code if possible for linked combobox

                • Avatar-11 Silvia 18/11/2011

                  Thank you very much! You saved my day! :)

                  • Avatar-10 Robert 31/08/2013

                    Thanks for the details, I'm still using extjs 3.4.1 and this helped a great deal when I needed to update one recordform editor (Saki's grid editor plugin) dropdown based on the selection of another.

                    Instructor del curso

                    Crysfel3

                    Autor: Crysfel Villa

                    Software engineer with more than 7 years of experience in web development.

                    Descarga Código Fuente Ver Demostración

                    Regístrate a este curso

                    Este tutorial pertenece al curso Learning Ext JS 3, revisa todos los tutoriales que tenemos en este mismo curso ya que están en secuencia y van de lo más sencillo a lo más complicado.

                    Tendrás acceso a descargar los videos, códigos y material adicional.

                    Podrás resolver los ejercicios incluidos en el curso así como los Quizzes.

                    Llevarás un registro de tu avance.