Learning Ext JS 3

Combo box loaded dynamically and remotely Más videos

Descripción del tema

Today we will talk about a very complete component: the ComboBox. We will see how to configure a Combo Box locally and remotely. I will describe some of the properties used in the configuration, we will create a template so our ComboBox will have a nice format and finally we will see the different variations that ExtJS offers for the ComboBox, for example the TimeField.

Resources

Before you start this tutorial, you need to download the resources. Remember that this tutorial is part of the chapter Form, and end of the tutorial we will add our ComboBox to the form we created in the previous tutorial, but to avoid some confusion we'll do this tutorial in a separate file.

Packaging the tutorial.

Let's package our code before we start.
Ext.ns('com.quizzpot.tutorial');

Ext.BLANK_IMAGE_URL = '../ext-3.0/resources/images/default/s.gif';

com.quizzpot.tutorial. ComboBoxTutorial= {
	init: function(){
		//code for the tutorial goes here
       }
}
Ext.onReady(com.quizzpot.tutorial. ComboBoxTutorial.init,com.quizzpot.tutorial. ComboBoxTutorial);

Window

At this moment we're going to create a window that will contain different types of ComboBox. This window will display the different ComboBoxes we will create in this tutorial.
var win=new Ext.Window({
	title: 'ComboBox example',
	bodyStyle:'padding: 10px',		//adding padding to the components
	width:400,
	height:360,			
	layout:'form'			//organization of the components
});
win.show();
We can highlight the property "layout:'form'" from the code above, because for a window the layout by default is "auto", so we needed to overwrite the property to display the components distributed as a form.
Window

Window that will contain the ComboBox

Local ComboBox

After creating the window, let's create our ComboBoxes; the first thing we need is the data that will be loaded into our ComboBox, the simplest way to load data into our ComboBox is using an array.
var data=['Code Igniter','Cake Php','Symfony','Zend'];

var comboLocal =new Ext.form.ComboBox({
	fieldLabel:'Frameworks PHP',
	name:'cmb-data',
	forceSelection:true,
	store:data,
	emptyText:'Select a framework...',
	triggerAction: 'all',
	//hideTrigger:true,
	editable:false,
	//minChars:3					
});
The above code creates a ComboBox with data naming some existing PHP Frameworks. Let's see the meaning of the properties that we can use to configure our ComboBox: forceSelection: This option forces the user to select a value from the combo, this is independent of the type of validation allowBlank, which we will discuss in the next tutorial. store: is the data source that our combo will show, we've talked about this component previously. emptyText: this is the text displayed when we haven't selected anything in our combo. triggerAction: this option indicates the action to execute when the trigger is clicked. editable: the combo can not be edited, which means you can not write any value on it. hideTrigger: setting this property to true we make the combo to be displayed without the small down arrow icon ("trigger"). minChars: it tells us how many characters we must write before the combo starts to display information, in our case we must comment the editable property and not comment the property minChars to see its functionality. Let's add the ComboBox to our window:
var win=new Ext.Window({
	bodyStyle:'padding: 10px',//adding padding to the components
	width:400,
	height:360,
	items: comboLocal, //adding the combo to the window
	layout:'form'		//organization of the components
});
win.show();
Simple Combo

A Combo loaded with local information

Remote ComboBox

Now let's create a combo that we will load with data remotely using Ajax. On this occasion we will use PHP, but as we know we can use any server language. In the remote ComboBox we will use for our source of data a JSON type store, I won't explain this component because we already talked about it in previous tutorials. The JS code will go like this:
//se crea el store
var store= new Ext.data.JsonStore({
		url:'combo.php',
		root: 'data',					
		totalProperty: 'num',
		fields: [
			{name:'name', type: 'string'},
			{name:'desc', type: 'string'},
			{name:'logo', type: 'string'},
		]
});

//creating the combo and assigning the store
var comboRemote=new Ext.form.ComboBox({
	fieldLabel:'Data Base',
	name:'cmb-DBs',
	forceSelection: true,
	store: store, //assigning the store
	emptyText:'pick one DB...',
	triggerAction: 'all',			
	editable:false,
	displayField:'name',
        valueField: 'name'	
});
As you can see in the properties of our combo we added the property displayField, with this property we tell the ComboBox the information to display, in this case is going to show only the data 'name' and using the property "valueField" we specify which field the store is going to use as a "value", it can be a numeric ID but in this case we use the name. Finally we need to add the combo we just created to the window, as follows:
var win=new Ext.Window({
	title: 'ComboBox example',
	bodyStyle:'padding: 10px',		//adding padding to the components
	width:400,
	height:360,
	items: [comboLocal,comboRemote],//adding the remote combo
	layout:'form'					//organization of the components
});
win.show();
Remote Combo

A ComboBox loaded remotely using Ajax

With PHP code we're going to present the information to display the combo, this information can come from a database or a Web Service, to make things simple and understandable the information is "hardcoded" in arrays.
<?php
	$dataDB = array(
				array(
					"name"=>"MySQL",
					"desc"=>"The world's most popular open source database",	
					"logo"=>"mysql.png"
				),
				array(
					"name"=>"PostgreSQL",
					"desc"=>"The world's advanced open source database",					
					"logo"=>"postgresql.png"
				),
				array(
					"name"=>"Oracle",
					"desc"=>"The world's largest enterprise software company",
					"logo"=>"oracle.png"				
				),
	);
	
	$o = array(
			"num"=>count($dataDB),			
			"data"=>$dataDB
		);
	echo json_encode($o);
?>
As you can see, we have defined the fields the JsonStore accepts, also with the function json_decode we are generating the JSON from a PHP array.

Formatted Data

Okay now let's give a format to our information, we will use the information from our remote combo, so let's get started. Let's create a new ComboBox that will be loaded with the same data that the PHP code provides, using the same store as the previous combo. To format our ComboBox we need a template, so we're going to assign the template to our new combo by using one of its properties ( "tpl" of "template"). The template is written in HTML with some CSS so the information is display in detail.
var comboRemoteTpl = new Ext.form.ComboBox({
	fieldLabel:'Data Base',
	name:'cmb-Tpl',
	forceSelection:true,
	store:store,
	emptyText:'pick one DB...',
	triggerAction: 'all',
	mode:'remote',
	itemSelector: 'div.search-item',
	tpl: new Ext.XTemplate('<tpl for="."><div class="search-item" style="background-image:url({logo})"><div class="name">{name}</div><div class="desc">{desc}</div></div></tpl>'),						
	displayField:'name'
});
The properties that appear now are: tpl: assigns a template to display each data of the combo, the template created is a string of HTML and some CSS styles and classes; in future tutorials we will talk about more on the functionality of the object "Ext.XTemplate", so for now is only worth mentioning that with a loop we go through all the records in the store and generate a list of options for the user. itemSelector: this property tells us which property of the DOM is going to trigger the "select" event of our combo. So far we have modified the HTML of the drop-down list of the combo, what we need to do now is set the styles needed like this:
	.search-item{
		border:1px solid #fff;
		padding:3px;
		background-position:right bottom; 
		background-repeat:no-repeat;
	}
	.desc{	
		padding-right:10px;
	}
	.name{	
		font-size:16px !important;
		color:#000022;	
	}
Customized Combo

ComboBox customized with a template

A variation of the ComboBox

There's a component that ExtJS that is a variation of the ComboBox, this component is called TimeField and is useful to display values dealing with time. The majority of the properties are the same as the ComboBox.
var timeField=new Ext.form.TimeField({						
       	fieldLabel: 'Time Field',
       minValue: '4:00',
       maxValue: '23:59',
       increment: 15,
       format:'H:i',
       name:'cb-time'						
});
TimeField Combo

A Combo with time

As we can see, we have created a new ComboBox that shows data in time format without any problems. Let me explain some of its properties: minValue: is the minimal value that will be shown in our field. maxValue: is the maximum value that will be shown. increment: the number of minutes between each time value in the list. format: the format of the time we're going to display.

Conclusions

Today we saw a very complete component called ComboBox, this component has many different types of configurations that make it a very used component in all kinds of applications with Ext JS. To see more benefits of this component do not forget to check the ExtJS API Documentation. If you have any questions or suggestion don't forget to leave a comment and follow us on Twitter (@quizzpot) to be updated.

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?

11Comentarios

  • Avatar-11 Frederick D. 13/11/2009

    Very nice! I like this site a great deal. Excellent progressive style for the tutorials. Do you know if a follow-up tutorial is planned for linked combo boxes where a listener is involved in the parent that filters the child combo box? I am struggling with this now for my CakePHP app with an ExtJS front end. Thanks! Keep up the good work!

    • Avatar-12 Hazel 19/11/2009

      Hi Frederick! Thanks for leaving a comment, we've just published a new tutorial about <a href="http://www.quizzpot.com/2009/11/linked-comboboxes-with-extjs/" rel="nofollow">Linked ComboBoxes</a>, you should check it out ;)

      • Avatar-1 ruel 15/03/2010

        the js is empty!...

        • Avatar-8 ruel 15/03/2010

          combo js is empty

          • Avatar-9 Crysfel 15/03/2010

            Thats true, you need to download the source code here: http://www.quizzpot.com/wp-content/uploads/2009/06/combobox-src.zip

            • Avatar-3 Sapan 11/04/2011

              Hi, Great Job indeed! But I have a small doubt I want to fill the ComboBox as provided by Java. Do you know how can I pass parameters/values from Java to js file for filling the comboBox entries. Any help will be deeply appreciated. Thanks.

              • Avatar-5 bomber jackets 26/10/2011

                What a frankly incredible blog post!!!

                • Avatar-8 Crysfel 21/11/2011

                  Thank you, we are not writing english tutorials here, so you should go to the http://www.bleext.com/blog where we are writing in english on Ext4 :)

                  • Avatar-9 Merchandise 06/12/2011

                    I dont disagree with you!

                    • Avatar-12 Andrew 08/12/2011

                      Please help me , how can I do auto select like countries , regions, from combobox and after send ID (value) not text ? :)

                      • Avatar-5 Tabitha 09/09/2012

                        I am truly grateful to the owner of this web site who has shared this wonderful post at at this place.

                        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.