Learning Ext JS 3

Ext JS basic forms and fields Más videos

Descripción del tema

Among the many types of panels that ExtJS offers, we have the Ext.FormPanel component, a component that provides all the functionality of a common form in HTML but with methods and specific functions of ExtJS. The component Ext.FormPanel has a default type of design ("layout") called "form", this design intelligently aligns each of the components (label-component) of the form. The unique characteristic of the Ext.FormPanel is that it already has implemented the saving and loading data process in a way that is very secure and completely configurable.

Resources

Go ahead and download the resources for this tutorial, unzip the file and create a folder called "forms" inside of the folder "course" (which is the folder we've been working on), then copy the files you unzipped to the new folder. The goal is that by the end of the chapter "Forms", we have a form that works perfectly with all relevant features and validations.

Packaging the tutorial

We need to package the code to avoid conflicts with other variables.
 
Ext.ns('com.quizzpot.tutorial');

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

com.quizzpot.tutorial.FormTutorial = {
	init: function(){
		//code here
	}	

}

Ext.onReady(com.quizzpot.tutorial.FormTutorial.init,com.quizzpot.tutorial.FormTutorial);

Form

Now we will build a form with the most common fields; two text fields, a checkbox group, a hidden field, a group of radio buttons and two buttons. First we need to create a form where the fields will be set so the user can enter the necessary information, we do this as follows:
//creamos un formulario 
this.form= new Ext.FormPanel({ 
	title:'New Developer', 
	renderTo: 'frame', 
	defaults:{xtype:'textfield'},	//component by default of the form
	bodyStyle:'padding: 10px', //adding padding for the components of the form
	html: 'This form is empty!' //<-- in the next step we will remove this property
});
The forms inherit properties and methods from the component "Ext.Panel", that's why the configuration we've made looks familiar, if you can't remember about this then I suggest you to take a look at the chapter "Panels". With the property "defaults" we can define the properties we want to be applied on the components that the Form component has, in this case we just define the "xtype" to "textfield", this means that the default fields of this form will be Texfields. The previous code generates the following screen:
Empty Form Image

Empty Form

At this point there is no visual difference between a form and a panel, this is because we haven't added any field yet, let's see in detail the most common components below.

Text fields

As seen in previous tutorials, we can create components using the keyword "new" and the component we need to instantiate, or we can create them through configuration objects using the property "xtype" to distinguish between the available components. The component that lets us create text boxes is "Ext.form.TextField" and the "xtype" is "textfield", for example:
 
//creating an instance of textfield
var name = new Ext.form.TextField({ 
	fieldLabel:'Name', 
	name:'txt-name', 
	emptyText:'Your name...', 
	id:"id-name" 
}); 

//creating a form
this.form= new Ext.FormPanel({ 
	title:'New Developer', 
	renderTo: 'frame', 
	defaults:{xtype:'textfield'},	//component by defaul of the form
	bodyStyle:'padding: 10px', //adding padding for the components of the form		 
	items:[ 
		name, //adding the instance we created previously
		{ 
			fieldLabel:'Email', // we can create a component 
			name:'txt-email', // with a configuration
			value:'default@quizzpot.com', //object
			id:"id-email" 
		} 
	] 
});
In the previous code we've created two text fields in two different ways, one using an instance of the TextField component and the other one is using a configuration object, each developer can choose the option that suits him/her better depending on the circumstances.
Textfields image

Textfields

In the following list I will mention the properties that we use: "fieldLabel": This property defines the text that accompanies each component of the form. "emptyText": This property defines the text that the field will contain when it is empty. "name": is the name by which the data (that contains the fields) is sent to the server, is exactly like the "name" we normally use in common forms. "value": is the default value that appears in the component, useful when we want to edit a record and display information that is currently captured.

Checkbox

The checkboxes are used to select one or more items from a list, or simply to activate or deactivate any flag or permission in a system, for this example I'll put a field that is called "active" using a configuration object, we can also do this by instantiating the component "Ext.form.Checkbox".
 
// code remove to keep the it simple...

//creating a form
this.form= new Ext.FormPanel({ 
	title:'New Developer', 
	renderTo: 'frame', 
	defaults:{xtype:'textfield'},	
	bodyStyle:'padding: 10px', 		 
	items:[ 
		name, 
		{ 
			fieldLabel:'Email', 
			name:'txt-email', 
			value:'default@quizzpot.com', 
			id:"id-email" 
		},{ 
			xtype: 'checkbox', //defining the type of component
			fieldLabel: 'Active',//assigning a label
			name: 'chk-active', //and a "name" so we can retrieve it in the server... 
			id: 'id-active'// ...when the form is sent
		} 
	] 
});
On the other hand, when we want to group multiple check boxes we need to use the component "Ext.form.CheckboxGroup" which allows an easy handling of any number of checkboxes.
 
//creating a group of checkboxes
var checkboxes = new Ext.form.CheckboxGroup({ 
	fieldLabel:'Interests', 
	columns:2,//showing two columns of checkboxes						 
	items:[ 
		{boxLabel: 'JavaScript', name: 'cb-js', checked: true}, //field checked from the beginning
		{boxLabel: 'HTML', name: 'cb-html'}, 
		{boxLabel: 'CSS', name: 'cb-css'}, 
		{boxLabel: 'Otros', name: 'cb-otros'} 
	] 
});

//creating a form
this.form= new Ext.FormPanel({ 
	title:'New Developer', 
	renderTo: 'frame', 
	defaults:{xtype:'textfield'},	
	bodyStyle:'padding: 10px', 	 
	items:[ 
		name, 
		{ 
			fieldLabel:'Email', 
			name:'txt-email',
			value:'default@quizzpot.com',
			id:"id-email" 
		},{ 
			xtype: 'checkbox', //defining the type of component
			fieldLabel: 'Active',//assigning a label
			name: 'chk-active', //and a "name" so we can retrieve it in the server... 
			id: 'id-active'// ...when the form is sent
		}, 
		checkboxes //<-- group of checkboxes 
	] 
});
Imagen de checkboxes

Checkboxes with ExtJS

The groups of checkboxes accept the property "items" which should contain an array of configuration objects or instances of the checkbox.

Radio buttons

The radio buttons are used to select a single choice of several items, this component is created very similar to the checkboxes, except that we use the component "Ext.form.RadioGroup" to group multiple radios.
 
//code remove to keep it simple

//creating a group of radiobuttons 
var radios = new Ext.form.RadioGroup({ 
	fieldLabel: 'Favorite Framework',		                
     columns: 2, //display the radiobuttons in two columns 
     items: [ 
          {boxLabel: 'Ext Js', name: 'framework', inputValue: 'Ext js', checked: true}, 
          {boxLabel: 'Dojo', name: 'framework', inputValue: 'Dojo'}, 
          {boxLabel: 'Mootools', name: 'framework', inputValue: 'Mootools'}, 
          {boxLabel: 'jQuery', name: 'framework', inputValue: 'jQUery'}, 
          {boxLabel: 'prototype', name: 'framework', inputValue: 'prototype'}, 
          {boxLabel: 'YIU', name: 'framework', inputValue: 'yui'} 
     ] 
}); 

//creating a form
this.form= new Ext.FormPanel({ 
	title:'New Developer', 
	renderTo: 'frame', 
	defaults:{xtype:'textfield'},	
	bodyStyle:'padding: 10px', 			 
	items:[ 
		name, 
		{ 
			fieldLabel:'Email', 
			name:'txt-email', 
			value:'default@quizzpot.com', 
			id:"id-email" 
		},{ 
			xtype: 'checkbox',
			fieldLabel: 'Active',
			name: 'chk-active',
			id: 'id-active'
		}, 
		checkboxes,
		radios // <-- group of radio buttons
	] 
});
Radiobuttons Image

Group of Radiobuttons

Typically the radios are used together, but if for some strange reason you only need one or instead of using configuration objects in the property "items" of the RadioGroup you want to put instances, you can use the component “Ext.form.Radio”.

Hidden fields

The hidden fields are useful to send information to the server that the user doesn't need to know, such as "id" of the record being edited, or a security token, and so on. ExtJS has the component “Ext.form.Hidden” which allows us to achieve this functionality.
 
//code remove to keep it simple

//creating a form
this.form= new Ext.FormPanel({ 
	title:'New Developer', 
	renderTo: 'frame', 
	defaults:{xtype:'textfield'},	
	bodyStyle:'padding: 10px', 	 
	items:[ 
		name, 
		{ 
			fieldLabel:'Email',
			name:'txt-email', 
			value:'default@quizzpot.com',
			id:"id-email" 
		},{ 
			xtype: 'checkbox', 
			fieldLabel: 'Active',
			name: 'chk-active',
			id: 'id-active'
		}, 
		checkboxes, 
		radios,
		{ 
		    	xtype:'hidden',//<--hidden field
		    	name:'h-type', //name of the field sent to the server
		    	value:'developer'//value of the field
		}	 
	] 
});
It is really important to define the property "name" and property "value" to assign the content to the variable that will be sent to the server, we can additionally assign an "id" so we can modify the value easily later on.

Button on the Form

We can assign buttons to the form that when pressed they'll perform the operations defined, for now I'm only going to create buttons with no actions.
 
//creating a form 
this.form= new Ext.FormPanel({ 
	title:'New Developer', 
	renderTo: 'frame', 
	defaults:{xtype:'textfield'},
	bodyStyle:'padding: 10px', 			 
	items:[ 
		name,
		{ 
			fieldLabel:'Email', 
			name:'txt-email', 
			value:'default@quizzpot.com', 
			id:"id-email" 
		},{ 
			xtype: 'checkbox', 
			fieldLabel: 'Active',
			name: 'chk-active',
			id: 'id-active'
		}, 
		checkboxes, 
		radios, 
		{ 
		    	xtype:'hidden',
		    	name:'h-type', 
		    	value:'developer'
		} 
	], 
	buttons:[{text:'Save'},{text:'Cancel'}] //<-- button of the form
});
Buttons Image

Button in a Form

We can align the position of the buttons to the right, left or center, by default they're aligned to the center, but with the property “buttonAlign” we can define where the buttons are going to be displayed. To align the buttons to the right we would do the following:
 
//creating a form 
this.form= new Ext.FormPanel({ 
	title:'New Developer', 
	renderTo: 'frame', 
	defaults:{xtype:'textfield'}, 
	bodyStyle:'padding: 10px', 			 
	items:[ 
		name, 
		{ 
			fieldLabel:'Email', 
			name:'txt-email',
			value:'default@quizzpot.com', 
			id:"id-email" 
		},{ 
			xtype: 'checkbox', 
			fieldLabel: 'Active',
			name: 'chk-active', 
			id: 'id-active'
		}, 
		checkboxes, 
		radios, 
		{ 
		    	xtype:'hidden',
		    	name:'h-type', 
		    	value:'developer'
		} 
	], 
	buttonAlign: 'right', //<--buttons aligned to the right
	buttons:[{text:'Save'},{text:'Cancel'}] //button of the form
});
Image of the buttons aligned

Buttons aligned to the right

Window that contains the form

Just for visual purposes, let's use a window to contain the form, so it is necessary to remove the property “renderTo: 'frame'” and insert the form inside the window that we'll create, we will also move the buttons to the window, the title and body style as follows:
 
//creating a form 
this.form= new Ext.FormPanel({ 
	border:false, // <-- removing the border of the form
	defaults:{xtype:'textfield'},	//component by default of the form
	items:[ 
		name, //assigning the instance we created previously
		{ 
			fieldLabel:'Email', // creating a field
			name:'txt-email', // using a 
			value:'default@quizzpot.com', //configuration 
			id:"id-email" 
		},{ 
			xtype: 'checkbox', //defining the type of component
			fieldLabel: 'Active',//assigning a label
			name: 'chk-active',//and a "name" to retrieve it on the server... 
			id: 'id-active'// ...when the form is sent 
		}, 
		checkboxes, //group of checkboxes 
		radios, // group of radios 
		{ 
		    	xtype:'hidden',//hidden field(hidden) 
		    	name:'h-type', //name of the field sent to the server
		    	value:'developer'//value of the field
		} 
	] 
}); 

//creating the window that will contain the form
var win = new Ext.Window({ 
	title: 'New Developer', 
	width:300, 
	height:300, 
	bodyStyle:'background-color:#fff;padding: 10px', 
	items:this.form, //assigning the form
	buttonAlign: 'right', //buttons aligned to the right
	buttons:[{text:'Save'},{text:'Cancel'}] //buttons of the form
}); 

win.show();
Window with a form image

Window with a form

Conclusions

Today we have learned how to create a form very easy and simple, you can download the complete code at the top right of this page. In the next tutorial we'll see how to add a combo box with data loaded locally and remotely to our form and also we'll add some more fields that ExtJS provides us. Don't forget to leave your questions of suggestions at the comment's section 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?

35Comentarios

  • Avatar-6 Chan 15/10/2009

    Great tutorials.....please continue your good work!!!

    • Avatar-1 Okee 06/11/2009

      that is cool

      • Avatar-12 N00bUser 10/12/2009

        Great job!

        • Avatar-3 tot2ivn 26/02/2010

          Thanks a lot for the tut. Saved me quite amount of time w ExtJS form. :)

          • Avatar-3 Robert 24/03/2010

            How would you get the field labels to appear closer to it corresponding field. .. rather than

            • Avatar-12 Alex 09/04/2010

              You can use the 'labelStyle' config option to set the label width. Example: { xtype:'textfield', labelStyle:'width:200px;' } If you want all your fields to be the same width, you can use the 'defaults' config option of the form to apply the same configuration on all child items. Example: new Ext.FormPanel({ defaults:{ labelStyle:'width:200px;' }, items:[ { xtype:'textfield' } ] });

              • Avatar-2 karthick 25/05/2010

                Very helpful...thanks

                • Avatar-9 Doni 07/06/2010

                  what about checkbox in comboBox. How to do that

                  • Avatar-1 agnes 09/08/2010

                    Hello, how to change the alignment of the text inside the button, for example i would like to have OK text on the right of the button,can anybody help me?

                    • Avatar-8 Arun 15/08/2010

                      How can I move the label for a textfield to always appear above the textfield instead of on the left?

                      • Avatar-9 Joydeep 23/08/2010

                        How all the form fields can be accessed ?

                        • Avatar-8 Crysfel 23/08/2010

                          You can get the values of all fields like this: <pre name="code" class="javascript"> this.form.getForm().getValues(); </pre>

                          • Avatar-4 You Cab 06/10/2010

                            how to get value from checkbox using post method? i'm using php. thx

                            • Avatar-3 naveen 16/11/2010

                              Hi, I have a html select converted to extJS combobox using transform attribute. How can I access the transformed elements to set some values programatically? Thanks

                              • Avatar-1 vijay 21/01/2011

                                very nice....each n every even minor things also covered.....go ahead please....thnks

                                • Avatar-2 Gautam 25/01/2011

                                  Excellent ExtJs tutorial. Please keep writing.

                                  • Avatar-10 Imran 02/02/2011

                                    What about to use textarea?

                                    • Avatar-7 neki chan 09/02/2011

                                      simply useful. thanks alot ! :D

                                      • Avatar-2 enmn 01/03/2011

                                        create, but i how to get all field names???

                                        • Avatar-1 Crysfel 01/03/2011

                                          In order to get all fields and their values you need to do this: form.getForm().getValues();

                                          • Avatar-2 kiran 22/03/2011

                                            I need to set fieldDescription dynamically using the js .. can anyone help on this

                                            • Avatar-12 Tamil Selvam .P 10/06/2011

                                              Hi Team, I am new to ExtJs, I able to design login page with extjs, and using with spring and hibernate, i am not able to get return value, Like. If user name and password are valid page should be redirect, If is not valid, error should pass in same page. Please help me. Regards, Tamil Selvam .P

                                              • Avatar-1 Anoop 16/06/2011

                                                Hi. I would like to have my form fields( text box, combo and an image in same row and two such rows) and how can i do this using exts JS. i tried different layouts. but not working. could you please help? Thanking you in advance, Anoop

                                                • Avatar-1 Wilder 24/06/2011

                                                  Donde esta el enlace acceder a los tutoriales?

                                                  • Avatar-1 RAFF 27/06/2011

                                                    Excellent tutorial!!! Good job!

                                                    • Avatar-5 Raj Kapoor 20/07/2011

                                                      I have a requirement to display input text fields along with radio buttons, something like this scenario To display a radio group with 2 options of 'Make' and 'Model' of a car, with input text next to each radio option to input either make or model. Any ideas for a solution?

                                                      • Avatar-7 Rashmi 21/07/2011

                                                        Superb tutorials. Thanks a lot!!!!!!!!

                                                        • Avatar-2 Tom 27/09/2011

                                                          how can we move textbox beneath the lable in extjs.

                                                          • Avatar-9 Alana 30/11/2011

                                                            The align button don't work. The buttons is always align in the left. Any ideas for a solution?

                                                            • Avatar-12 Arun 27/03/2012

                                                              thank you very much.. its useful

                                                              • Avatar-9 sergiu 01/06/2012

                                                                Great job ! thanks

                                                                • Avatar-10 nancy 02/07/2012

                                                                  Does anyone know how to reduce the gap between the fieldLabel and the component? (let's say a combobox) Thanks!

                                                                  • Avatar-8 jenifer 13/07/2012

                                                                    Quite informative... Keep blogging such useful materials.

                                                                    • Avatar-1 mani 11/07/2013

                                                                      Hi, How to assign one of the textbox values to other textbox's field names?

                                                                      • Avatar-11 Johnb0 31/08/2016

                                                                        Thanks for this article. I'd also like to express that it can often be hard if you are in school and simply starting out to initiate a long credit standing. There are many students who are just trying to endure and have an extended or favourable credit history are often a difficult matter to have. ecadedeagbgf

                                                                        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.