Archive | February, 2009

Zend Framework and prototype: Creating nice grid having ajax functionality

26 Feb

Few weeks back I tried to make a dojo grid. Though I successfully created one with the sorting functionality but didn’t succeeded in making that gird editable.

Yesterday I decided why not make a grid using some javascript and prototype library for providing on the fly editing functionality.

So here I am with a nice and cool grid with everything working.

At the end of this tutorial you will see a grid like.

Zend framework grid

Zend framework grid

 After clicking edit you would see grid like the following.

Zend Framework grid in edit mode

Zend Framework grid in edit mode

The grid now provide two options, save and cancel. If you click the save button the contents will be saved on the fly with AJAX request. However if you click the cancel, the grid will go back to its previous un editable format.

 Before going to discuss how to get this functionality I would like to tell you that if you haven’t read my previous post on making grid using Zend Framework, please read that. If haven’t read that article you will not be able to understand this tutorial.

 In my previous post I created a grid by creating my own view helper as

<?php

require_once ‘Zend/View/Helper/Abstract.php’;

class Zend_View_Helper_Grid2 extends Zend_View_Helper_Abstract

{

    public $sorting=null;

            public $view = null;

           

   public function setView(Zend_View_Interface $view)

   {

       $this->view = $view;

        return $this;

   }

           

    public function grid2($name, $fields = null,$paginator=null,$sorting=false)

    {

   

$sort = Zend_Controller_Front::getInstance()->getRequest()->getParam(‘sort’,’DESC’);

if($sort == ‘ASC’) {

$sort = ‘DESC’;

} else {

            $sort = “ASC”;

}

$output=”<div id='”.$name.”‘>”;

$output .= “<table class=’grid’>

                                                <thead>

                                                            <tr>”;

foreach($fields as $key=>$value) {

            $output .= “<th>”;

            if          ($sorting){

$output .= “<a href='”.

$this->view->url(array(‘sort’=>$sort,’by’=>$key)).”‘>”.$value.”</a>”;

            } else {

                        $output .= $value;

            }

            $output .= “</th>”;

}

 $output .= “</tr></thead>”;

 $output .=”<tbody>”;

 foreach($paginator as $p) {

            $output.=”<tr id=’row”.$p[‘id’].”‘>”;

            foreach($p as $record) {

                        $output .= “<td>”.$record.”</td>”;

            }

$output .=”<td id=’action”.$p[‘id’].”‘><a href=’#’

onclick=’edit(“.$p[‘id’].”)’>Edit<a></td>”;

$output.=”</tr>”;

 }

$output .= “</tbody>”;

            if($paginator) {

                        $output .=”<tfoot>”;

                        $output .=”<td align=’center’ colspan='”.count($fields).”‘>”;

                        $output.= $this->view->paginationControl($paginator,

                                                   ‘Sliding’,

                                                ‘pagination.phtml’);

                                                $output .=”</tfoot>”;

            }

$output .=”</table><div>”;

return $output;

    }

}

The only difference between my previous helper and this helper is

 

$output .=”<td id=’action”.$p[‘id’].”‘><a href=’#’

onclick=’edit(“.$p[‘id’].”)’>Edit<a></td>”;

 

If you look at the code you will understand that I have added extra “td” for making edit link and I have associated onclick event to the link. When you click on the link the edit javascript function is called.

Sorry I forgot one thing. I also associated id with the row attribute as

 

$output.=”<tr id=’row”.$p[‘id’].”‘>”;

 

Now as we have defined our view helper, its now time to edit our view template. We make the following modifications to our view template.

 

<?

            $fields = array(

                        ‘id’ => ‘ID’,

                        ‘firstname’ => ‘First Name’,

                        ‘lastname’ => ‘Last Name’,

                        ’email’ => ‘Email’,

                        ‘username’ =>’Username’,

                        ‘edit’ => ‘Action’

            );

            echo $this->grid2(

                                                ‘grd’,

                                                            $fields,

                                                                                    $this->paginator,

                                                                                                                                    true);

?>

 

If you compare this with the previous one, you will find that we have only added Action string to our field array.

However the most important thing in creating this gird is javascript code

The javascript I have defined look as

 

<script>

var editable=true;

function edit(id)

{         

            var row=$(“row” + id);

            var cells=row.getElementsByTagName(“td”);

            if(editable) {

                        cells[0].innerHTML=”<input type=’text’ name=’Id’ id=’Id’ value='”+ cells[0].innerHTML +”‘ size=’5’/>”;

            cells[1].innerHTML=”<input type=’text’ id=’firstname’ name=’firstname’ value='”+ cells[1].innerHTML +”‘ size=’15’ />”;

            cells[2].innerHTML=”<input type=’text’ id=’lastname’ name=’lastname’ value='”+ cells[2].innerHTML +”‘ size=’15’ />”;

                        cells[3].innerHTML=”<input type=’text’ id=’email’ name=’email’ value='”+ cells[3].innerHTML +”‘ size=’15’ />”;

            cells[4].innerHTML=”<input type=’text’ id=’username’ name=’username’ value='”+ cells[4].innerHTML +”‘ size=’15’ />”;

                        cells[5].innerHTML=”<a href=’javascript:#’ onClick=’save()’>Save</a>”

                                                                                    +”<br /><a href=’javascript:#’ onClick=’edit(” + id + “)’>Cancel</a>”;

                        editable=false;

            } else {

                        cells[0].innerHTML=$(‘Id’).value;

                        cells[1].innerHTML=$(‘firstname’).value;

                        cells[2].innerHTML=$(‘lastname’).value;

                        cells[3].innerHTML=$(’email’).value;

                        cells[4].innerHTML=$(‘username’).value;

                        cells[5].innerHTML=”<a href=’javascript:#’ onClick=’edit(” + id + “)’>Edit</a>”;

                        editable=true;

            }

}

function save() 

            new Ajax.Request(

            “<?=$this->url(array(‘action’=>’save’))?>”, {  method: ‘get’,

  parameters: {Id: $(‘Id’).value, firstname:$(‘firstname’).value,

                        lastname:$(‘lastname’).value, email:$(’email’).value, username:$(‘username’).value

                        }

  });

}

</script>

 

Nothing hard to understand.

In our edit method, we first get reference to our row element. And then call getElementByTagName java script method to get reference to all td elements of the row.

We then add input box to each td and give the value of the td to that input box.

The if condition specify that if we are not in editable mode, if condition is executed and we are taken to the edit mode otherwise we are taken back to the un editable condition.

In the save  method we make an ajax call using prototype Ajax request object.

Giving this method the url and the params.

 

In our controller saveAction we will have code like this.

 

public function saveAction()

{

            $users = new Users();

            $id = $this->_getParam(‘Id’);

            $data[‘firstname’] = $this->_getParam(‘firstname’);

            $data[‘lastname’] = $this->_getParam(‘lastname’);

            $data[’email’] = $this->_getParam(’email’);

            $data[‘username’]  = $this->_getParam(‘username’);

            $users->update($data,’id=’.$id);

            exit;

}

 

In the action User is our model. we get reference to our model then get params using _getParam() method, give these values to the update method.

And that’s it we are done.

JAVA : Creating data table in java

24 Feb

Since few week I am trying to work in java. It was always my dream to work in java when I
was university student and was doing my masters.
I was keen to complete my final year project in java but time didn’t allow us to get our
dreams true.
After working in php for more than year, I feel it would be worthy working in java, so
I m here to discuss one of its cool feature.

Creating data table in java is simple.

you will need to create an object of JTable, give it data and column names and that’s it.
let’s see how our code look like.

String[] columnNames = {“first name”,”last name”,”sports”};
Object[][] data = {{‘faheem’,”Abbas”,”Cricket”},{“shazil”,”Hassan”,”Soccer”}};

and now

JTable table = new JTable(data,columnNames);
getContentPane.add(JScrollPane(table));

it you want to have a table with some extra functionalities, you will need to create your our
own table model by extending it from AbstractTableModel and override some of the methods
provided by this abstract class.

I am giving its example as

class MyTableModel extends AbstractTableModel
{

String[] columnNames = {“first name”,”last name”,”sports”};

Object[][] data = {{‘faheem’,”Abbas”,”Cricket”},{“shazil”,”Hassan”,”Soccer”}};

public int getColumnCount()
{

return columnNames.length;

}

public int getRowCount()

{

return data.length;

}

public String getColumnName(int col)
{

return columnNames[col];

}

public Object getValueAt(int row, int col)
{

return data[row][col];

}

public boolean isCellEditable()

{

return true/false;

}

}

Now while creating object of JTable, write

JTable table = new JTable(new MyTableModel());

JQuery: ColorPicker Example

11 Feb

What? Zend guru working with pure JQuery.

You may have question in your mind.

Okay story begins here. Actually I tried my best to attach JQuery ColorPicker to my Zend Form text element using ZendX/JQuery form element, but didn’t succeed.

That was painful.

I tried and tried again, but result was not different. So I decided why not created it using the standard html input box and use java script to attach ColorPicker to that, instead of relaying on the Zend JQuery form elements and helpers.

So here I am, creating input box with JQuery ColorPicker.

I hopefully will try to implement same in the Zend Framework JQuery form elements that are shipped with latest version of ZF.

At the end of this article we will have a ColorPicker like the following.

 

JQuery Color Picker

JQuery Color Picker

 

Firs you will need to have following three files.

jquery.js

colorpicker.js

colorpicker.css

Download these three files from jquery website and place them in the js directory. Now

Write the following code in your file

<link rel=”stylesheet” href=”css/colorpicker.css” type=”text/css” />

<script type=”text/javascript” src=”js/jquery.js”></script>

<script type=”text/javascript” src=”js/colorpicker.js”></script>

<input type=”text” maxlength=”6″ size=”6″ id=”colorpickerField1″ value=”” />

<script>

$(“#colorpickerField1”).colorpicker({});

</script>

What we do in the above code.

  1. include necessary css and js files.
  2. define input box
  3. and

 

<script>

$(“#colorpickerField1”).colorpicker({});

</script>

 

The rest for us, attach a very nice and beautiful ColorPicker to our input box.

However we are not over here.

The real question is how to put color value in the input box?

Yes, a nice question.

So to achieve this you will need to replace

 

<script>

$(“#colorpickerField1”).colorpicker({});

</script>

 

with the following code.

 

<script>

$(‘#colorpickerField1’).ColorPicker({

      onSubmit: function(hsb, hex, rgb) {

                  $(‘#colorpickerField1’).val(hex);

      }

})

</script>

Isn’t it simple enough?

Zend Framework Dojo Form decorators example and usage

10 Feb

Zend Framework Dojo Form decorators example and usage

Nearly two months back I wrote an article on Zend_Form decorators. Many developers around the globe take help from that article and many post their comments.

As Zend has now done collaboration with Dojo and have provided helpers and form elements for creating nice form elements. They way of applying decorators to those elements also changed a bit.

After writing many articles on different Zend Framework and Dojo related topic, I feel that I’d discuss Zend_Dojo_Form decorators with the hope that someone might find it helpful.

If you have read my post on Zend_Form decorators, you will find this article pretty easy to understand. If you haven’t red that you will still get benefits of this article.

Before showing my code I would like to show the two form, one with the default decorators applied and the other with the decorators applied with setElementDecorators() method of the Zend_Dojo_Form.

The form with default decorators applied look as

dojo-form-with-default-decorators5

Zend Dojo Form with default decorators

By default Zend will wrap individual elements in “<dt>” tag and the entire form elements in “<dl>” tag.

 

The form with the decorators manually applied look as follows.

dojo-form-with-decorators-applied

Zend Dojo Form with decorators applied

Here we have wrapped individual elements in “<td>” tag and the entire elements in the “<table>” tag.

 

Now lets have a look at the code.

First the code without decorators applied.

<?php

class SimpleDojoForm extends Zend_Dojo_Form

{

            public function init()

            {

                        $this->setMethod(‘post’);

                        $this->setAttribs(array(

                                                ‘name’ => ‘masterform’

                                    ));

 

                        $this->addElement(

                                                ‘TextBox’,

                                                ‘textbox’,

                                                array(

                                                            ‘value’ => ”,

                                                            ‘label’ => ‘TextBox’,

                                                            ‘trim’ => true,

                                                            ‘propercase’ => true

                                                )

                                    );

 

                        $this->addElement(

                                                ‘DateTextBox’,

                                                ‘datebox’,

                                                array(

                                                            ‘value’ => ’07/06/2009′,

                                                            ‘label’ => ‘DateTexBox’,

                                                            ‘required’ => true

                                                )

                                    );

 

                        $this->addElement(

                                                ‘TimeTextBox’,

                                                ‘timebox’,

                                                array(

                                                            ‘label’ => ‘TimeTexBox’,

                                                            ‘required’ => true

                                                )

                                    );

                        $this->addElement(

                                                ‘CurrencyTextBox’,

                                                ‘currencybox’,

                                                array(

                                                            ‘label’ => ‘CurrencyTexBox’,

                                                            ‘required’ => true,

                                                            ‘currency’=>’USD’,

                                                            ‘invalidMessage’ => ‘Invalid amount’,

                                                            ‘symbol’ => ‘USD’,

                                                            ‘type’ => ‘currency’

                                                )

                                    );

                        $this->addElement(

                                                ‘NumberTextBox’,

                                                ‘numberbox’,

                                                array(

                                                            ‘label’ => ‘NumberTexBox’,

                                                            ‘required’ => true,

                                                            ‘invalidMessage’=>’Invalid elevation.’,

                                                            ‘constraints’ => array(

                                                                        ‘min’ => -2000,

                                                                        ‘max’=> 2000,

                                                                        ‘places’ => 0,

                                                            )

                                                )

                                    );

                        $this->addElement(

                                                ‘ValidationTextBox’,

                                                ‘validationbox’,

                                                array(

                                                            ‘label’ => ‘ValidationTexBox’,

                                                            ‘required’ => true,

                                                            ‘regExp’ => ‘[\w]+’,

                                                            ‘invalidMessage’ => ‘invalid non-space text.’

                                                )

                                    );

            }

}

In the code above we first extends our form from the Zend_Dojo_Form, set its method name and name attribute.

Next we add different Dojo elements and set their different attributes.

That’s it. Dojo Form with the default decorators applied.

 

To achieve the layout shown in the figure 2, you will need to add the following code after adding the elements to the Form.

 

$this->setElementDecorators(array(

 

‘DijitElement’,

‘Errors’,

            array(array(‘data’=>’HtmlTag’),array(‘tag’=>’td’)),

            array(‘Label’,array(‘tag’=>’td’)),

            array(array(‘row’=>’HtmlTag’),array(‘tag’=>’tr’))

 

));

 

This code wrap label and corresponding element in the “td” tag and both in “tr” tag.

 

$this->setDecorators(array(

                        ‘FormElements’,                       

                        array(array(‘data’=>’HtmlTag’),

array(‘tag’=>’table’,’cellspacing’=>’4′)),

                        ‘DijitForm’

                                    ));

 

This wrap the entire form elements in the “<table>” tag.

That’s it.

Zend Framework: creating your own grid helper

9 Feb

Grid is used in almost every application. So its better to create a gird view helper than to create a grid on each page where it needs.

In this article I am going to discuss how to create a helper for creating grid with a single line of code.

Although you can create view helper wherever you want and can use that helper only by adding path to that helper and than call that view helper in your view template, however here I am going to create a gird helper in the library/Zend/View/Helper directory where all the helper shipped with Zend reside.

So lets have a look.

First create Grid.php in library/Zend/View/Helper directory and place the following code in it.

<?php

require_once ‘Zend/View/Helper/Abstract.php’;

class Zend_View_Helper_Grid2 extends Zend_View_Helper_Abstract

{

 

public $view = null;

 

   public function setView(Zend_View_Interface $view)

    {

        $this->view = $view;

        return $this;

    }

   /* this constructor takes 4 args, name of the grid, header columns, paginator and the bool value sorting.

    public function grid ($name, $fields = null,$paginator=null,$sorting=false)

    {

 

// taking value of sort using Fron controller getRequest() method.

$sort = Zend_Controller_Front::getInstance()->getRequest()->getParam(‘sort’,’DESC’);

// checking and handling sorting.

if ($sort  ==  ‘ASC’) {

            $sort = ‘DESC’;

          }  else  {

            $sort = “ASC”;

         }

// start constructing the gird.

       $output=”<div id='”.$name.”‘>”;

        $output .= “<table class=’grid’>

                                                         <thead>

                                                                    <tr>”;

        // this foreach loop display the column header  in “th” tag.

foreach ($fields as $key => $value)  {

                            $output .= “<th>”;

                          // check if sorting is true, if so add link to the fields headers

 if          ($sorting){

                            $output .= “<a href='”.$this->view->url(array(‘sort’=>$sort,’by’=>$key)).”‘>”.$value.”</a>”;

                             }  else  {

                             $output .= $value;

                            }

              $output .= “</th>”;

                       }

                            $output .= “</tr>

                                   </thead>”;

                    // constructing the body that contain the records in rows and columns.

 $output .=”<tbody>”;

                      // this loop display the actual data.

foreach($paginator as $p) {

                        $output.=”<tr>”;

                            foreach($p as $record) {

                                             $output .= “<td>”.$record.”</td>”;

                                }

                          $output.=”</tr>”;

                    }

                   $output .= “</tbody>”;

                  // check if paginator is ture, if so then add paginator component to the table “tfoot”.

if($paginator) {

                           $output .=”<tfoot>”;

                           $output .=”<td align=’center’ colspan='”.count($fields).”‘>”;

            $output.= $this->view->paginationControl($paginator,

                             ‘Sliding’,

                             ‘pagination.phtml’);

                               $output .=”</tfoot>”;

                        }

        $output .=”</table><div>”;

           return $output;

    }

}

 

In the code above we first extend our helper form the Zend_View_Helper_Abstract class. All view helper classes extend this abstract class.

Next we define function setView(Zend_View_Interface $view). This function is necessary if you want to access variable assign to you view template in your helper class.

 The next method/constructor is the most important one. In constructor we are creating our gird.

The argument passed to this constructor are the name of the gird, fields array that will be displays as the column name of the grid.

The paginator variable is the object of paginator component.

In the fist lines we get the sort from the request if sent. Otherwise set its default value.

Next we create a table and check if paginator is set to true, if yes then we call paginator controller, passing it paginator instance, the type of the pagination, and the partial view helper.

That’s it, if you break the code you will easily understand what we are building.

 

After creating your helper class, its time to call it from your view template. Use the following code for this purpose.

<?

            $fields = array(

                        ‘id’ => ‘ID’,

                        ‘firstname’ => ‘First Name’,

                        ‘lastname’ => ‘Last Name’,

                        ’email’ => ‘Email’,

                        ‘username’ =>’Username’

            );

            echo $this->grid(

                                              ‘grd’,

                                                    $fields,

                                                              $this->paginator,

                                                                                                   true);

?>

 

 

cheers.

Zend Framework Db: even more advanced database queries

2 Feb

You may have custom of using/writing advanced queries in mysql. It often require writing complex queries if you are working on enterprise, large scale web application(s).

The use of joins can never be ignored.

Zend Framework developers have done tremendous job by providing simple method for implementing joins.

Lets look some examples of different type of joins.

Before discussing joins lets consider we have two tables, “authors” and “books”.

These are associated with author_id.

  1. Inner Join

The simplest query will be

$select = $this->_db->select()

->from(‘books’,array(‘col1’,’col2’…..))

->joinInner(‘authors’,’books.id=authors.bks_id’,array(‘col1’,’col3’…))

->where(‘where condition here’)

->order(‘column name ASC/DESC’);

  1. Left Join

$select = $this->_db->select()

->from(‘books’,array(‘col1’,’col2’…..))

->joinLeft(‘authors’,’books.id=authors.bks_id’,array(‘col1’,’col3’…))

->where(‘where condition here’)

->group(‘group by column name here’)

->order(‘column name ASC/DESC’);

  1. Right Join

$select = $this->_db->select()

->from(‘books’,array(‘col1’,’col2’…..))

->joinRight(‘authors’,’books.id=authors.bks_id’,array(‘col1’,’col3’…))

->where(‘where condition here’)

->group(‘group by column name here’)

->order(‘column name ASC/DESC’);

4. Full Join

$select = $this->_db->select()

->from(‘books’,array(‘col1’,’col2’…..))

->joinFull(‘authors’,’books.id=authors.bks_id’,array(‘col1’,’col3’…))

->where(‘where condition here’)

->group(‘group by column name here’)

->order(‘column name ASC/DESC’);

5. Cross Join

$select = $this->_db->select()

->from(‘books’,array(‘col1’,’col2’…..))

->joinCross(‘authors’,’books.id=authors.bks_id’,array(‘col1’,’col3’…))

->where(‘where condition here’)

->group(‘group by column name here’)

->order(‘column name ASC/DESC’);

Zend Framework : basic configuration

1 Feb

Zend Framework Quick Start (click for ppt presentation)

After writting seperate articles on different Zend Framework topics I recieved many email from newbie asking me to write an article on how to make initial configuration.

Although this must have been done in the beginning however its never to late. Clikcing the above link you will find a powever point presentation where i have discuss what are design patterns, especially MVC design patterns, how to make initail directory structure, bootstrap file and a simple hello world example.

I have made all these things as simple as possible for beginners.

Although it is not necessary to learn design patterns for working in the Zend Framework however it will better to have a atleast basic idea of some conceptual topics like design pattern and object oriented programming.  This will enable you to get most benefits out of the Zend Framework.

Beside giving definition of design patterns i have given an example of the directory structure and most importantly the bootrap file. 

This is the minimal code require in the bootstrap file for working with Zend Framework MVC.

I haven’t discussed topics like how to make database configuration, configuration for two step view and how to add helpers to you Zend Framework application. This is becuase when you will get used to the minimal difinition you will be able to learn how to make extra configuration in future.

And finally I have developed a simple “hello world” example for better understanding of how controllers and views work togather. You will also find an example of how to use models in your application.