<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Quizzpot &#187; English</title>
	<atom:link href="http://www.quizzpot.com/category/en/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.quizzpot.com</link>
	<description>Cursos en video gratuitos</description>
	<lastBuildDate>Wed, 21 Jul 2010 20:19:46 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Show information from an XML file</title>
		<link>http://www.quizzpot.com/2010/01/show-information-from-an-xml-file/</link>
		<comments>http://www.quizzpot.com/2010/01/show-information-from-an-xml-file/#comments</comments>
		<pubDate>Mon, 25 Jan 2010 20:23:58 +0000</pubDate>
		<dc:creator>Crysfel</dc:creator>
				<category><![CDATA[English]]></category>
		<category><![CDATA[Ext JS]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://www.quizzpot.com/?p=2230</guid>
		<description><![CDATA[Today I will show how to load information into a grid from an XML file, this is something very easy to do and useful when developing applications.]]></description>
			<content:encoded><![CDATA[<h3>Resources</h3>
<p>To continue we need to download the <a href="http://www.quizzpot.com/wp-content/uploads/2009/07/gridxml.zip">resources</a>, and copy the three files within our <a href="http://www.quizzpot.com/2009/03/basic-installation-of-the-framework/">Web server</a>, we have been working inside the folder &#8220;course&#8221; where we already have the Ext JS library and we already created a folder called &#8220;grids&#8221; for this chapter.</p>
<p>I have prepared a <a href="http://www.quizzpot.com/demos/extjs/grids/gridxml.html">demo</a> to show you what we&#8217;re going to do in this tutorial.</p>
<p><!-- imagen 1 --></p>
<div class="example"><img src="http://www.quizzpot.com/wp-content/uploads/2009/07/xmlgrid.jpg" alt="gridpanel" />
<p>Final example</p>
</div>
<h3>Packaging the code</h3>
<p>We know that packaging our code is really important and is a good practice, so let&#8217;s create the namespace for this tutorial.</p>
<pre name="code" class="javascript">
Ext.ns('com.quizzpot.tutorial');

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

Ext.onReady(com.quizzpot.tutorial.GridXmlTutorial.init,com.quizzpot.tutorial.GridXmlTutorial);
</pre>
<h3>The XML we&#8217;re going to use</h3>
<p>We will use XML as our data source, such data may be contained in a database, Web service, file, etc..To make things simpler in this example I have put information directly in the source code as follows:</p>
<pre name="code" class="xml">
&lt;?php
	header(&quot;Content-Type: text/xml&quot;); 

	echo '&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;';
?&gt;

&lt;people&gt;
	&lt;person&gt;
		&lt;name&gt;Jack Slocum&lt;/name&gt;
		&lt;age&gt;32&lt;/age&gt;
		&lt;position&gt;Chief Software Architect and Founder&lt;/position&gt;
		&lt;company&gt;Ext JS&lt;/company&gt;
	&lt;/person&gt;
	&lt;person&gt;
		&lt;name&gt;Sasha Cohen&lt;/name&gt;
		&lt;age&gt;24&lt;/age&gt;
		&lt;position&gt;Figure Skating&lt;/position&gt;
		&lt;company&gt;&lt;/company&gt;
	&lt;/person&gt;
	&lt;person&gt;
		&lt;name&gt;John Resig&lt;/name&gt;
		&lt;age&gt;24&lt;/age&gt;
		&lt;position&gt;JavaScript Developer&lt;/position&gt;
		&lt;company&gt;Mozilla Corporation&lt;/company&gt;
	&lt;/person&gt;
	&lt;person&gt;
		&lt;name&gt;Sara Mcfly&lt;/name&gt;
		&lt;age&gt;35&lt;/age&gt;
		&lt;position&gt;Tester&lt;/position&gt;
		&lt;company&gt;Google&lt;/company&gt;
	&lt;/person&gt;
	&lt;person&gt;
		&lt;name&gt;Crysfel Villa&lt;/name&gt;
		&lt;age&gt;25&lt;/age&gt;
		&lt;position&gt;Software Developer&lt;/position&gt;
		&lt;company&gt;JWM Solutions&lt;/company&gt;
	&lt;/person&gt;
	&lt;person&gt;
		&lt;name&gt;Felicia Day&lt;/name&gt;
		&lt;age&gt;30&lt;/age&gt;
		&lt;position&gt;Actress&lt;/position&gt;
		&lt;company&gt;&lt;/company&gt;
	&lt;/person&gt;
	&lt;person&gt;
		&lt;name&gt;Collis Ta'eed&lt;/name&gt;
		&lt;age&gt;29&lt;/age&gt;
		&lt;position&gt;CEO&lt;/position&gt;
		&lt;company&gt;Envato&lt;/company&gt;
	&lt;/person&gt;
&lt;/people&gt;
</pre>
<h3>The record “Person”</h3>
<p>We&#8217;re going to display the information in XML on the grid, these are facts of people, therefore we need to create the record &#8220;Person&#8221; and map it to the node &#8220;person&#8221; of XML.</p>
<pre name="code" class="javascript">
var Person = Ext.data.Record.create([
	{name: 'name'},
	{name: 'position'},
	{name: 'age', type:'float'},
	{name: 'company'}
]);
</pre>
<h3>Creating the “Reader”</h3>
<p>Now let&#8217;s create the &#8220;reader&#8221; that will be assigned to the &#8220;store&#8221;:</p>
<pre name="code" class="javascript">
var reader = new Ext.data.XmlReader({
	record: "person"
}, Person);
</pre>
<p>In the previous code we have defined in the configuration of the XmlReader, the property &#8220;record&#8221; with the value &#8220;person&#8221;, by doing this the &#8220;reader&#8221; will be able to go to the node &#8220;person&#8221; (in XML) and retrieve the information contained in the object &#8220;Person&#8221;.</p>
<h3>Creating the Store and loading information</h3>
<p>The next step is to create the &#8220;Store&#8221; and load the XML information like this:</p>
<pre name="code" class="javascript">
var store = new Ext.data.Store({
	url: 'xml.php',
	reader: reader
});

store.load();
</pre>
<p>First we define the &#8220;url&#8221; where we&#8217;re going to search for the XML using Ajax, in the second configuration parameter we assigned the &#8220;reader&#8221; to the &#8220;Store&#8221;.</p>
<p>Once created the store we can use the method &#8220;load&#8221; to make the &#8220;Ajax&#8221; request and receive the information.</p>
<p>So far we have only defined the data source by making the necessary configurations. If you still have doubts about the &#8220;Store&#8221;, I recommend you to read <a href="http://www.quizzpot.com/2009/06/reading-information-in-xml/">the tutorial</a> where we talked specifically about this component.</p>
<h3>Creating the Grid</h3>
<p>Once we have the information ready to display it in the table, we can start creating the grid as follows:</p>
<pre name="code" class="javascript">
var grid = new Ext.grid.GridPanel({
	store: store, //assigning the data source
	columns: [ //creating the columns
		new Ext.grid.RowNumberer(), //numbering the rows
		{header:'Name', dataIndex:'name',sortable: true},
		{header:'Company', dataIndex:'company',sortable: true},
		{header:'Position', dataIndex:'position',width:230,sortable: true},
		{header:'Age', dataIndex:'age', width:40,sortable: true}
	],
	border: false, //removing the bordering
	stripeRows: true //assigning the stripes to the rows
});
</pre>
<p>With this simple configuration we created a very basic but attractive table, we have studied the code in the previous tutorial, but I will review the properties used in this grid:</p>
<p>“store”: This property defines the data source used in the grid.<br />
“columns”: we define the columns that the grid will have, this part is really important because we link the columns with the information that is going to be displayed (dataIndex).<br />
“border”: This property is inherited from the component Panel and by assigning the value &#8220;false&#8221; we remove the border, we do this because we put the grid in a window.<br />
“stripeRows”: By assigning the value &#8220;true&#8221; we stripe the rows this will make it easy to see the information, by default is &#8220;false&#8221;.</p>
<h3>Creating the window</h3>
<p>Finally, let&#8217;s put the grid inside of a window:</p>
<pre name="code" class="javascript">
var win = new Ext.Window({
	title: 'Grid example',
	layout: 'fit', // <---
	width: 510,
	height:350,
	items: grid
});

win.show();
</pre>
<p>The only important thing in this setting and we probably do not know (if we have taken this course from the beginning) is the setup "layout" to whom we are assigning the value "fit", this value will display the table occupying one hundred percent of the window, otherwise the grid will not be displayed completely, but I will talk about the layouts in the future tutorials.</p>
<p><!-- imagen 1 --></p>
<div class="example"><img src="http://www.quizzpot.com/wp-content/uploads/2009/07/xmlgrid.jpg" alt="gridpanel" />
<p>If all went well, you should see this screen</p>
</div>
<h3>Conclusions</h3>
<p>We have seen how easy it is to display information from a XML into a grid, we also appreciated the engineering implement on the Ext JS library, because the creation of the grid is the same for the different formats (XML, JSON, Array), the only thing we changed was the "Store" and the grid works the same, this is an advantage in terms of the maintenance of systems is concerned.</p>
<p>If you have any questions or suggestions feel free to leave a comment in this post, also don't forget to subscribe to <a href="http://feeds2.feedburner.com/quizzpot-en">our feeds</a> or follow us on <a href="http://twitter.com/quizzpot">Twitter (@quizzpot)</a> to be updated.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.quizzpot.com/2010/01/show-information-from-an-xml-file/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Binding information from an array to a grid</title>
		<link>http://www.quizzpot.com/2010/01/binding-information-from-an-array-to-a-grid/</link>
		<comments>http://www.quizzpot.com/2010/01/binding-information-from-an-array-to-a-grid/#comments</comments>
		<pubDate>Mon, 11 Jan 2010 16:50:20 +0000</pubDate>
		<dc:creator>Hazel</dc:creator>
				<category><![CDATA[English]]></category>
		<category><![CDATA[Ext JS]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://www.quizzpot.com/?p=2222</guid>
		<description><![CDATA[One of the most interesting components from ExtJS are the grids, which provide us the ability to display information in a simple and orderly way.]]></description>
			<content:encoded><![CDATA[<p>In this tutorial we will learn how to use the components of a basic GridPanel such as DataStore (or data repository), ColumnModel, and SelectionModel.</p>
<h3>Packaging the tutorial</h3>
<p>Let&#8217;s package the code first, to avoid conflicts with other variables.</p>
<pre name="code" class="javascript">
Ext.ns('com.quizzpot.tutorial');   

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

com.quizzpot.tutorial.ArrayGridTutorial = {
    init: function(){
        //The code of the tutorial goes here
    }
}   

Ext.onReady(com.quizzpot.tutorial.ArrayGridTutorial.init,com.quizzpot.tutorial.ArrayGridTutorial);
</pre>
<h3>The Store</h3>
<p>The next thing we need to do is define the data repository, which is where we will retrieve the data, in this case we are going to work with static data stored in a two-dimensional array like this:</p>
<pre name="code" class="javascript">
//Two-dimensional array
var myData = [
	['3m Co',71.72,0.02,0.03,'9/1 12:00am'],
	['Alcoa Inc',29.01,0.42,1.47,'9/1 12:00am'],
	['Altria Group Inc',83.81,0.28,0.34,'9/1 12:00am'],
	['American Express Company',52.55,0.01,0.02,'9/1 12:00am'],
	['American International Group, Inc.',64.13,0.31,0.49,'9/1 12:00am'],
	['AT&#038;T Inc.',31.61,-0.48,-1.54,'9/1 12:00am'],
	['Boeing Co.',75.43,0.53,0.71,'9/1 12:00am'],
	['Caterpillar Inc.',67.27,0.92,1.39,'9/1 12:00am']
];
</pre>
<p>Now, let&#8217;s define an &#8220;Ext.data.ArrayStore&#8221; that will be responsible for reading the data array, in order to do this we need to set the reference name of the data column and the type of data it contains.</p>
<pre name="code" class="javascript">
//creating the data repository
var store = new Ext.data.ArrayStore({
	fields: [
	   {name: 'company'},
	   {name: 'price', type: 'float'},
	   {name: 'change', type: 'float'},
	   {name: 'pctChange', type: 'float'},
	   {name: 'updated', type: 'date', dateFormat: 'n/j h:ia'}
	]
});
store.loadData(myData);
</pre>
<p>The attribute &#8220;name&#8221; defines the name by which we will reference the first data column, the column called &#8220;price&#8221; is a reference to the second column and so on.</p>
<p>You can use the &#8220;type&#8221; attributes which defines the data type of the column, &#8220;dateFormat&#8221; defines the format of the columns that have a date format (see ExtJS API for more information).</p>
<h3>The Grid</h3>
<p>Now we are ready to create our grid by using the object &#8220;Ext.grid.GridPanel&#8221;:</p>
<pre name="code" class="javascript">
//Creating the object Ext.grid.GridPanel
var grid = new Ext.grid.GridPanel({
	title:'Company List',
	store: store,
	renderTo: document.body,
	columns: [
		{id:'company',header: "Company", width: 160, sortable: true, dataIndex: 'company'},
		{header: "Price", width: 75, sortable: true, dataIndex: 'price'},
		{header: "Change", width: 75, sortable: true, dataIndex: 'change'},
		{header: "% of change", width: 75, sortable: true, dataIndex: 'pctChange'},
		{header: "Updated", width: 85, sortable: true, renderer: Ext.util.Format.dateRenderer('m/d/Y'), dataIndex: 'updated'}
	],
	stripeRows: true,
	height:250,
	width:500
});
</pre>
<p>The grids, as well as the forms and other components inherit from &#8220;Ext.Panel&#8221;, this has already been seen in <a href="http://www.quizzpot.com/2009/07/what-is-a-panel-whats-the-functionality-how-do-you-create-one/">previous tutorials</a> so I guess you will be familiar with this.</p>
<p>The properties used are:<br />
&#8220;title&#8221;: property inherited from the Ext.Panel class, it defines the title of the panel.<br />
&#8220;store&#8221;: property that defines where the grid will get the data, (the Ext.data.ArrayStore defined previously).<br />
&#8220;renderTo&#8221;: defines where the grid is going to be rendered, receives a reference of the id of a DOM object or DIV.<br />
&#8220;columns&#8221;: defines the header of each column, in here the store date are associated through the property &#8220;name&#8221; defined in the store.<br />
&#8220;id&#8221;: defines the id of the column.<br />
&#8220;header&#8221;: defines the name displayed in the title of each column.<br />
&#8220;width&#8221;: sets the width of the column.<br />
&#8220;sortable&#8221;: boolean property that defines if we&#8217;re going to allow the ordering of the data by clicking the column heading.<br />
&#8220;dataIndex&#8221;: in here we define the value of the property &#8220;name&#8221; of the store, by doing this we associate the  data of the column of the store with the column of the table.<br />
&#8220;renderer&#8221;: with this property we can customize the data as shown in the column, I&#8217;ll explain that later.<br />
&#8220;stripeRows&#8221;: this property is used to show a slight shading spacing in the rows of the table.<br />
&#8220;height&#8221;: defines the height of the grid.<br />
&#8220;width&#8221;: define the width of the grid.</p>
<div class="example"><img src="http://www.quizzpot.com/wp-content/uploads/2009/06/tabla1.jpg" alt="Image of a grid" />
<p>Image of a basic grid</p>
</div>
<p>As we can see the grids have well-defined components, for the data management we need to use a store whose type depends on the type of information we need to handle; for example we have the &#8220;Ext.data.JSONStore&#8221; that handles information in JSON format, I suggest you to check the API to see more properties and types of data repositories.</p>
<h3>The ColumnModel</h3>
<p>Even though our grid is now ready and there are some things we might need that thankfully ExtJS has, one of those things are &#8220;Ext.grid.ColumnModel&#8221; which can be use to display the columns in the table and link them with the columns of the store, at the same time they provide functionalities such as selection of rows using a checkbox or a column for the enumeration of the rows.</p>
<p>Basically, creating a columnModel is similar to the content we&#8217;ve added in the property &#8220;columns&#8221; of our table.</p>
<pre name="code" class="javascript">
//Creating the object Ext.grid.ColumnModel
var myColumnModel = new Ext.grid.ColumnModel([
	{id:'company',header: "Company", width: 160, sortable: true, dataIndex: 'company'},
	{header: "Price", width: 75, sortable: true, dataIndex: 'price'},
	{header: "Change", width: 75, sortable: true, dataIndex: 'change'},
	{header: "% of change", width: 75, sortable: true, dataIndex: 'pctChange'},
	{header: "Updated", width: 85, sortable: true, renderer: Ext.util.Format.dateRenderer('m/d/Y'), dataIndex: 'updated'}
]);
//our grid will  be changed to associated with the variable myColumnModel
var grid = new Ext.grid.GridPanel({
	title:'Company List',
	store: store,
	renderTo: document.body,
	cm: myColumnModel,//reference to columnModel
	stripeRows: true,
	height:250,
	width:500
});
</pre>
<p>Now let&#8217;s number the rows and add a column of checkboxes for the selection.</p>
<pre name="code" class="javascript">
//Creating the object Ext.grid.ColumnModel
var myColumnModel = new Ext.grid.ColumnModel([
  	new Ext.grid.RowNumberer(),
  	new Ext.grid.CheckboxSelectionModel(),
  	{id:'company',header: "Company", width: 160, sortable: true, dataIndex: 'company'},
  	...
]);
</pre>
<div class="example"><img src="http://www.quizzpot.com/wp-content/uploads/2009/06/tabla2.jpg" alt="Image of a Grid" />
<p>A grid with numeration on the rows and checkboxes to select them</p>
</div>
<h3>The SelectionModel</h3>
<p>We are almost done, the only thing to add is a &#8220;Ext.grid.SelectionModel&#8221; which will indicate the mode of selection that our grid will have.</p>
<pre name="code" class="javascript">
//Creating a variable to link our object
var mySelectionModel = new Ext.grid.CheckboxSelectionModel({singleSelect: false});

//these are the settings we need for the grid
var grid = new Ext.grid.GridPanel({
	title:'Company List',
	store: store,
	renderTo: document.body,
	cm: myColumnModel, //reference of the columnModel
	sm: mySelectionModel, //reference of the selectionModel
	stripeRows: true,
	height:250,
	width:500
});
</pre>
<div class="example"><img src="http://www.quizzpot.com/wp-content/uploads/2009/06/tabla3.jpg" alt="Image of a grid" />
<p>Characteristics of a grid in Ext JS</p>
</div>
<h3>Conclusions</h3>
<p>Today we have created a simple grid that reads data from an Array using an &#8220;ArrayStore&#8221;, then we created the table and we associated the store columns with the property &#8220;columns&#8221; of the table or creating a &#8220;ColumnModel&#8221; and finally we added a &#8220;SelectionModel&#8221; to manage the way to select rows, soon we will learn how to use different types of store, use events in the store and the table and &#8220;selecionModel.</p>
<p>If you have any question or suggestion feel free to leave a comment in this post. Don&#8217;t forget to follow us on <a href="http://twitter.com/quizzpot">Twitter (@quizzpot)</a> or add <a href="http://feeds2.feedburner.com/quizzpot-en">our feeds</a> to your favorite RSS reader.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.quizzpot.com/2010/01/binding-information-from-an-array-to-a-grid/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Merry christmas</title>
		<link>http://www.quizzpot.com/2009/12/merry-christmas/</link>
		<comments>http://www.quizzpot.com/2009/12/merry-christmas/#comments</comments>
		<pubDate>Thu, 24 Dec 2009 17:22:57 +0000</pubDate>
		<dc:creator>Crysfel</dc:creator>
				<category><![CDATA[English]]></category>

		<guid isPermaLink="false">http://www.quizzpot.com/?p=2214</guid>
		<description><![CDATA[Merry Christmas and a happy New Year!]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.quizzpot.com/wp-content/uploads/2009/12/merry-christmas-2009.jpg" alt="Merry Christmas" /></p>
<p>May you all enjoy these holidays with your family and friends, and have a very Happy Christmas and a new year of successes and challenges.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.quizzpot.com/2009/12/merry-christmas/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Custom validations</title>
		<link>http://www.quizzpot.com/2009/12/custom-validations/</link>
		<comments>http://www.quizzpot.com/2009/12/custom-validations/#comments</comments>
		<pubDate>Mon, 07 Dec 2009 19:00:00 +0000</pubDate>
		<dc:creator>Hazel</dc:creator>
				<category><![CDATA[English]]></category>
		<category><![CDATA[Ext JS]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://www.quizzpot.com/?p=2148</guid>
		<description><![CDATA[Many times it is necessary to create specific validations for our applications and are necessary to achieve the correct functionality, this tutorial explains how we can create "vtype's" to validate our ExtJS forms.]]></description>
			<content:encoded><![CDATA[<p>In the previous tutorial we saw how to do common validations, today we will learn how to do personalized validations and we&#8217;ll also see how to restrict the entry of characters in the text boxes.</p>
<p>I&#8217;ll invite you to test <a href="http://www.quizzpot.com/demos/extjs/forms/customvalidations.html">the demo</a> of what we&#8217;ll do in this tutorial.</p>
<p><!-- imagen 1 --></p>
<div class="example"><img src="http://www.quizzpot.com/wp-content/uploads/2009/08/vtype1.jpg" alt="Vtype in Ext JS" />
<p>Form with personalized validations</p>
</div>
<h3>Resources</h3>
<p>Before we start the tutorial don&#8217;t forget to download the <a href="href="http://www.quizzpot.com/wp-content/uploads/2009/08/vtypes.zip"">resources</a>, which only consist of two files: a HTML and JS; I  have created a form and I put it inside of a window, so what you need to do is add the validations to some fields.</p>
<h3>Display error messages</h3>
<p>If you execute the resources at this moment you will see that three fields are required, and when you click on the button &#8220;save&#8221; you will see some errors in red (if you don&#8217;t write anything in the text boxes), but only around the fields.</p>
<p><!-- imagen 2 --></p>
<div class="example"><img src="http://www.quizzpot.com/wp-content/uploads/2009/08/vtype2.jpg" alt="Vtype in Ext JS" />
<p>No error messages</p>
</div>
<p>The user should receive enough information to know what is wrong and how to fix it, so what we need to do is show an error message, to do this we only need to write the following lines at the beginning of the method &#8220;init&#8221;:</p>
<pre name="code" class="javascript">
Ext.QuickTips.init();
Ext.form.Field.prototype.msgTarget = 'side';
</pre>
<p>The first line allows to display floating messages when we position the mouse over the text box, on the second line we display an error icon on the side of the field.</p>
<p><!-- image 3 --></p>
<div class="example"><img src="http://www.quizzpot.com/wp-content/uploads/2009/08/vtype3.jpg" alt="Vtype in Ext JS" />
<p>Displaying a floating message with the validation error</p>
</div>
<h3>Validate the age of majority</h3>
<p>In the &#8220;Date of birth&#8221; we&#8217;re going to calculate how many years we have from the given date of birth to today and validate that is over 18 years.</p>
<p>In the previous tutorial we saw how to use the &#8220;vtype&#8217;s&#8221; that are included in the ExtJS framework, today we&#8217;ll add more validations to the class &#8220;Ext.form.VTypes. The first thing we need to do is to extend the class like this:</p>
<pre name="code" class="javascript">
Ext.apply(Ext.form.VTypes,{

	//in here we're going to define the validations

});
</pre>
<p>The next things we need to do is define the &#8220;vtype&#8221; like this:</p>
<pre name="code" class="javascript">
Ext.apply(Ext.form.VTypes,{
	adult: function(val, field){
		try{
			var birth = field.getValue();
			var now = new Date();
			// The number of milliseconds in one year
			var ONE_YEAR = 1000 * 60 * 60 * 24 * 365;
		    	// Convert both dates to milliseconds
		    	var date1_ms = birth.getTime()
		    	var date2_ms = now.getTime()
		    	// Calculate the difference in milliseconds
		    	var difference_ms = Math.abs(date1_ms - date2_ms)
		    	// Convert back to years
		    	var years = difference_ms/ONE_YEAR;
			return years &gt;= 18;
		}catch(e){
			return false;
		}
	},
	adultText: 'You are underage!', //error message
	adultMask: / /  //regexp to filter the characters allowed
});
</pre>
<p>First we defined the name that the &#8220;VType&#8221; will receive, in this case &#8220;adult&#8221;, then we assign a function that receives two parameters: the contents of the field and the instance of the field that&#8217;s being validated, within this function we will have the code to validate and it must return &#8220;true&#8221; when the captured value is correct or &#8220;false&#8221; when the value is incorrect.</p>
<p>The next thing we need to do is define the text to display if the captured information is incorrect, we must remember that we have more validations within this object (Ext.form.VTypes), therefore to link the message with the function we only need to add the word &#8220;Text&#8221; at the end of the function name, in this case &#8220;adultText.</p>
<p>Optionally we can define a filter to capture only the correct characters, in order to do that we need to define a mask with the appropriate regular expression.</p>
<pre name="code" class="javascript">
adultMask: /[\d\/]/
</pre>
<p>The previous regular expression validates that the user can only enter digits and a slash, these characters are the only ones we need to enter a date in the format we have defined; please notice that the property is called &#8220;adultMask&#8221;, we only added at the end the word &#8220;Mask&#8221; to relate it with the validation we created previously.</p>
<p>Having defined the &#8220;vtype&#8221; we have to assign it to the field we need to validate, in this case the field &#8220;birth&#8221; of the form:</p>
<pre name="code" class="javascript">
{xtype:'datefield',fieldLabel:'Date of birth',name:'birth',allowBlank:false,format:'d/m/Y',vtype:'adult'},
</pre>
<p><!-- imagen 4 --></p>
<div class="example"><img src="http://www.quizzpot.com/wp-content/uploads/2009/08/vtype4.jpg" alt="Vtype in ExtJS" />
<p>Validating a date of birth (validating age of majority)</p>
</div>
<h3>Validate a phone number</h3>
<p>Now we will validate the format of a phone number, first we need to define the validation rules.</p>
<ul>
<li>Must contain 10 digits, for example: 8192847135</li>
<li>It can only accept parentheses, dashes, spaces and numbers,for example: (81) 92 847 135, 81 92-847-135, (81) 92-847-135, 81 92 84 71 35, 8192847135</li>
<li>It should only contain characters defined previously.</li>
</ul>
<p>With these rules we can now define the &#8220;vtype&#8221;:</p>
<pre name="code" class="javascript">
phone: function(value,field){
	return value.replace(/[ \-\(\)]/g,'').length == 10;
},
phoneText: 'Wrong phone number, please make sure it contains 10 digits',
phoneMask: /[ \d\-\(\)]/
</pre>
<p>The function defined in the property &#8220;phone&#8221; only removes the accepted characters (such as spaces, dashes, parentheses) leaving only the numbers, then validates that are ten digits; the mask accepts only the characters defined in the rules.</p>
<p>Finally we need to assign the &#8220;vtype&#8221; to the form field that we need to validate.</p>
<pre name="code" class="javascript">
{fieldLabel:'Phone number',name:'phone',vtype:'phone'},
</pre>
<p><!-- imagen 5 --></p>
<div class="example"><img src="http://www.quizzpot.com/wp-content/uploads/2009/08/vtype5.jpg" alt="Vtype in ExtJS" />
<p>Validating a phone number</p>
</div>
<h3>Validate a credit card</h3>
<p>In this last example we will validate the number of a credit card. First, we need to define the validation rules to have a clear idea of what we need to do.</p>
<ul>
<li>The number should have 16 digits, for example: 1234567891234567</li>
<li>We can only accept digits, spaces and dashes, for example:  1234 5678 9123 4567, 1234-5678-9123-4567</li>
<li>We should not accept any other character than the previous mentioned.</li>
</ul>
<p>You can see that these rules are very similar to the phone, so we can do a copy / paste and modify the code to fit these requirements.</p>
<pre name="code" class="javascript">
creditcard: function(value,field){
	return value.replace(/[ \-]/g,'').length == 16;
},
creditcardText: 'Wrong credit card number',
creditcardMask: /[ \d\-]/
</pre>
<p>I just made small changes because these rules are very similar, now we need to add the &#8220;vtype&#8221; to the field &#8220;credit&#8221;:</p>
<pre name="code" class="javascript">
{fieldLabel:'Credit card',name:'credit',vtype:'creditcard'},
</pre>
<p><!-- imagen 6 --></p>
<div class="example"><img src="http://www.quizzpot.com/wp-content/uploads/2009/08/vtype6.jpg" alt="Vtype in ExtJS" />
<p>Validating a credit card</p>
</div>
<h3>Conclusions</h3>
<p>Today we learned how to create our own client-side validations, as you can see it was really easy. ExtJS provides us an easy way to create custom validations and even put a mask on our fields.</p>
<p>If you have any question or suggestion feel free to leave a comment on this post. Don&#8217;t forget to follow us on <a href="http://twitter.com/quizzpot">Twitter (@quizzpot)</a> to be updated with the new tutorials we will post.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.quizzpot.com/2009/12/custom-validations/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Simple validations in the forms</title>
		<link>http://www.quizzpot.com/2009/11/simple-validations-in-the-forms/</link>
		<comments>http://www.quizzpot.com/2009/11/simple-validations-in-the-forms/#comments</comments>
		<pubDate>Wed, 25 Nov 2009 16:08:26 +0000</pubDate>
		<dc:creator>Crysfel</dc:creator>
				<category><![CDATA[English]]></category>
		<category><![CDATA[Ext JS]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://www.quizzpot.com/?p=2073</guid>
		<description><![CDATA[The validations are very important when we're saving the information the user entered, we should always validate the information we receive. In today's tutorial we will see how to use the validations ExtJS provides. ]]></description>
			<content:encoded><![CDATA[<p>It is very important to remember that we must validate the information the user enters in our application, both sides are equally important: the client side and server side. Using JavaScript, we can provide a better user experience when entering information in our application, but we must not forget that the server is responsible to validate everything it receives therefore we also have to do validate the information on the server and show the errors when they occurred.</p>
<p>This is a complicated task, but with Ext JS we can do this process faster by using the validations the Framework provides us. In this tutorial we will validate common information but later I will show you how to do complex validations.</p>
<h3>Resources</h3>
<p>Let&#8217;s download the <a href="http://www.quizzpot.com/wp-content/uploads/2009/08/simplevalidations-src.zip">resources</a> for this tutorial, I have created a <a href="http://www.quizzpot.com/2009/10/ext-js-basic-forms-and-fields/">form</a> with common fields such as &#8220;name, date, e-mail, Website, comment&#8221;, also there&#8217;s a PHP file which returns randomly some validation errors that we will show in the forms.</p>
<h3>Demo</h3>
<p>For everyone&#8217;s benefit I&#8217;ve created a <a href="http://www.quizzpot.com/demos/extjs/forms/simplevalidations.html">demo</a> of what we will see at the end of the tutorial, so go ahead a try it.</p>
<div class="example"><img src="http://www.quizzpot.com/wp-content/uploads/2009/08/validation1.jpg" alt="Validations in Ext JS" />
<p>Example of the tutorial finished</p>
</div>
<h3>Required fields</h3>
<p>If you run the application right now you will see that an <a href="http://www.quizzpot.com/2009/10/ext-js-basic-forms-and-fields/">empty form</a> is displayed, if we click on the &#8220;Save&#8221; button a request to the server is made through Ajax, then we get a message of &#8220;success&#8221; or &#8220;error&#8221;. It is very common to have required fields in an application, we should make sure that these fields are entered by the user and are being sent to the server (through Ajax).</p>
<p>To define a field as required we only need to use the property &#8220;allowBlank: false&#8221; in the fields we want to make mandatory, we will modify the form as follows.</p>
<pre name="code" class="javascript">
this.form = new Ext.form.FormPanel({
	url: 'simplevalidations.php',
	border:false,
	labelWidth: 80,
	defaults: {
		xtype:'textfield',
		width: 150
	},
	items:[
		{fieldLabel:'Name',name:'name',allowBlank:false}, //required field
		{xtype:'datefield',fieldLabel:'Start',name:'start',allowBlank:false}, //required field
		{xtype:'combo',fieldLabel:'Year',name:'year',triggerAction:'all',store:[2009,2008,2007,2006],readOnly:true},
		{fieldLabel:'Email',name:'email'},
		{fieldLabel:'Web site',name:'website'},
		{xtype:'textarea',fieldLabel:'Comment',name:'comment',allowBlank:false},//required field
		{xtype:'checkbox',fieldLabel:'',labelSeparator:'',boxLabel:'Available',name:'available'}
	]
});
</pre>
<p>In the previous code I&#8217;ve added the property &#8220;allowBlank: false&#8221; to the required fields, if you refresh the tutorial in your browser and click on the button &#8220;Save&#8221; you will get an error message and the required fields will be shown in red.</p>
<div class="example"><img src="http://www.quizzpot.com/wp-content/uploads/2009/08/validation2.jpg" alt="Validations in Ext JS" />
<p>Required field in the form</p>
</div>
<h3>Maximum of character in a TexField</h3>
<p>Normally we define in the database the number of characters we want in a field, so it is recommended to make sure the user can only enter something less to that number, otherwise we will have problems when saving the information. To do this we need only set the property &#8220;maxLength&#8221; with the maximum number we need.</p>
<pre name="code" class="javascript">
this.form = new Ext.form.FormPanel({
	//… code removed for simplicity
	items:[
		{fieldLabel:'Name',name:'name',allowBlank:false,maxLength:20},
		//… code removed for simplicity
	]
});
</pre>
<p>Now when we enter more than 20 characters in the field &#8220;name&#8221; an error appears telling us that something is wrong.</p>
<div class="example"><img src="http://www.quizzpot.com/wp-content/uploads/2009/08/validation3.jpg" alt="Validations in Ext JS" />
<p>Restrict number of characters in a field</p>
</div>
<h3>Common validations</h3>
<p>Ext JS has a component that contains some common validations and we can add the validations we need, in this tutorial we will use the default ones.</p>
<p>The component responsible of saving these validations is the &#8220;Ext.form.VTypes&#8221; and has four default validations:</p>
<h3>Only alpha characters</h3>
<p>The alpha characters are all letters and the underscore, it does not include numbers or other symbols. Let&#8217;s assign a &#8220;VType&#8221; to the field &#8220;name&#8221; to accept only these characters.</p>
<pre name="code" class="javascript">
this.form = new Ext.form.FormPanel({
	//… code removed for simplicity
	items:[
		{fieldLabel:'Name',name:'name',allowBlank:false,maxLength:20,vtype:'alpha'},
		//… code removed for simplicity
	]
});
</pre>
<p>With the property &#8220;VType&#8221; we can configure the validation we need, in this case we used &#8220;alpha&#8221; which is defined within the component &#8220;Ext.form.VTypes&#8221;, so don&#8217;t forget that.</p>
<div class="example"><img src="http://www.quizzpot.com/wp-content/uploads/2009/08/validation4.jpg" alt="Validations in Ext JS" />
<p>Only alpha characters</p>
</div>
<h3>Validate an e-mail</h3>
<p>A common validation is the e-mail, let&#8217;s assign the &#8220;VType&#8221; that corresponds to the field of email in our form as follows:</p>
<pre name="code" class="javascript">
this.form = new Ext.form.FormPanel({
	//… code removed for simplicity
	items:[
		//… code removed for simplicity

		{fieldLabel:'Email',name:'email',vtype:'email'}, // validating an e-mail

//… code removed for simplicity
	]
});
</pre>
<p>Thanks to Ext JS we don&#8217;t have to spend more than a minute to add that validation, now the form will look similar to the following screen when you enter a invalid e-mail.</p>
<div class="example"><img src="http://www.quizzpot.com/wp-content/uploads/2009/08/validation5.jpg" alt="Validations in Ext JS" />
<p>Validation of an e-mail</p>
</div>
<h3>Validate an URL</h3>
<p>Let&#8217;s see how to validate a Website address or &#8220;URL&#8221;.</p>
<pre name="code" class="javascript">
this.form = new Ext.form.FormPanel({
	//… code removed for simplicity
	items:[
		//… code removed for simplicity

		{fieldLabel:'Web site',name:'website',vtype:'url'}, //validating an URL

//… code removed for simplicity
	]
});
</pre>
<p>I&#8217;d like to emphasize that it also validates protocols such as &#8220;https&#8221; and &#8220;ftp&#8221;.</p>
<div class="example"><img src="http://www.quizzpot.com/wp-content/uploads/2009/08/validation6.jpg" alt="Validations in Ext JS" />
<p>Validation of an URL</p>
</div>
<h3>Validation in the server</h3>
<p>So far we have seen how to validate on the client side, but it is also important to validate on the server side, let&#8217;s see how we can display the validation errors that are caused on the server.</p>
<p>Ext JS has a feature that will save us a lot of time when we need to display the errors caused in the server, this feature will emphasize the exact area where and why the error was caused. To use this feature the server response should have the following format:</p>
<pre name="code" class="javascript">
{
	success: false,
	msg: 'General message of the error',
	errors: {
		field: 'Message of the reason of the error',
		anotherFieldError: 'what caused the error?'
       }
}
</pre>
<p>After defining the error messages, we need to edit the file &#8220;simplevalidations.php&#8221; and generate some test failures.</p>
<pre name="code" class="php">
$info = array(
	'success' =&gt; false,
	'msg' =&gt; 'There was an error saving the record',
	'errors' =&gt; array(
		'name' =&gt; $name.' is not an employee of this corporation',
		'email' =&gt; 'E-mail does not exist in the database',
		'comment' =&gt; 'The comment is to short'
	)
);
</pre>
<p>These fields are enough to accomplish the functionality we want, so just go ahead a refresh your browser and you will see something similar to the following image:</p>
<div class="example"><img src="http://www.quizzpot.com/wp-content/uploads/2009/08/validation7.jpg" alt="Validations in Ext JS" />
<p>Displaying validations errors caused in the server side</p>
</div>
<p>With this we can see that although the client validations are correct, the information may be incorrect due to our business logic, in this example the name of the person should exist in our catalog of employees (hypothetical example).</p>
<h3>Conclusions</h3>
<p>The validations are very important, today we saw how to use the default validations and we learned how to display error messages that are generated on the server. As you can see it was very easy validating fields with Ext JS.</p>
<p>If you have any questions or suggestions feel free to leave a comment on this post and don&#8217;t forget to follow us on <a href="http://twitter.com/quizzpot">Twitter</a> (@quizzpot) to be updated.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.quizzpot.com/2009/11/simple-validations-in-the-forms/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Linked ComboBoxes with ExtJS</title>
		<link>http://www.quizzpot.com/2009/11/linked-comboboxes-with-extjs/</link>
		<comments>http://www.quizzpot.com/2009/11/linked-comboboxes-with-extjs/#comments</comments>
		<pubDate>Wed, 18 Nov 2009 18:59:12 +0000</pubDate>
		<dc:creator>Hazel</dc:creator>
				<category><![CDATA[English]]></category>
		<category><![CDATA[Ext JS]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://www.quizzpot.com/?p=2118</guid>
		<description><![CDATA[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.]]></description>
			<content:encoded><![CDATA[<p>In today&#8217;s tutorial we will create two combos that are related to each other, we&#8217;ll use the typical example countries and their respective states, the information of the state&#8217;s combo will be loaded with Ajax depending on the country selected in the first combo. I recommend you <a href="http://www.quizzpot.com/demos/extjs/forms/linked-cmb.html">test the demo</a> to be able to see the final result.</p>
<p><!-- imagen 1 --></p>
<div class="example"><img src="http://www.quizzpot.com/wp-content/uploads/2009/11/linked-cmb1.jpg" alt="Linked ComboBoxes with ExtJS" />
<p>Tutorial&#8217;s demo</p>
</div>
<h3>Resources</h3>
<p>Before I start explaning this tutorial you need to download the <a href="http://www.quizzpot.com/wp-content/uploads/2009/11/linked-cmb.zip">resources</a> and copy the content into a Web server because we will be using Ajax to load information.</p>
<h3>The information source</h3>
<p>Let&#8217;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.</p>
<pre name="code" class="php">
$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')
);
</pre>
<p>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.</p>
<p>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&#8217;s write the following code to linked both combos:</p>
<pre name="code" class="php">
$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
}
</pre>
<p>In step one we retrieve the parameter &#8220;id&#8221; and verify the existence, if it hasn&#8217;t been sent we assign the value &#8220;-1&#8243; to the variable.</p>
<p>In step two we verify that the &#8220;id&#8221; is greater than &#8220;-1&#8243;, this tells us that our application is requesting the states of a country, the variable &#8220;id&#8221; must have the position of the requested country so in this part we decide what is going to be displayed: countries or states.</p>
<p>Step three is executed if the variable &#8220;id&#8221; contains the index of the selected country, so we can display the states of the requested index.</p>
<p>Step four is only implemented if the &#8220;id&#8221; is less than or equal to -1, this tells us that the application has requested the countries.</p>
<p>You probably noticed that we&#8217;re invoking the function &#8220;toJSON&#8221;, so let&#8217;s go ahead an write the function like this:</p>
<pre name="code" class="php">
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
	));
}
</pre>
<p>The purpose of this function is to create the JSON we&#8217;re going to send to the combos.</p>
<p>In step one we created two variables: &#8220;data&#8221; and &#8220;i&#8221;, in the variable &#8220;data&#8221; we will store each country or state we will display in the combos, the variable &#8220;i&#8221; is very important because we will use it to create the connection between the combos, I will explain this in step three.</p>
<p>In step two, we create a loop that runs through the array we received as a parameter, this array contains the information we&#8217;re going to display in the combos.</p>
<p>In step three we are storing each element of the array in the variable &#8220;data&#8221;, you can see that we are creating an array with two properties &#8220;value&#8221; and &#8220;label&#8221;, these properties will be used by the combo, in the property &#8220;value&#8221; we assigned the value of &#8220;i&#8221;, this is the value sent as a parameter to request the states of the country selected in the first combo, the property &#8220;label&#8221; is only the text that will display each option in the combo.</p>
<p>In step four we return the information we collected previously in JSON format.</p>
<h3>Creating JsonStores</h3>
<p>Once we have defined the information we need to display we can create the combos, we already know that the combos use <a href="http://www.quizzpot.com/2009/10/combo-box-loaded-dynamically-and-remotely/">a Store</a> 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&#8217;s go ahead and edit it and within the function &#8220;getStore&#8221; you would write the following:</p>
<pre name="code" class="javascript">
getStore: function(){
	var store = new Ext.data.JsonStore({
		url:'linked-cmb.php',
		root:'data',
		fields: ['value','label']
	});
	return store;
}
</pre>
<p>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&#8217;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&#8217;t want to rewrite the same code twice, so I just created a function that generates the stores as many time as necessary.</p>
<h3>Creating the Linked ComBoxes</h3>
<p>In the previous step we created a function that generates <a href="http://www.quizzpot.com/2009/06/reading-information-in-json-format/">one JsonStore</a>, so let&#8217;s create two of these so we can use them with each of the combos:</p>
<pre name="code" class="javascript">
this.countryStore = this.getStore();
this.stateStore = this.getStore();
</pre>
<p>The combo that will display the countries will have the following properties:</p>
<pre name="code" class="javascript">
this.countryCmb = new Ext.form.ComboBox({
	store: this.countryStore,
	id: 'country',
	valueField: 'value',
	displayField: 'label',
	triggerAction: 'all',
	emptyText: 'Select a Country',
	fieldLabel: 'Country'
});
</pre>
<p>There&#8217;s nothing complicated in the previous code, is just a typical configuration of a <a href="http://www.quizzpot.com/2009/10/combo-box-loaded-dynamically-and-remotely/">ComboBox</a>, the next thing we need to do is create a combo that will display the states of the selected country.</p>
<pre name="code" class="javascript">
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'
});
</pre>
<p>This configuration has some differences from the previous one, these differences are very important and I will explain you why:</p>
<p>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.</p>
<p>Step two is very important, if we don&#8217;t assign this configuration we will have a strange behavior because by assigning the property &#8220;mode: &#8216;local&#8217;&#8221; we ensure that there is no Ajax requests to the server when the user clicks on the combo to see the options.</p>
<h3>Displaying the combos in a window</h3>
<p>So far we have written code but still can not see anything on the screen, so now it&#8217;s time to render the components, for this example I will use a window with the following properties:</p>
<pre name="code" class="javascript">
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();
</pre>
<p><!-- imagen 2 --></p>
<div class="example"><img src="http://www.quizzpot.com/wp-content/uploads/2009/11/linked-cmb2.jpg" alt="Linked ComboBoxes with ExtJS" />
<p>Creation of the ComboBoxes</p>
</div>
<p> </p>
<h3>Adding the “listener”</h3>
<p>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.</p>
<p>To interact with the components we need to add a <a href="http://www.quizzpot.com/2009/05/handling-events-on-dom-elements-and-components/">&#8220;listener&#8221;</a> to the first combo, in order to enable the combo of states when the first combo is selected and load the appropriate information.</p>
<pre name="code" class="javascript">
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);
</pre>
<p>In step one we added a &#8220;listener&#8221; to the event &#8220;select&#8221;, 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.</p>
<p>In step two we only enable the combo of states.</p>
<p>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.</p>
<p>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.</p>
<p>In step four we are reloading the information of the Store of states with Ajax.</p>
<p>In step five we pass the parameter &#8220;id&#8221; which is going to be used by the server to decided which states must be returned.</p>
<p><!-- imagen 3 --></p>
<div class="example"><img src="http://www.quizzpot.com/wp-content/uploads/2009/11/linked-cmb1.jpg" alt="Linked ComboBoxes with ExtJS" />
<p>Linked combos</p>
</div>
<h3>Conclusions</h3>
<p>Following the steps in this tutorial we can create linked combos on the levels we need, we just need to assign a &#8220;listener&#8221; to the event &#8220;select&#8221; of the combo and within this &#8220;listener&#8221; reload the store of the combo.</p>
<p>Don&#8217;t forget to follow us on <a href="http://twitter.com/quizzpot">Twitter (@quizzpot)</a> 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.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.quizzpot.com/2009/11/linked-comboboxes-with-extjs/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Saving information in the server</title>
		<link>http://www.quizzpot.com/2009/11/saving-information-in-the-server/</link>
		<comments>http://www.quizzpot.com/2009/11/saving-information-in-the-server/#comments</comments>
		<pubDate>Thu, 12 Nov 2009 18:01:54 +0000</pubDate>
		<dc:creator>Crysfel</dc:creator>
				<category><![CDATA[English]]></category>
		<category><![CDATA[Ext JS]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://www.quizzpot.com/?p=2062</guid>
		<description><![CDATA[Today we will see how to send the information submitted in a form of Ext JS to the server in order to save it in a database or manipulate it in any way.]]></description>
			<content:encoded><![CDATA[<p>In previous tutorials we saw how to load a form with information on the fields, like <a href="http://www.quizzpot.com/2009/11/loading-forms-remotely/">requesting the information from the server</a>, in this tutorial I will show you how to &#8220;submit&#8221; the form to send information to the server and save or process the information.</p>
<h3>Resources</h3>
<p>To continue this tutorial you must download the <a href="http://www.quizzpot.com/wp-content/uploads/2009/08/submitform.zip">resources</a>, which contains an HTML that includes a JS file in which I have created a form contained in a window and a PHP file which will process the information sent.</p>
<h3>Demonstration</h3>
<p>I created a demonstration of the exercise we&#8217;re going to do, I recommend you go to <a href="http://www.quizzpot.com/demos/extjs/forms/submitform.html">test its functionality</a>, is very simple but it explains perfectly what we&#8217;ll learn today.</p>
<p><!-- imagen 1 --></p>
<div class="example"><img src="http://www.quizzpot.com/wp-content/uploads/2009/08/submitform1.jpg" alt="Submit form" />
<p>Final result</p>
</div>
<h3>Traditional Submit</h3>
<p>If we want to do an ordinary &#8220;submit&#8221;, without using Ajax and reload the whole page, we only need to set the property &#8220;standardSubmit: true&#8221;, by default is false.</p>
<p>If we open the file &#8220;submitform.js&#8221; of the resources, you will see the following code in the method &#8220;init&#8221;:</p>
<pre name="code" class="javascript">
this.form = new Ext.form.FormPanel({
	standardSubmit: true, // traditional submit
	url: 'submitform.php',
	border:false,
	labelWidth: 80,
	defaults: {
		xtype:'textfield',
		width: 150
	},
	items:[
		{fieldLabel:'Title',name:'title', allowBlank:false},
		{xtype:'combo',fieldLabel:'Year',name:'year',triggerAction:'all',store:[2009,2008,2007,2006]},
		{xtype:'numberfield',fieldLabel:'Revenues',name:'revenues'},
		{xtype:'textarea',fieldLabel:'Comment',name:'comment'},
		{xtype:'checkbox',fieldLabel:'',labelSeparator:'',boxLabel:'Available',name:'available'}
	]
});

this.win = new Ext.Window({
	id:'mywin',
	title: 'Submit data to the Server',
	bodyStyle: 'padding:10px;background-color:#fff;',
	width:300,
	height:270,
	items:[this.form],
	buttons: [{text:'Save'},{text:'Cancel'}]
});

this.win.show();
</pre>
<p>We have studied the previous code several times, so I assume that you understand it perfectly. If you&#8217;ve noticed, the first setting is &#8220;standardSubmit: true&#8221; and it enable us to a traditional &#8220;submit&#8221;, this is actually the only difference of the forms we&#8217;ve created in previous tutorials.</p>
<h3>make a submit with the buttons save</h3>
<p>Until now the buttons do absolutely nothing, they are just being displayed in the form so what we have to do is assign them a &#8220;handler&#8221; and in this case assign the &#8220;scope&#8221; we are going to use. Let&#8217;s change the code of the button like this:</p>
<pre name="code" class="javascript">

{text:'Save',handler:this.sendData,scope:this}
</pre>
<p>Now we have to implement the function &#8220;sendData&#8221; to do the &#8220;submit&#8221;.</p>
<pre name="code" class="javascript">
sendData: function(){
	//submit the form
	this.form.getForm().submit();
}
</pre>
<p>If you&#8217;ve noticed we used the method &#8220;getForm()&#8221; to have access to the BasicForm in order to do the &#8220;submit()&#8221;. The component &#8220;FormPanel&#8221; contains another component called &#8220;BasicForm&#8221; which is responsible for managing the basic functionalities of a form like: information of the fields, send information to the server, reset the fields, validations, etc.. At the same time, the &#8220;FormPanel&#8221; is a container that is responsible for managing the &#8220;layout&#8221;, assign a title and display it in the form of a &#8220;Panel&#8221; or allocate to other components.</p>
<p><!-- imagen 2 --></p>
<div class="example"><img src="http://www.quizzpot.com/wp-content/uploads/2009/08/submitform2.jpg" alt="Submit form" />
<p>Traditional submit, without Ajax</p>
</div>
<p>If at this time we click on the button &#8220;save&#8221;, we will see how the page is reloaded completely.</p>
<h3>Make a submit using Ajax</h3>
<p>I think this is the part that we&#8217;re all interested, let&#8217;s see how we can send information using Ajax. The first thing we need to do is remove the configuration &#8220;standardSubmit: true&#8221; of the form.</p>
<pre name="code" class="javascript">
this.form = new Ext.form.FormPanel({
	//standardSubmit: true, // remove this property
	url: 'submitform.php',
	border:false,
	labelWidth: 80,
	defaults: {
		xtype:'textfield',
		width: 150
	},
	items:[
		{fieldLabel:'Title',name:'title', allowBlank:false},
		{xtype:'combo',fieldLabel:'Year',name:'year',triggerAction:'all',store:[2009,2008,2007,2006]},
		{xtype:'numberfield',fieldLabel:'Revenues',name:'revenues'},
		{xtype:'textarea',fieldLabel:'Comment',name:'comment'},
		{xtype:'checkbox',fieldLabel:'',labelSeparator:'',boxLabel:'Available',name:'available'}
	]
});
</pre>
<p>These changes are enough to achieve our goal, if we test the example in this moment we can see in the Firebug console that the parameters are being sent correctly using the method &#8220;POST&#8221;.</p>
<p><!-- imagen 3 --></p>
<div class="example"><img src="http://www.quizzpot.com/wp-content/uploads/2009/08/submitform3.jpg" alt="Submit form" />
<p>Form submit using Ajax</p>
</div>
<h3>Customize the request method</h3>
<p>Sometimes is necessary to change the request method (by default POST) for a different one, in this case we must specify that method we need (GET, POST, PUT, DELETE), we will also send a message if the information was saved successfully or if something caused an error.</p>
<pre name="code" class="javascript">
this.form.getForm().submit({
	method: 'put',
	success: function(form,action){
		Ext.Msg.alert('Success',action.result.msg);
	},
	failure: function(form,action){
		switch (action.failureType) {
			  case Ext.form.Action.CLIENT_INVALID:
				 Ext.Msg.alert('Failure', 'Form fields may not be submitted with invalid values');
				 break;
			  case Ext.form.Action.CONNECT_FAILURE:
				 Ext.Msg.alert('Failure', 'Ajax communication failed');
				 break;
			  case Ext.form.Action.SERVER_INVALID:
				Ext.Msg.alert('Failure', action.result.msg);
				break;
			  default:
				Ext.Msg.alert('Failure',action.result.msg);
		  }
	}
});
</pre>
<p>In this example we used the method &#8220;PUT&#8221; to create a new record in the database, you must be wondering why I used PUT and not POST, right? In future tutorials I will talk about a technique called &#8220;REST&#8221; which specifies that we must use different existent methods to interact with the server as well as identify the &#8220;status&#8221; codes in the responses.</p>
<p>The property &#8220;success&#8221; enables us to configure the function that will be executed if everything went as expected, in this case we&#8217;ll only send a message of success:</p>
<p><!-- imagen 4 --></p>
<div class="example"><img src="http://www.quizzpot.com/wp-content/uploads/2009/08/submitform4.jpg" alt="Submit form" />
<p>Information saved successfully</p>
</div>
<p>The property &#8220;failure&#8221; allow us to configure a function we want to execute when an error was caused in the server.</p>
<p><!-- imagen 5 --></p>
<div class="example"><img src="http://www.quizzpot.com/wp-content/uploads/2009/08/submitform5.jpg" alt="Submit form" />
<p>Something went wrong when saving the information</p>
</div>
<p>Who decides when the methods are executed? Great question! Right now the component &#8220;FormPanel&#8221; expects that the server&#8217;s response contains the property &#8220;success&#8221;, this property is the one that decides which method will be executed, if the property is &#8220;true&#8221; the function configure in &#8220;success&#8221; is executed and if it is &#8220;false&#8221; the function set on property &#8220;failure&#8221; is executed.</p>
<pre name="code" class="javascript">
{
    "success":true,
    "msg":"Message example"
}
</pre>
<p>Also the function configured in &#8220;failure&#8221; is executed when you cannot establish a communication with the server or an error was caused in the form validation.</p>
<h3>Extra parameters</h3>
<p>Sometimes it is necessary to send extra parameters to the server, to do this we only need to configure the property &#8220;params&#8221; in the options of the submit.</p>
<pre name="code" class="javascript">
this.form.getForm().submit({
	method: 'put',
	params: {
		extraParam: 'Extra params!',
		param2: 'Param 2'
		},
	success: function(form,action){
		Ext.Msg.alert('Success',action.result.msg);
	},
	failure: function(form,action){
		switch (action.failureType) {
			  case Ext.form.Action.CLIENT_INVALID:
				 Ext.Msg.alert('Failure', 'Form fields may not be submitted with invalid values');
				 break;
			  case Ext.form.Action.CONNECT_FAILURE:
				 Ext.Msg.alert('Failure', 'Ajax communication failed');
				 break;
			  case Ext.form.Action.SERVER_INVALID:
				Ext.Msg.alert('Failure', action.result.msg);
				break;
			  default:
				Ext.Msg.alert('Failure',action.result.msg);
		  }
	}
});
</pre>
<h3>Message loading</h3>
<p>Finally I will show you how we can mask the window and display a message telling the user that the information is being sent.</p>
<p>First, we need to create the mask and show it before we do the submit.</p>
<pre name="code" class="javascript">
var mask = new Ext.LoadMask(Ext.get('mywin'), {msg:'Saving. Please wait...'});
mask.show();
</pre>
<p>The component &#8220;Ext.LoadMask&#8221; creates a mask for a given element, in this case we are assigning the window that contains the form, the second parameter is a configuration object where we are assigning a message to show; once the &#8220;instance&#8221; is create we will show the mask using the method &#8220;show&#8221;.</p>
<p><!-- imagen 6 --></p>
<div class="example"><img src="http://www.quizzpot.com/wp-content/uploads/2009/08/submitform6.jpg" alt="Submit form" />
<p>Mask showing the message to the user</p>
</div>
<p>Now we must hide it when the server responds, this means that we must invoke the method &#8220;hide&#8221; in the &#8220;success&#8221; and &#8220;failure&#8221;.</p>
<pre name="code" class="javascript">
success: function(form,action){
		mask.hide(); //hide the mask
		Ext.Msg.alert('Success',action.result.msg);
}
</pre>
<h3>Conclusions</h3>
<p>In today&#8217;s tutorial we learned some important things, you can see that making a submit is very easy and is completely configurable and can be adapted to our needs.</p>
<p>If you have any questions about this tutorial you can leave a comment or contact us, we will gladly answer your questions. Don&#8217;t forget that you can subscribe to our <a href="http://feeds2.feedburner.com/quizzpot-en">Feeds</a> or read the tutorials by <a href="http://feedburner.google.com/fb/a/mailverify?uri=quizzpot-mail-en&#038;loc=en_US">email and of course you can follow us on <a href="http://twitter.com/quizzpot">Twitter (@quizzpot)</a> to be updated.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.quizzpot.com/2009/11/saving-information-in-the-server/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Loading forms remotely</title>
		<link>http://www.quizzpot.com/2009/11/loading-forms-remotely/</link>
		<comments>http://www.quizzpot.com/2009/11/loading-forms-remotely/#comments</comments>
		<pubDate>Mon, 02 Nov 2009 17:38:15 +0000</pubDate>
		<dc:creator>Crysfel</dc:creator>
				<category><![CDATA[English]]></category>
		<category><![CDATA[Ext JS]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://www.quizzpot.com/?p=2008</guid>
		<description><![CDATA[In today's topic we will see how to fill out a form using Ajax to make a request to the server, we will request the information with an identifier we'll send as a parameter.]]></description>
			<content:encoded><![CDATA[<p>We&#8217;ve already learned how to fill an Ext JS form through a record, today we&#8217;ll fill the form by retrieving information through an Ajax request to the server.</p>
<h3>Resources</h3>
<p>Before we start this tutorial, please download the <a href="http://www.quizzpot.com/wp-content/uploads/2009/08/loadform.zip">resources</a>, which consists of three files and a folder containing images, you must copy these files to the Web server we have been working on, this is very important so we can use Ajax.</p>
<h3>Demo</h3>
<p>In today&#8217;s exercise we will dynamically generate the &#8220;Top Ten&#8221; list of the most popular movies, when we click on any of these images a form will be displayed, which will be loaded by making a request to the server via Ajax. You can <a href="http://www.quizzpot.com/demos/extjs/forms/loadform.html">see a demonstration</a> of what we&#8217;ll have when we finish this tutorial.</p>
<p><!-- image 1 --></p>
<div class="example"><img src="http://www.quizzpot.com/wp-content/uploads/2009/08/loadform1.jpg" alt="Form loaded with Ajax" />
<p>Final Example</p>
</div>
<h3>Information</h3>
<p>The most important thing in an application is the information, this time the information is contained in an array on the server, but remember that the information can come from a database such as MySQL, PostgreSQL, Oracle, a Web Service or any other place.</p>
<pre name="code" class="php">
&lt;?php
	header(&quot;Content-Type: text/plain&quot;); 

	$all = isset($_GET['all']);
	$movie = isset($_POST['id'])?$_POST['id']:rand(0,9);

	$data = array(
			array('title'=&gt;'G-Force','year'=&gt;2009,'revenues'=&gt;32.2,'comment'=&gt;'Very good movie, it is an awesome movie','available'=&gt;true,'img'=&gt;'images/gforce.jpg'),
			array('title'=&gt;'Harry Potter and the Half-Blood Prince','year'=&gt;2009,'revenues'=&gt;30,'comment'=&gt;'Not to good, but it is ok','available'=&gt;true,'img'=&gt;'images/hpotter.jpg'),
			array('title'=&gt;'The Ugly Truth','year'=&gt;2009,'revenues'=&gt;27,'comment'=&gt;'Another comment to the movie','available'=&gt;false,'img'=&gt;'images/ugly.jpg'),
			array('title'=&gt;'Orphan','year'=&gt;2009,'revenues'=&gt;12.8,'comment'=&gt;'Testing the comment','available'=&gt;'images/orphan.jpg','img'=&gt;'images/orphan.jpg'),
			array('title'=&gt;'Ice Age: Dawn of the Dinosaurs ','year'=&gt;2009,'revenues'=&gt;8.2,'comment'=&gt;'Awesome movie, really good','available'=&gt;true,'img'=&gt;'images/ice.jpg'),
			array('title'=&gt;'Transformers: Revenge of the Fallen','year'=&gt;2009,'revenues'=&gt;8,'comment'=&gt;'Another test','available'=&gt;false,'img'=&gt;'images/transformers.jpg'),
			array('title'=&gt;'The Hangover','year'=&gt;2009,'revenues'=&gt;6.46,'comment'=&gt;'Testing','available'=&gt;true,'img'=&gt;'images/hangover.jpg'),
			array('title'=&gt;'The Proposal','year'=&gt;2009,'revenues'=&gt;6.42,'comment'=&gt;'Comment','available'=&gt;true,'img'=&gt;'images/proposal.jpg'),
			array('title'=&gt;'Public Enemies','year'=&gt;2009,'revenues'=&gt;4.17,'comment'=&gt;'One more comment','available'=&gt;false,'img'=&gt;'images/public.jpg'),
			array('title'=&gt;'Br&#252;no','year'=&gt;2009,'revenues'=&gt;2.72,'comment'=&gt;'nothing to say','available'=&gt;false,'img'=&gt;'images/bruno.jpg')

	);

	if($all){
		$info = $data;
	}else{
		$info = array(
			'success'=&gt;true,
			'data'=&gt; $data[$movie]
		);
	}

	echo json_encode($info);
?&gt;
</pre>
<p>The most important thing I&#8217;d like to mention from the previous code is the parameter &#8220;all&#8221;, if this parameter is sent in the request, the entire array of objects will be printed in format &#8220;json&#8221;, if it&#8217;s not present it means that we&#8217;re requesting only one item.</p>
<h3>Requesting information from the server</h3>
<p>If you run the HTML in your browser right now you will only see the title, we need to request the information we&#8217;re going to display <a href="http://www.quizzpot.com/2009/05/ajax-object-get-and-post-requests/">with Ajax</a>, within the method &#8220;init&#8221; of the main object we will make the request like this:</p>
<pre name="code" class="javascript">
Ext.Ajax.request({
	url: 'loadform.php',
	params: {all:true}, //requesting all the records
	method: 'GET', //using the method GET
	scope: this,
	success: this.createTopTen // and indicationg what function will process the response
});
</pre>
<p>As we have requested all the records we will get the following result:</p>
<pre name="code" class="javascript">
[{"title":"G-Force","year":2009,"revenues":32.2,"comment":"Very good movie, it is an awesome movie","available":true,"img":"images\/gforce.jpg"},{"title":"Harry Potter and the Half-Blood Prince","year":2009,"revenues":30,"comment":"Not to good, but it is ok","available":true,"img":"images\/hpotter.jpg"},{"title":"The Ugly Truth","year":2009,"revenues":27,"comment":"Another comment to the movie","available":false,"img":"images\/ugly.jpg"},{"title":"Orphan","year":2009,"revenues":12.8,"comment":"Testing the comment","available":"images\/orphan.jpg","img":"images\/orphan.jpg"},{"title":"Ice Age: Dawn of the Dinosaurs ","year":2009,"revenues":8.2,"comment":"Awesome movie, really good","available":true,"img":"images\/ice.jpg"},{"title":"Transformers: Revenge of the Fallen","year":2009,"revenues":8,"comment":"Another test","available":false,"img":"images\/transformers.jpg"},{"title":"The Hangover","year":2009,"revenues":6.46,"comment":"Testing","available":true,"img":"images\/hangover.jpg"},{"title":"The Proposal","year":2009,"revenues":6.42,"comment":"Comment","available":true,"img":"images\/proposal.jpg"},{"title":"Public Enemies","year":2009,"revenues":4.17,"comment":"One more comment","available":false,"img":"images\/public.jpg"},{"title":"Br\u00fcno","year":2009,"revenues":2.72,"comment":"nothing to say","available":false,"img":"images\/bruno.jpg"}]
</pre>
<h3>Creating the “Top Ten” List</h3>
<p>With the information we received we can create the &#8220;Top Ten&#8221; list, we will implement the function &#8220;createTopTen&#8221; where we will decode the JSON first so we can use it correctly and then with the class &#8220;DomHelper&#8221; we will generate and insert nodes to the DOM.</p>
<pre name="code" class="javascript">
var info = Ext.decode(response.responseText); //decoding the text we received
Ext.each(info,function(movie){ //iterating the information
	Ext.DomHelper.append('content',{ //and creating an image for each element
		tag:'img',
		src:movie.img,
		alt:movie.title,
		title:movie.title,
		cls: 'movie'
	});
},this);
</pre>
<p>We have previously studied the class <a href="http://www.quizzpot.com/2009/04/the-class-domhelper/">Ext.DomHelper</a>, therefore we must be familiar with its functionality, if you can&#8217;t remember about this component I recommend you to review the tutorial where we studied <a href="http://www.quizzpot.com/2009/04/the-class-domhelper/">this component</a>.</p>
<p><!-- imagen 2 --></p>
<div class="example"><img src="http://www.quizzpot.com/wp-content/uploads/2009/08/loadform2.jpg" alt="Form loaded with Ajax" />
<p>Creating the images for the Top Ten list</p>
</div>
<h3>Adding &#8220;listeners&#8221; to the images</h3>
<p>The next thing we need to do is add a &#8220;<a href="http://www.quizzpot.com/2009/05/handling-events-on-dom-elements-and-components/">listener</a>&#8221; to the event &#8220;click&#8221; of each image we created, so we can display the form with the appropriate information.</p>
<p>Right after we create the images, we&#8217;re going to select the DOM nodes, iterate them and we will add the listener to each image.</p>
<pre name="code" class="javascript">
var items = Ext.DomQuery.select('div[id=content] > img');
Ext.each(items,function(el,i){
	el = Ext.get(el);
	el.on('click',function(){
		this.showDetail(i); //this function will be triggered when the user clicks on an image
	},this);
},this);
</pre>
<p>In the previous code we can see that the function &#8220;showDetail (i);&#8221; will be triggered when we click on any image, it is important to mention that you are receiving a parameter &#8220;i&#8221; which indicates the &#8220;id&#8221; of the image that has been clicked, this will be useful to request the information to the server.</p>
<h3>Creating the form</h3>
<p>It&#8217;s time to create the form within the &#8220;showDetail&#8221; function as follows:</p>
<pre name="code" class="javascript">
var form = new Ext.form.FormPanel({
	url: 'loadform.php', //the URL we  need to load the form
	border:false,
	labelWidth: 80,
	defaults: {
		xtype:'textfield',
		width: 150
	},
	items:[
		{fieldLabel:'Title',name:'title'},
		{xtype:'combo',fieldLabel:'Year',name:'year',triggerAction:'all',store:[2009,2008,2007,2006]},
		{xtype:'numberfield',fieldLabel:'Revenues',name:'revenues'},
		{xtype:'textarea',fieldLabel:'Comment',name:'comment'},
		{xtype:'checkbox',fieldLabel:'',labelSeparator:'',boxLabel:'Available',name:'available'}
	]
});
</pre>
<p>At this time of course we must be completely familiar with the <a href="http://www.quizzpot.com/2009/10/ext-js-basic-forms-and-fields/">code</a> <a href="http://www.quizzpot.com/2009/10/combo-box-loaded-dynamically-and-remotely/">above</a>, the only difference is the property &#8220;url&#8221;, in this property we configure the URL to make the Ajax request to load the form, don&#8217;t forget that it&#8217;s very important to use the property &#8220;name&#8221; in the form fields.</p>
<p>The next thing we need to do is <a href="http://www.quizzpot.com/2009/07/a-floating-window/">create the window</a> that will contain the previous form.</p>
<pre name="code" class="javascript">
var win = new Ext.Window({
	title: 'Loading data into a form',
	bodyStyle: 'padding:10px;background-color:#fff;',
	width:300,
	height:270,
	items:[form],
	buttons: [{text:'Save'},{text:'Cancel'}]
});

win.show();
</pre>
<p>If you click on any image at this moment you will see something like the following picture.</p>
<p><!-- imagen 3 --></p>
<div class="example"><img src="http://www.quizzpot.com/wp-content/uploads/2009/08/loadform3.jpg" alt="Form loaded with Ajax" />
<p>Empty form</p>
</div>
<h3>Requesting the information from the server</h3>
<p>We have created the form and appears when clicking on each image, the next thing we will do is fill it with the information depending on the requested image, this is very easy to do because we simply need to invoke the method &#8220;load&#8221; with the corresponding parameters:</p>
<pre name="code" class="javascript">
form.getForm().load({params:{id:id}});
</pre>
<p>We must remember that the JSON format that the server must return is:</p>
<pre name="code" class="javascript">
{
	"success":true,
	"data":{"title":"The Proposal","year":2009,"revenues":6.42,"comment":"Comment","available":true,"img":"images\/proposal.jpg"}
}
</pre>
<p>It is very important to return the parameter &#8220;success&#8221; to &#8220;true&#8221; (if there wasn&#8217;t any error) in order to properly fill out the form, otherwise the component assumes that there was an error in the server and the form won&#8217;t get filled.</p>
<p><!-- imagen 4 --></p>
<div class="example"><img src="http://www.quizzpot.com/wp-content/uploads/2009/08/loadform4.jpg" alt="Form loaded with Ajax" />
<p>Form loaded with Ajax</p>
</div>
<h3>Conclusions</h3>
<p>Today we learned how to fill out the form using Ajax calls to the server, it is very important that the response contains the property &#8220;success: true&#8221; so it will work correctly; from my point of view I don&#8217;t like that the component requires us to accomplish this, I think it would be better to use a HTTP status to detect whether an error has happened, so we could develop our applications using &#8220;REST&#8221; (I&#8217;ll talk about it in future tutorials) however, the Forms are awesome.</p>
<p>As always, if you have any questions or suggestions please leave a comment and don&#8217;t forget to follow us on <a href="http://twitter.com/quizzpot">Twitter (@quizzpot)</a> to be updated on new tutorials or you can subscribe to our <a href="http://feeds2.feedburner.com/quizzpot-en">Feeds</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.quizzpot.com/2009/11/loading-forms-remotely/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>A calendar to capture dates</title>
		<link>http://www.quizzpot.com/2009/10/a-calendar-to-capture-dates/</link>
		<comments>http://www.quizzpot.com/2009/10/a-calendar-to-capture-dates/#comments</comments>
		<pubDate>Tue, 20 Oct 2009 17:38:13 +0000</pubDate>
		<dc:creator>Hazel</dc:creator>
				<category><![CDATA[English]]></category>
		<category><![CDATA[Ext JS]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://www.quizzpot.com/?p=1998</guid>
		<description><![CDATA[Today we will talk about the DateField component. This component provides an "input" type formatted date from a calendar very well stylized. DateField in Ext JS is a very complete component since it offers many configuration options. In this tutorial we will discuss the most important settings.]]></description>
			<content:encoded><![CDATA[<h3>Resources</h3>
<p>Before you start this tutorial you need to <a href="http://www.quizzpot.com/wp-content/uploads/2009/06/dateField.zip">download the resources</a>. Just remember that this tutorial belongs to the chapter of Forms and at end of the chapter we will add the DateField to our final form, but to avoid confusions, let&#8217;s do this tutorial in a separate file.</p>
<p>You can <a href="http://www.quizzpot.com/demos/extjs/forms/dateField.html">see the demo</a> of what we&#8217;ll do in this tutorial, the following images show the component we will see today.</p>
<div class="example"><img src="http://www.quizzpot.com/wp-content/uploads/2009/06/date1.jpg" alt="datefield's image" /><img src="http://www.quizzpot.com/wp-content/uploads/2009/06/date5.jpg" alt="datefield's image" />
<p>The component DateField</p>
</div>
<h3>Packaging the tutorial.</h3>
<p>Let&#8217;s package our code before we start.</p>
<pre name="code" class="javascript">
Ext.ns('com.quizzpot.tutorial');

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

com.quizzpot.tutorial.DateFieldTutorial = {
	init: function(){
		//the code goes here
        }
}
Ext.onReady(com.quizzpot.tutorial.DateFieldTutorial.init,com.quizzpot.tutorial.DateFieldTutorial);
</pre>
<p>By now you all must know what the previous code is doing, otherwise I recommend you read the <a href="http://www.quizzpot.com/2009/04/packages-and-namespace/">tutorial</a> that has a better explanation.</p>
<h3>Window</h3>
<p>Right now we&#8217;re going to create a window that will contain different types of settings for the DateField component we will create, this window will help us to visualize the DateFields we will use in this tutorial.</p>
<pre name="code" class="javascript">
var win=new Ext.Window({
	title: 'DateField demo',
	bodyStyle:'padding: 10px',//adding padding to the components
	width:400,
	height:360,
	layout:'form'		//organization of the components
});
win.show();
</pre>
<p>We have explained the configuration properties in the chapter of <a href="http://www.quizzpot.com/2009/07/a-floating-window/">windows and panels</a>, if you have doubts regarding the previous code you can review the chapter. About the configuration &#8220;layout&#8221;, I won&#8217;t explain in details about it since we&#8217;ll discuss about it later on, for now just keep in mind that assigning the value &#8220;form&#8221;, the fields will be organized in the window just like form.</p>
<div class="example"><img src="http://www.quizzpot.com/wp-content/uploads/2009/06/date2.jpg" alt="datefield image" />
<p>The window that will contain the date fields</p>
</div>
<h3>Simple DateField</h3>
<p>Once created our window, we will create our first DateField component.</p>
<pre name="code" class="javascript">
 var dateField = new Ext.form.DateField({
	fieldLabel: 'Date',
	emptyText:'Insert a date...',
	format:'Y-m-d',
	width: 150
});
</pre>
<p>In the previous code we use three properties, let&#8217;s see a description of them:</p>
<p><em>format</em>: this property defines the date format to display in our field. The format &#8216;Y-m-d&#8217;, defines a format like &#8220;year-month-day&#8221;. If  you want to see more formats you can check the API of the <a href="http://www.extjs.com/deploy/dev/docs/?class=Ext.form.DateField">Date object</a>.</p>
<p><em>fieldLabel</em>: this is the common property for all components, this property sets the text that will appear next to the component; through this property we&#8217;ll show the user to type of information he/she needs to enter in the field, so make sure you write a descriptive text.</p>
<p><em>emptyText</em>: we have seen this property previously, it&#8217;s the default text to place into an empty field, it is very useful to display a hint to the user.</p>
<p>Let&#8217;s add the component to our window:</p>
<pre name="code" class="javascript">
var win=new Ext.Window({
	bodyStyle:'padding: 10px',
	width:400,
	height:360,
	items: dateField, //&lt;-- assigning the datefield
	layout:'form'
});
win.show();
</pre>
<div class="example"><img src="http://www.quizzpot.com/wp-content/uploads/2009/06/date3.jpg" alt="datefield image" />
<p>A basic DateField</p>
</div>
<h3>A restricted DateField</h3>
<p>What happens if we want to show that our dates are restricted? For example if we want the user to select days from today. For this type of configuration there are some properties we need to add to our DateField.</p>
<pre name="code" class="javascript">
var dateFieldR=new Ext.form.DateField({
	fieldLabel: 'Date from today',
	emptyText:'Insert a date...',
	format:'Y-m-d',
	minValue: new Date(), //&lt;-- min date is today
	maxValue:'2010-08-28', // &lt;-- max date
	value:new Date() // &lt;-- a default value
});
</pre>
<p>Description of the properties:</p>
<p><em>minValue</em>: is the the minimum value allowed in our component DateField.</p>
<p><em>maxValue</em>: is the the maximum value allowed in our component DateField.</p>
<p><em>value</em>: the value to initialize the field with (defaults to undefined).</p>
<p>As you can see in this example, in the property &#8220;maxValue&#8221; I&#8217;ve put a date directly, I did it only to show that we can also assign a date using a String and the component will make the necessary data conversions.</p>
<div class="example"><img src="http://www.quizzpot.com/wp-content/uploads/2009/06/date4.jpg" alt="datefield image" />
<p>A restricted DateField</p>
</div>
<h3>Conclusions</h3>
<p>The DateField component is a fairly complete component and the configuration options it gives us are mostly the same as the TextField component with variations specific to the component, this is because DateField inherits from TextField.</p>
<p>This tutorial was short but to see the different configurations we can have a better understanding of the functionality of the DateField component. In the next tutorial we will discuss two nice components: the textareas and HTML editors. </p>
<p>As always, your comments and suggestions are very welcome, just remember to follow us on <a href="http://twitter.com/quizzpot">Twitter (@quizzpot)</a> to be updated.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.quizzpot.com/2009/10/a-calendar-to-capture-dates/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Combo box loaded dynamically and remotely</title>
		<link>http://www.quizzpot.com/2009/10/combo-box-loaded-dynamically-and-remotely/</link>
		<comments>http://www.quizzpot.com/2009/10/combo-box-loaded-dynamically-and-remotely/#comments</comments>
		<pubDate>Fri, 16 Oct 2009 20:49:26 +0000</pubDate>
		<dc:creator>Hazel</dc:creator>
				<category><![CDATA[English]]></category>
		<category><![CDATA[Ext JS]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://www.quizzpot.com/?p=1966</guid>
		<description><![CDATA[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.]]></description>
			<content:encoded><![CDATA[<h3>Resources</h3>
<p>Before you start this tutorial, you need to <a href="http://www.quizzpot.com/wp-content/uploads/2009/06/combobox.zip">download the resources</a>. 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&#8217;ll do this tutorial in a separate file.</p>
<h3>Packaging the tutorial.</h3>
<p>Let&#8217;s package our code before we start.</p>
<pre name="code" class="javascript">
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);
</pre>
<h3>Window</h3>
<p>At this moment we&#8217;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.</p>
<pre name="code" class="javascript">
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();
</pre>
<p>We can highlight the property &#8220;<em>layout:&#8217;form&#8217;</em>&#8221; from the code above, because for a window the layout by default is &#8220;<em>auto</em>&#8220;, so we needed to overwrite the property to display the components distributed as a form.</p>
<p><!-- imagen1 --></p>
<div class="example"><img src="http://www.quizzpot.com/wp-content/uploads/2009/06/combos1.jpg" alt="Window" />
<p>Window that will contain the ComboBox</p>
</div>
<h3>Local ComboBox</h3>
<p>After creating the window, let&#8217;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.</p>
<pre name="code" class="javascript">
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
});
</pre>
<p>The above code creates a ComboBox with data naming some existing PHP Frameworks. Let&#8217;s see the meaning of the properties that we can use to configure our ComboBox:</p>
<p><em>forceSelection</em>: This option forces the user to select a value from the combo, this is independent of the type of validation <em>allowBlank</em>, which we will discuss in the next tutorial.<br />
<em>store</em>: is the data source that our combo will show, we&#8217;ve talked about this component previously.<br />
<em>emptyText</em>: this is the text displayed when we haven&#8217;t selected anything in our combo.<br />
<em>triggerAction</em>: this option indicates the action to execute when the trigger is clicked.<br />
<em>editable</em>: the combo can not be edited, which means you can not write any value on it.<br />
<em>hideTrigger</em>: setting this property to <em>true</em> we make the combo to be displayed without the small down arrow icon (&#8220;trigger&#8221;).<br />
<em>minChars</em>: 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.</p>
<p>Let&#8217;s add the ComboBox to our window:</p>
<pre name="code" class="javascript">
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();
</pre>
<p><!-- imagen2 --></p>
<div class="example"><img src="http://www.quizzpot.com/wp-content/uploads/2009/06/combos2.jpg" alt="Simple Combo" />
<p>A Combo loaded with local information</p>
</div>
<h3>Remote ComboBox</h3>
<p>Now let&#8217;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.</p>
<p>In the remote ComboBox we will use for our source of data a <a href="http://www.quizzpot.com/2009/06/reading-information-in-json-format/">JSON type store</a>, I won&#8217;t explain this component because we already talked about it in <a href="http://www.quizzpot.com/2009/06/reading-information-in-json-format/">previous tutorials</a>.</p>
<p>The JS code will go like this:</p>
<pre name="code" class="javascript">
//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'
});
</pre>
<p>As you can see in the properties of our combo we added the property <em>displayField</em>, with this property we tell the ComboBox the information to display, in this case is going to show only the data &#8216;name&#8217; and using the property &#8220;<em>valueField</em>&#8221; we specify which field the store is going to use as a &#8220;value&#8221;, it can be a numeric ID but in this case we use the name.</p>
<p>Finally we need to add the combo we just created to the window, as follows:</p>
<pre name="code" class="javascript">
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();
</pre>
<p><!-- imagen3 --></p>
<div class="example"><img src="http://www.quizzpot.com/wp-content/uploads/2009/06/combos3.jpg" alt="Remote Combo" />
<p>A ComboBox loaded remotely using Ajax</p>
</div>
<p>With PHP code we&#8217;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 &#8220;hardcoded&#8221; in arrays.</p>
<pre name="code" class="php">
&lt;?php
	$dataDB = array(
				array(
					&quot;name&quot;=&gt;&quot;MySQL&quot;,
					&quot;desc&quot;=&gt;&quot;The world's most popular open source database&quot;,
					&quot;logo&quot;=&gt;&quot;mysql.png&quot;
				),
				array(
					&quot;name&quot;=&gt;&quot;PostgreSQL&quot;,
					&quot;desc&quot;=&gt;&quot;The world's advanced open source database&quot;,
					&quot;logo&quot;=&gt;&quot;postgresql.png&quot;
				),
				array(
					&quot;name&quot;=&gt;&quot;Oracle&quot;,
					&quot;desc&quot;=&gt;&quot;The world's largest enterprise software company&quot;,
					&quot;logo&quot;=&gt;&quot;oracle.png&quot;
				),
	);

	$o = array(
			&quot;num&quot;=&gt;count($dataDB),
			&quot;data&quot;=&gt;$dataDB
		);
	echo json_encode($o);
?&gt;
</pre>
<p>As you can see, we have defined the fields the JsonStore accepts, also with the function <em>json_decode</em> we are generating the JSON from a PHP array.</p>
<h3>Formatted Data</h3>
<p>Okay now let&#8217;s give a format to our information, we will use the information from our remote combo, so let&#8217;s get started. Let&#8217;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.</p>
<p>To format our ComboBox we need a template, so we&#8217;re going to assign the template to our new combo by using one of its properties ( &#8220;tpl&#8221; of &#8220;template&#8221;). The template is written in HTML with some CSS so the information is display in detail.</p>
<pre name="code" class="javascript">
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('&lt;tpl for=&quot;.&quot;&gt;&lt;div class=&quot;search-item&quot; style=&quot;background-image:url({logo})&quot;&gt;&lt;div class=&quot;name&quot;&gt;{name}&lt;/div&gt;&lt;div class=&quot;desc&quot;&gt;{desc}&lt;/div&gt;&lt;/div&gt;&lt;/tpl&gt;'),
	displayField:'name'
});
</pre>
<p>The properties that appear now are:<br />
<em>tpl</em>: 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 &#8220;<em>Ext.XTemplate</em>&#8220;, 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.</p>
<p><em>itemSelector</em>: this property tells us which property of the DOM is going to trigger the &#8220;select&#8221; event of our combo.</p>
<p>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:</p>
<pre name="code" class="css">
	.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;
	}
</pre>
<p><!--imagen4--></p>
<div class="example"><img src="http://www.quizzpot.com/wp-content/uploads/2009/06/combos4.jpg" alt="Customized Combo" />
<p>ComboBox customized with a template</p>
</div>
<h3>A variation of the ComboBox</h3>
<p>There&#8217;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.</p>
<pre name="code" class="javascript">
var timeField=new Ext.form.TimeField({
       	fieldLabel: 'Time Field',
       minValue: '4:00',
       maxValue: '23:59',
       increment: 15,
       format:'H:i',
       name:'cb-time'
});
</pre>
<p><!--imagen5--></p>
<div class="example"><img src="http://www.quizzpot.com/wp-content/uploads/2009/06/combos5.jpg" alt="TimeField Combo" />
<p>A Combo with time</p>
</div>
<p>As we can see, we have created a new ComboBox that shows data in time format without any problems.<br />
Let me explain some of its properties:<br />
<em>minValue</em>: is the minimal value that will be shown in our field.<br />
<em>maxValue</em>: is the maximum value that will be shown.<br />
<em>increment</em>: the number of minutes between each time value in the list.<br />
<em>format</em>: the format of the time we&#8217;re going to display.</p>
<h3>Conclusions</h3>
<p>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.</p>
<p>To see more benefits of this component do not forget to check the <a href="http://www.extjs.com/deploy/dev/docs/">ExtJS API Documentation</a>.</p>
<p>If you have any questions or suggestion don&#8217;t forget to leave a comment and follow us on <a href=" http://twitter.com/quizzpot">Twitter (@quizzpot)</a> to be updated.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.quizzpot.com/2009/10/combo-box-loaded-dynamically-and-remotely/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>
