Zend Framework: using JSon and Prototype for filling form on fly

2 Apr

I used JSon for the first time in my application today. Zend provide a very easy way to create JSon response.

In this article I would use Prototype to make ajax call. Hopefully you will know a bit about Prototype. Anyway if not, it’d not be a hard job to understand it after reading my article.

So let’s get started.

Consider you have the following form.

Zend Form

Zend Form

The scenario is

When user select name from the dropdown, the entire form is filled with the data from the database for that particular user.

For this purpose you would need to have a controller/Action(s), a model and template file.

In your form attach the following attrib to your name element as

$name = $this->createElement(‘select’,’name’);

$name->addMultioptions(array(

‘select’=>'[select]’,

‘1’ => ‘Faheem’,

‘2’ => ‘Abbas’

));

$name->setAttrib(‘onchange’,’AutoFill(this.value)’);

In the lines above we first create a dropdown give it two values. And then attach javascript function “AutoFill” function using setAttrib method.

In your controller initialize your form and assign it to the view template as

$form = new MyCustomForm();

$this->view->form = $form;

Now in your view template file write the following.

Write the following javascript code.

<script>

function AutoFill(value)

{

new Ajax.Request(

“<?=$this->url(array(‘controller’=>’user’,’action’=>’getdata’))?>”,

{

method:’get’,

parameters: {id: value},

onSuccess: FillForm

}

);

}

function FillForm(rsp)

{

var card = eval(‘(‘ + rsp.responseText + ‘)’);

$(‘address1).value = card.items[0].address1;

$(‘address2’).value = card.items[0].address2;

$(‘postalcode’).value = card.items[0].postalcode;

}

</script>

To get response you will need to create an action and write the following code

<?php

class User extends Zend_Controller_Action

{

public function indexAction()

{

$form = new MyCustomForm();

$this->view->form = $form;

}

public function getdataAction()

{

$this->_helper->layout()->disableLayout();

$users = new Users();

$this->_helper->viewRenderer->setNoRender();

if ($this->getRequest()->isXmlHttpRequest()) {

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

$userData = $ users ->getData($id);

$dojoData= new Zend_Dojo_Data(‘id’,$userData,’id’);

echo $dojoData->toJson();

}

}

}

In the above code getdataAction is called using ajax call. In the first line we have disabled the layout, because we don’t need layout in case of ajax response. Next we create object of our model class(discussed later). Next we tell zend to disable view rendering.

In the next few lines we check for ajax request, get id, call our getData model method.

We then create dojo data object. This object provide a very useful method to convert data retrieved into json format. The method used is toJson().

In our model we have code like the following.

<?php

class Users extends Zend_Db_Table

{

protected $_name = ‘users’;

public function getData($id)

{

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

->from($this->_name,

array(‘id’,’address1′,’address2’….))

->where(‘id = ?’, $id);

$result = $this->getAdapter()->fetchAll($select);

return $result;

}

}

13 Responses to “Zend Framework: using JSon and Prototype for filling form on fly”

  1. Vivek April 8, 2009 at 7:59 pm #

    Hello Faheem
    First of all Thanks for posting this, its been great help!!
    I am attempting to do this. I get ‘Ajax’ is undefined error (javascript) from the autofill function. How do I make it recognize the object. Any missing paths or something?

  2. Faheem Abbas April 9, 2009 at 6:31 am #

    Yes Vivek,
    you will need to download latest version of prototype.js and include that as

  3. Vijay April 9, 2009 at 10:29 am #

    Hi,

    How I Fill the Dojo FilteringSelect Value by using Json?

    I try like this

    $(’myFilteringSelect).value = card.items.address1;
    or
    $(’myFilteringSelect).value = card.items;

    It is not working Can you pls tell how to do this

    Vijay

  4. Vijay April 9, 2009 at 10:31 am #

    Hi Vivek,

    Try this

    “new Ajax.Request(” to “new Ajax.Requesting(”

    It is working for me

    Vijay

  5. Vivek April 10, 2009 at 9:12 pm #

    Thanks Faheem, after including prototype.js it worked great!! Your blog have been a great help in working with Zend.
    I am also looking into file management through zend and files needs to be housed in Oracle table’s blob column. I didn’t see any support from Zend for handling this. Do you have any pointers that you can share?

  6. Faheem Abbas April 11, 2009 at 5:47 pm #

    Zend Framework provide Zend_File for handling files. You can have your contents and put them into blob. This will, however need to work a bit more. Give it try and hopefully you will do it.

  7. smita April 28, 2009 at 11:01 am #

    hi

    but still i am not able to call the function AutoFill()..This is not called up the controlled..it will be helpful to me if you reply to my queries

  8. roland May 13, 2009 at 7:46 am #

    Hi Vijay
    You can use dojo and bypass prototype all together if you want to use filterselect and combobox. For the onchange function, add the following line

    dijit.byId(‘address1’).attr(‘value’, (dijit.byId(‘myfilterselectid’).item ).address1);

  9. Lalit July 13, 2009 at 8:18 am #

    Hi Faheem ..
    My query was that if we write the javascript code in the view file and if we want to have the layout enabled , the javascript code would end up getting placed in the body of the page .. and this defeats the purpose ..
    Is there any other alternative of writing the javascript code so that it would end up being in the head section ..
    Also do you have a similar code for jQuery ??
    Thanks ..
    Cheers

  10. rakesh August 25, 2009 at 9:58 am #

    Hi Faheem,

    Thanks for nice tutorial..
    I m new to ZF and learning himself, i did one example of ajax in zf (with help of urs blog but i use simple form and prototype not dojo form). Its work fine (thanks🙂 )
    Now what i wanted is to create a drop down in my javascript func. from return value from controller and once i select any value i should assign it to a form.

    Assigning part is fine but i am not able to regenerate drop down since I only know passing value as text. So when i create my drop down in controller and echo it print html code as text .😦

    Could you please help me to solve this??

    Thanks
    Rakesh

  11. Rajesh Gurjar December 16, 2009 at 4:49 am #

    Hi All,

    I am facing problem in displaying blob image in zend using ajax.

    Please have any solution please reply

    Thanks
    Rajesh

  12. faraz January 25, 2010 at 9:33 pm #

    how can i including prototype.js.it is an row form

Trackbacks/Pingbacks

  1. Zend Form Remove Error Messages | Edmonds Commerce Blog - April 11, 2009

    […] Zend Framework: using JSon and Prototype for filling form on fly …Zend Framework: Creating custom Zend form « Zend FrameworkGrouping Form errors for display purpose […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: