Posts Tagged ‘extjs’
Vertical Checkbox Groups
While working on my usual project at work I encountered the need to solve the problem of having check boxes display in a vertical list, across several columns from a non numerically indexed PHP array. I came up with two solutions; one used Ext JS and one was plain PHP with some CSS thrown in for good measure. One thing I noticed was that this task is not as easy as it seems.
Take for example the following array.
$list = array('AL'=>"Alabama",
'AK'=>"Alaska",
'AZ'=>"Arizona",
'AR'=>"Arkansas",
'CA'=>"California",
'CO'=>"Colorado",
'CT'=>"Connecticut",
'DE'=>"Delaware",
'DC'=>"District Of Columbia",
'FL'=>"Florida",
'GA'=>"Georgia"
... and so on
I won’t paste the entire code as it’d just waste space.
To get that into a 4 column list proved rather tricky. My first attempt was using an Ext.FormPanel, combined with PHP to generate the array. Not a glamorous solution by any means but it worked .
Here’s the code. It’s pretty self explanatory. are in mind the list variable from above.
<script>
/**
* here we loop our $list variable creating some JSON objects
* which match the specification for an Ext.Checkbox
* The PHP you see just stops the last , being added to the list, IE chokes on that!
*
*/
var _list_items = [
< ?php $lastKey = count($list); $i = 0; foreach($list as $program_id => $program_name): $i++?>
{
boxLabel: '< ?php echo ucwords($program_name);?>',
name: 'programs[]',
inputValue : '< ?php echo $program_id;?>'
}< ?php echo ($i !== $lastKey) ? "," : "";?>
< ?php endforeach;?>
];
Ext.onReady(function(){
/*
Create our FormPanel variable in the usual panel way.
*/
var _fp = new Ext.FormPanel({
renderTo: Ext.getBody(),
frame:true,
title : 'States',
method: 'POST',
url : 'post.php', // dummy page, which spits back the variables passed through
width: 795,
autoHeight:true,
bodyStyle : {
padding: '10px'
},
/**
After seeing the examples of this it's pretty easy, the one thing to rememember is if you don't want a random
Colon (:) to appear in the top left when you enter no fieldLabel, use hideLabel, I think there's a bug for the Ext Boys.
*/
items : [{
xtype: 'checkboxgroup',
hideLabel : true,
id : "program_checkboxes",
itemCls: 'x-check-group-alt',
columns: 5,
vertical: true,
items: _list_items // our php generated list.
}],
// add some funky buttons. bbar is such a cool config option!
bbar : [
'->',
new Ext.Button({
text : 'Clear',
handler : function(){
_fp.getForm().reset();
},
style : {
display: 'inline',
margin : '0px 5px'
}
}),
new Ext.Button({
text: 'Save',
style : {
display: 'inline',
margin : '0px 5px'
},
handler: function(){
if(_fp.getForm())
{
_fp.getForm().submit();
}
}
})]
});
});
</script>
So that should be sufficient to get your Ext.FormPanel displaying check boxes vertically. What surprised me though, was the amount of processing it took to render! Reloading that simple script caused my Firefox to freeze on several occasions. Not sure why!
Anyway here’s how it looked;

After the serveral crashes I decided to try some PHP to lighten my mood. The solution I came up with is a little tricky to get your head around but, is very flexible, and doesn’t crash the browser so much. All it takes is a little PHP and CSS.
<div id="form-container"> < ?php // set the maximum columns as a hard limit. $max_cols = 4; // determine how many rows to output per column $perCol = round(ceil(count($list) / $max_cols)); // create two numerically indexed array of keys and values. // this is important, because our initial array is indexed by strings, we need to re index them. $names = array_values($list); $ids = array_keys($list); // now its a simple case of looping and creating a column out of a div each time. ?> < ?php for ($i = 0; $i < $max_cols; $i++):?> <div class="programcol"> <ul> < ?php for ($js = 0; $js < $perCol; $js++):?> < ?php if(strlen(current($names)) > 0):?> <li> <input type="checkbox" name="programs[]" value="<?php echo current($ids);?/>"> <label>< ?php echo ucwords(current($names));?></label> </li> < ?php endif;?> < ?php next($names); next($ids);?> < ?php endfor;?> </ul> </div> < ?php endfor;?> </div> < ?php /** * We loop down each time, iterating the array in sections, making a column out of each section. * I'm sure this can be improved upon! */ ?>
That generates the divs’ holding a list of columns, now to sprinkle on a little CSS to get the vertical styling.
<style>
body
{
font-family:tahoma;
font-size:10px;
}
#form-container
{
width:795px;
min-height:250px;
max-height:500px;
float:left;
}
.programcol
{
float:left;
width:195px;
height:auto;
text-align:left;
display:inline;
clear:none;
}
.programcol li
{
margin: 4px 0px;
height:12px;
padding:0.25em
}
.programcol li label
{
margin-left:4px;
position:relative;
top:-2px
}
</style>
…and we’re all good, we have vertical checkboxes across several columns! viola

Hope you liked this.
James
Ext.Ajax.request makes for Easy Ajax
Basic AJAX
Long time no post, today I want to show you how easy it is to make AJAX calls using ExtJs. With Ajax being all the rage these days, if you can’t call server side scripts from your JavaScript I’m afraid you’re site is being bagged as Web 1.0 (bla whatever.. as long as it works right?) So with progression in mind here’s how to do wonderful, wonderful Ajax things with ExtJs.
Basically, Ajax is sending a request from Javascript to a server side resource, and not forcing the entire page to reload in the process, just the bit you want to update.
- A stands for Asynchronous.
- J stands for JavaScript.
- A stands for umm and?
- X stands for XML.
So it’s a combination of alsorts, except I don’t know anyone who uses the XML part of it.
In code you simply set up an XmlHTTPRequest Object point it at a url and click go. But because of the different implementations of XmlHTTP Objects in the different browsers it’s easier and less painful to use a library like ExtJS.
There’s two things to bare in mind here before we start:
- The url can include a query string, but it’s cleaner to use the params collection.
- The parameter passed to the success and failure callback functions is an XmlHttpRequest Object, not the response text from the server.
- The success function will be called if your HTTP request was successful (your server returned HTTP response code 200) e.g. you didn’t make a call that got an HTTP 404 error or 500 error.
- If you got an HTTP error the failure function would be called into action.
Ext.Ajax.request({
url : 'my-server-side-script.php',
params : {
name : 'James',
age : 26
},
success: function(objServerResponse){
alert(objServerResponse.responseText); // outputs whatever was returned from the server in an alert window
},
failure : function(objServerResponse){
}
});
When this is called via an onclick, onload, or when ever you choose to call it will automatically send a HTTP request to your server side script with the specified parameters. Other code will carry on running and when the request is complete it will execute the function success or failure regardless of what other javascript code has executed since your request started. Think of it as you (or your mum) putting on your washing machine, and going out for half an hour to do some shopping, the washing machine (ajax request in this case) carries on working regardless of who set it off. Once your wash has finished, you’ve got to go and empty the washer, so once your request has finished you’e got to take some action with your code (this is the call back function success or failure). In this function you can decide what to do with the data returned form the server, as you would decide weather or not to tumble or hang out your clothes?
Good analogy right?? ![]()
The code on your server can take as long as it wants to execute but its best not to leave your javascript waiting around for more then 30 seconds.
JSON
So whats the easiest way to return data from a server side script. I’ve seen a few ways of doing this. Easiest and by far the most easily breakable way is to simply have your server script echo some text back and then check for that text in your success function, thus:
< ?php // your server side code here echo $success == true ? "success" : "failed";
That will output the text success or failed depending on how you came ot that conclusion on the server side. All your success callback function would do is check the responseText property like so:
Ext.Ajax.request({
url : 'my-server-side-script.php',
params : {
name : 'James',
age : 26
},
success: function(objServerResponse){
if(objServerResponse.responseText === 'success'){
alert("It Worked!");
} else
{
// server code failed but request was OK.
}
},
failure : function(objServerResponse){
alert("Sorry, there was a server Error!");
}
});
Using JSON to analyse the response from the server not only means you can use server data as JavaScript objects but you can also take advantage of sending more data back from the server, in a well structured form.
I program in PHP and whenever I use Ajax I make sure to have the JSON extension installed. Here’s how I usually return JSON from a PHP script. Look for the potential for returning more server side data.
$returnData['success'] = false; $returnData['message'] = "Sorry, we were unable to validate your details"; $returnData['user_id'] = 123456; $returnData['timeOnSite'] = "1 minute"; echo json_encode($returnData); die();
The above code outputs the return data as json, text basically – this data can then be converted to javscript objects using Ext.decode for use in your call back function.
success : function (objServerResponse){
// convert to javascript objects.
var server_data = Ext.decode(objServerResponse.responseText);
if(server_data.success === false)
{
alert(server_data.message);
}
}
You can see how easy it is to return useful data from your Ajax calls and then use it in the client side code. A much more effective use of an HTTP request I’d say!
Recommended Reading
- Json for the Masses by Dustin Diaz
- Ext.Ajax Documentation – explore what other parameters and features you can set.
- Jesse James Garrett, the article that set the ball rolling
- Ajaxian – an Ajax blog
Please feel free to leave comments and suggestions below, I’ll try my best to answer them all!
I never knew Ext.DatePicker Existed!
Did you know Ext JS had a calendar control?
I didn’t until yesterday when after dissection our application at work I discovered we were using a 3rd party calendar from DynamicDrive.com.
Not only was this calendar a bit lame, it also added about three extra JavaScript files (setup file, main calendar file and a language file) and an extra CSS file.
The speed heads out there will tell you that that equals 4 extra http requests, which even if cached is still an overhead if you’re including JavaScript libraries in your app too.
So I set about pulling the original calendar to pieces, mainly because it wasn’t working to start with. This was when I came across the Ext.DatePicker class. After stumbling on the MultiMonth Calendar.
So I figured seeing as though I now know Ext has its own calendar, why not chuck it in bro?
So here’s how it’s done. A basic calendar can be rendered thus:
Ext.onReady(function(){
// this is required for the tooltips.
Ext.QuickTips.init();
var dp = new Ext.DatePicker({
renderTo: Ext.getBody(),
listeners: {
'select': function(date_picker, date){
alert(date.getFullYear() + '-' + (parseInt(date.getMonth()) + 1) + '-' + date.getDay());
}
}
});
});
That gives a basic calendar control which when a date is clicked will display an alert with the date format of YYYY-MM-DD. Sooooo simple!! Much nicer then the calendar we were using to.
Floating the Calendar
From here I went a bit further, because the calendar needs to be in a floating div (and I’m too lazy to float it with CSS) I wrapped my calendar control in an Ext.Window (why not, it’s all there!)
Here is the code for a calendar in an Ext.Window
Ext.onReady(function(){
Ext.QuickTips.init();
// define the calendar.
var dp = new Ext.DatePicker({
listeners: {
'select': function(date_picker, date){
// our form element.
var _frm = document.getElementById('date_picker_form');
// date value form inpuit
var _set_day = document.getElementById('set_day');
// set value and submit.
_set_day.value = date.getFullYear() + '-' + (parseInt(date.getMonth()) + 1) + '-' + date.getDate();
_frm.submit();
}
}
});
// define the window.
var win = new Ext.Window({
title: 'Date Picker',
closeable: true,
closeAction: 'hide',
id: 'calendar_ctrl',
hidden: true,
resizable: false,
renderTo: Ext.getBody(),
items: [dp] // the date picker from above.
});
});
Now this works fine in FireFox. Internet Explorer however showed a big box the height of the calendar across the page. Bit annoying!! But after a while I found the fix. In the Ext.Window definition add the following:
width:'200px',
height:'200px',
That fixed it for me, and didn’t compromise the calendar display.
That’s chopped out an extra 4 items from our app – another performance win!!
Recommended Reading
- http://extjs.com/deploy/dev/docs/ – DatePicker and Window
James