What! A month off

You may have noticed a month lag between posts, or more likely you didn’t and I was just giving myself more credit than was due. I have spent the past month enjoying Thanksgiving, Christmas, and coding an update to the TakeStock app that I originally released in response to the first Sencha contest. I wanted to use the command line tools, see if there were any improvements in local storage, as last time around I had to fall back on SqlLite to get the data stored locally on the client machine. I also wanted to take a small stab at skinning an app using SASS and SCSS. Of course, I am now nearing the end of this experiment and have had some time to gather everything together in a presentation designed to give you all the resources you will need to build your first Sencha Touch app in one place. Here’s the post:

http://bit.ly/TFkRFe

 

Versions everywhere …. How to really use the Sencha Command Line Tools

What and Why
I wanted to take advantage of Senchas touch 2 and update the Take Stock app I built way back when touch was being released using version 0.97. Over the summer I went to the Touch training that Sencha provided in Manhattan and got really excited about the prospects of the sencha command line tools that allow you to build a streamlined (compressed) version of your app and deploy it across multiple platforms with a few easy commands. To do this, the builder will take just the classes that you need opposed to the entire javascript library and combine them with your code then minimize the code using the YUI compressor.

Using Sencha without the command line tools is like driving an 18 wheeler to deliver the neighborhood mail when a small jeep will do just fine – so I guess what I want to say is yes, if you want responsive apps you will have to learn to love the command line tools or deal with the fact that your app will be burdened with extra weight and needless requests.

In order for all of this to work, your app needs to adhere to the Sencha MVC structure, and your code has to be tight – how tight? In the DateFilter there is a trailing comma which ships with Sencha and was throwing off my build process while the app worked fine.

How

Remember reading ‘in the summer’ a few paragraphs back? It looks like Sencha has been very busy over the past few months releasing beta version after beta version, what hasn’t been too clear is the documentation or the naming  conventions of the old Cmd vs Command vs the Command Line tools in the SDK. The names are so similar the chances of you finding and trying to use the wrong documentation for the version you are using is damn near 100%, however, the improvements are worth all of the time invested, and I cannot imagine starting another project without using Sencha Command!

Easy Steps to a perfect install 

1. For Windows users make sure that you are installing everything from your profile otherwise chances are Ruby and Compass will give you errors, and Sencha Command uses both to create the CSS files for your new app during the build process.

2. Install RUBY by visiting http://www.ruby-lang.org/en/downloads/ and following the instructions for your operating system. If you are developing on a Mac Ruby is installed by default, however, you will need to follow the next few steps.

3. Install Compass (http://compass-style.org/install/ ). This can be done from the command line / or terminal by typing the following commands:

$ gem update –system
$ gem install compass

4. Ok, now here comes the tricky part, you have to install Version 3 of Sencha Command which can be found here for all platforms -> http://www.sencha.com/products/sencha-cmd/download.

5.) Now download Sencha Touch 2.1 or Extjs 4.1a. These are the only versions that will work with the new Sencha Command tools!

6.) Unzip your Sencha Touch or Extjs file to the root of your web directory. At this point you can safely refer to the Touch/Extjs files as your ‘SDK’.

Congratulations, you just installed the command line and set up your web folder, now let’s start a quick Sencha Touch app using the command line tools.

1.) Open the cmd window in Windows or terminal in everything else and change your directory to the ‘SDK’ otherwise known as the Extjs or Touch folder in your web root.

2) Now you will need to generate the basic MVC framework for your new Sencha Touch application, this can be done right from the command line by typing in the following command:

$ sencha generate app /path/to/your/app

3) You should now have a ‘starter’ application in the folder that you specified above (/path/to/your/app). The folder structure should look like this:

Notice that there is a .sencha folder which contains an app and workspace folder, inside the app folder there is a file named sencha.cfg, if you open this file you will see your app name, framework, and directory settings. This is where, you guessed it, you can change the name of your application.

Great, now you have the application set up, let’s look at the steps required to deploy the application to a production environment.

First let’s discuss what ‘builing’ an app does. If you take a look in your ‘SDK’ folder aka Sencha-Touch or extjs notice that there is a file named ext-all.js (around 1.2MB) or sencha-touch-all.js (around 900KB). The file name alludes to the fact that they contain all of the classes in ext or touch minus the UX classes. Chances are good that you don’t actually use all of the classes that are provided by sencha, so why force your users to download all the classes on top of your app.js and MVC javascript files?  If you open up the folder src in your extjs or sencha touch folder you can get a look at the sizes of the individual classes that make up ext-all or sencha-touch-all.

The builder will search your code for class dependencies and compile all of the classes that you need to run your application, next the builder will compile all of your views, models, stores, and controllers into one nice file. Finally, the builder takes the extjs javascript as well as your application javascript and merges the two into one single javascript file. After this is done, the builder then ‘minifies’ your javascript which saves additional space. You gain a few clear advantages:

To build your new app just type the following command in the terminal:

$ sencha app build

The first time you issue this command the builder will create a folder named ‘build’ in which will be a folder with your app name. This folder contains your different ‘builds’. The folder named production contains the – you guessed it – production version of your application. Inside you will find the all-classes.js file which is your code plus the extjs code minimized, an ext folder which contains the CSS and any UX files that you may need in addition to any themes, and finally, your resources. It’s the files in this folder that you should push to your production server, they are all that is needed to run your new faster, sleeker, sencha application.

This is just the beginning of what can be accomplished using the new command tools, I’ll try and post some instructions on creating models, alternate versions, and so forth in the future.

Re-selecting the last selected record after store load in extjs4

This is a very quick one but sometimes it’s the easy things that you have to keep searching for. I have some instances where …. …. Wait let’s make that in most of my apps a row click is what drives either a form load or some type of action. Sometimes I just have to reload the data grid; sometimes I just want to be able to re-select the last selected row after I load my data from the store again. You can accomplish this task in three easy steps:

First, you have to get the currently selected index like this:

var sel_idx = your_grid.getSelectedRowIndex();

Second, you will want to call your store load:

your_grid.getStore().load({
      callback: function() {  
      	if(sel_idx){         
		your_grid.getSelectionModel().select(sel_idx);  
	}
      }   
});

Notice the inclusion of this code inside the load function.

{
      callback: function() {  
      	if(sel_idx){         
		your_grid.getSelectionModel().select(sel_idx);  
	}
      }   
}

This makes sure that the record is selected after the data store loads, so if you wanted to do anything that requires that the store be loaded beforehand make sure you put it in one of these callbacks.

Some thoughts on Sencha Touch 2.0

Wow, I just started playing with Sencha Touch version 2 which you can now download, and which comes with an extjs 4 style API on the sencha website, and I was so impressed I spent a few hours this weekend ditching my entire ICD10 app that was being written in jquery mobile. Why? The one word answer is speed, both in development time, and performance. Unlike version 1 I could hardly tell if I was coding extjs or touch, they seemed to work and act the same, this is a great plus for someone with a 9 – 5 in extjs coding. As far as performance is concerned take a look at the two apps side by side, then try to do a search for a medical term like ‘strep’ and see how they both respond. Now, imagine this difference playing out on a mobile device and not your desktop.

jquery mobile ICD 10 app

Sencha Touch 2 ICD 10 app

In addition, it looks like phonegap was purchased by Adobe, and it is now easier than ever to package and create native app files from your html5 / javascript application code, although the ‘free’ aspect of it has fallen by the wayside, the time saved is well worth the cost.

Using Ext.DomQuery and ajax request to validate and submit plain old HTML forms



So you need to create a quick form which would be easy in plain old HTML but you want to throw in some client side validation, just the thing that javascript packages excel in. Your choices you think are to go ahead and overcomplicate your form by writing it in javascript using the packages and then heavily modifying the CSS to get just the right look (and we all know the number of DOM elements seems to increase exponentially when doing it this way) OR spending time rewriting validation functions that you know are built in if you were just able to get ext to look right! I built the following reusable validation and form submission function using some of ext’s util methods as well as some good old fashioned javascript, since all of the names are referenced by Ext’s DomQuery it becomes an abstract method that could be dropped into any project and connected to any form. Right now I am only making sure that there is text in any given field, however, I am sure with a bit of creativity you can extend this to work with all types of validation requirements! (hint: look into Ext.isNumber(), Ext.isDate() etc.. in the Ext util functions. And then think about the fact that you could make up your own attribute, for example vtype=”crazy_number”). First, we need a HTML form, so for this example the code below will render the form that you see here.

<form id="test_form" method="post " action="some_test.php">

<label for="first_name" >First  Name </label><img style="visibility:hidden" src="ext-3.2.1/resources/images/default/form/exclamation.gif" name="first_name_error" />
<input name=" first_name " type="text" onkeyup="javascript:changeStyles(this);" />

<label for="last_name" ><img style="visibility:hidden" src="ext-3.2.1/resources/images/default/form/exclamation.gif" name="where_from_error" />Where are you from? </label>
<select name="where_you_from"  >		
<option value="here" >Here</option>
<option value="there" >There</option>
<option value="everywhere" >Everywhere</option>
</select>

<input type="button" onclick="javascript:sf()" value="Save" style="width:100px;float:right;margin-top:15px;" class="x-panel-btns"  />
</form>
<br><br>&nbsp;

The form above is pretty straight forward, no fancy code, however, you will notice that there is a javascript function in the onclick event of our ‘submit’ button, and in fact there is no real submit button in the html sense. There are also functions on all of the text fields and text areas in the onKeyUp event which will alert the users to the fact that all fields in the form are mandatory. This is done via some CSS that which pulls from the Extjs library to give the invalid boxes the fancy red squiggly line and exclamation point when a value has not been entered and the user tries to press the submit button. The CSS that is required is below, just modify the path to the images to match your Extjs path.

var valid_style = '{border: 1px solid;background-color:#fff;border-color:#ccc;background-image:url(nothing.gif);padding-top:2px;padding-bottom:2px;}';
var invalid_style = '{border: 1px solid;background-color:#fff;background-image:url(/ext-3.2.1/resources/images/default/grid/invalid_line.gif);padding-top:2px;padding-bottom:2px;background-position:center bottom;background-repeat:repeat-x;border-color:#ccc;}';
var ex_pt_show = '{background-image:url(/ext-3.2.1/resources/images/default/form/exclamation.gif);background-repeat:no-repeat;}';
var ex_pt_hide = '{background-image:url(nothing.gif);background-repeat:no-repeat;}';

Next, the javascript that will fire when you submit the form and make sure that everything is valid before updating your back end database. Since you will be using ext to crawl the DOM you can add as many fields as you want to the code below and all you have to do is pass the form name into the validation function.

Ext.onReady(function(){

changeStyles = function(item){
   if ( item.value.trim().length==0){
	Ext.get(item.name).applyStyles(invalid_style);
	doSubmit = false;
	} else {
	Ext.get(item.name).applyStyles(valid_style);
	Ext.get(item.name + '_label').applyStyles(ex_pt_hide);
    }
 }	
function validation(form_id){
// Get all of the form elements		
var textBoxes = Ext.DomQuery.select('form[id=' +  form_id + '] >input[type=text]');  
var selectBoxes = Ext.DomQuery.select('form[id=' +  form_id + ']>select');  
var textAreas = Ext.DomQuery.select('form[id=' +  form_id + ']>textarea');
var doSubmit = true;
Ext.each(textBoxes,function(item,i){   
	// lets loop through the textfields and see if they have values
	if (item.value.trim().length==0){
		Ext.get(item.name).applyStyles(invalid_style); 
		doSubmit = false;
	} else {
		Ext.get(item.name).applyStyles(valid_style);
		Ext.get(item.name + '_label').applyStyles(ex_pt_hide);
	}
}); // end of loop through text fields
Ext.each(selectBoxes,function(item,i){   
	if (item.value.trim().length==0){
		Ext.get(item.name).applyStyles(invalid_style); 
		doSubmit = false;
	} else {
		Ext.get(item.name).applyStyles(valid_style);
		Ext.get(item.name + '_label').applyStyles(ex_pt_hide);
	}	
});
Ext.each(textAreas,function(item,i){   
	// lets loop through the text areas and see if they have values
	if (item.value.trim().length==0){
		Ext.get(item.name).applyStyles(invalid_style); 
		doSubmit = false;
	} else {
		Ext.get(item.name).applyStyles(valid_style);
		Ext.get(item.name + '_label').applyStyles(ex_pt_hide);
	}	
}); // end of loop through text areas
return doSubmit;
}
sf =  function(form_id){				
var doSubmit = validation(form_id);
if(doSubmit == true){
    alert('I would have submitted the form in real life!');
} else {
        alert('Please fill out all required forms!');
}
}
});

Note: The example form in this post only performs the validation on click, but you can see the code above for the implementation of a fully functional submit button.