Zend Framework

Archive for January, 2009

Zend Framework and dojo- Auto Complete Example

Posted by Faheem Abbas on January 27, 2009

Sorry this blog is deprecated.

Find latest version of this article here. http://zendgeek.blogspot.com/2009/07/zend-framework-and-dojo-auto-complete.html

Creation of auto complete in Zend Framework using dojo is like a piece of cake. In one of my previous post I discuss how to create filtering select and populate that using dojo and ajax.

Here I am going to discuss how to create auto complete with combo box. The auto complete textbox will automatically/dynamically fetch data from the database.

So lets get started.

First of all create following functions in you controller.

public function getForm()

{

if (null === $this->_form) {

$this->_form = new Zend_Form();

$this->_form->setMethod(‘get’)

->setAction(

$this->getRequest()->getBaseUrl() . ‘/test/process’

)

->addElements(array(

‘test’ => array(‘type’ => ‘text’, ‘options’ => array(

‘filters’        => array(‘StringTrim’),

‘dojoType’       => array(‘dijit.form.ComboBox’),

’store’          => ‘testStore’,

‘autoComplete’   => ‘false’,

‘hasDownArrow’   => ‘true’,

‘label’ => ‘Your input:’,

)),

‘go’ => array(‘type’ => ’submit’,

‘options’ => array(‘label’ => ‘Go!’))

));

}

return $this->_form;

}

In the above code define a function and create a form adding it a combo box.

The important attributes of the combo box are

dojoType, store and autocomplet.

Sorry this blog is deprecated.

Find latest version of this article here. http://zendgeek.blogspot.com/2009/07/zend-framework-and-dojo-auto-complete.html

Posted in Zend Framework | 11 Comments »

Zend Framework and JQuery: JQuery Date Picker

Posted by Faheem Abbas on January 25, 2009

Sorry this blog is deprecated.

“Read new version of this article here. code nicely formatted”, http://zendgeek.blogspot.com/2009/07/zend-framework-and-jquery-jquery-date.html

Nearly two months back I used dojo calendar in my application. Although dojo has extremely large library and provide very nice widgets like number spinner, horizontal scroller and more importantly gird, however the current calendar available is not good looking and provide only basic functionality. We were using JACS calendar before using dojo calendar in our application.

After working for a bit of time with dojo calendar we feel that we need JACS type calendar. We were looking for the latest dojo release for getting calendar with more functionality.

Today I find JQuery Date picker, which is similar to the JACS. As Zend Framework latest version now provide JQuery View helper and Form elements, so I decided to write article on it, so that developers using JQuery may find some useful information.

So lets look how to develop a nice and cool JQuery date picker.

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

Zend Frameworm and JQuery Date Picker

Zend Frameworm and JQuery Date Picker

Sorry this blog is deprecated.

“Read new version of this article here. code nicely formatted”, http://zendgeek.blogspot.com/2009/07/zend-framework-and-jquery-jquery-date.html

Posted in Zend Framework | 8 Comments »

Zend Framework and dojo: tricky checkbox

Posted by Faheem Abbas on January 22, 2009

Few weeks back, I used dojo check box in my Zend framework application. Scenario  was a bit different at that time. I was submitting Zend dojo form on the click event of the checkbox. When I created a form and submitted that onclik, It didn’t give me desired results.

I set its checked value to 1 and unchecked value to 0, however when I submited it always gave me a single value. I was looking for 0 and 1, but it always gave me 0. I thought that It was because I was not using proper submit button for the posting of form.

However when today I used checkbox in normal zend dojo form, it gave me the same result. Oh God, how to fix it.

However as I have played with dojo js files, so I got the solution.

Let’s tell you the trick.

First of all create check box as

 

$checkbox= $form->createElement(

                        ‘checkBox’,

                        ‘checkbox’,

                        array(

‘label’ => ‘Tricky check box’,

‘checkedValue’ => 1,

‘uncheckedValue’ => 0

)

);

Now add onclick event to this checkbox element as

$checkbox->setAttrib(‘onclick’,'changeValue()’);

 

Now in your view, where you display this form, write the following javascript function

<script>

function changeValue()

{

if(dijit.byId(‘checkbox’).checked){

            dijit.byId(‘checkbox’).setValue(‘1′);

} else {

            dijit.byId(‘checkbox’).setValue(‘0′);

            dijit.byId(‘checkbox’).checked=false;

}

}

</script>

 

The above code isn’t simple?

Hmm. First we see if we have checked the checkbox, if yes we assign value 1 to it, if not we assign it value 0 and set its checked status to false. This will uncheck the checkbox.

That’s it. Submit your form and you will get desired results.

Doesn’t it help you. Do you have smarter solution than this.

Tell me……

Posted in Zend Framework | 2 Comments »

Zend Framework Tutorial- simple signup and login authentication

Posted by Faheem Abbas on January 17, 2009

After writing separate articles on different Zend framework topics, its now time to write a full fledge tutorials. I am starting from a simple sign up and login authentication example and hopefully will discuss some advance topic in future.

So lets get started.

First create a table in your database by executing the following sql query.

CREATE TABLE ‘users’ (

‘id’ int(11) NOT NULL auto_increment,

‘firstname’ varchar(100) default NULL,

‘lastname’ varchar(100) default NULL,

‘email’ varchar(255) NOT NULL,

‘username’ varchar(100) NOT NULL,

‘password’ varchar(15) NULL,

PRIMARY KEY  (‘id’)

)

Next create a model against this table in your application/model/ directory. I am creating Users.php and writing the following code in it.

<?

class Users extends Zend_Db_Table

{

protected $_name=”users”;

}

?>

Now create a controller named AuthController.php in application/controllers/ directory and place the following code in it

<?

class AuthController extends Zend_Controller_Action

{

public function loginAction()

{

}

public function signupAction()

{

}

public function logoutAction()

{

}

public function homeAction()

{

}

}

?>

Sorry this blog is deprecated.

“Read new version of this article here”.http://zendgeek.blogspot.com/2009/07/zend-framework-sign-up-and.html

Posted in Zend Framework Tutorials | 13 Comments »

Zend Framework and Dojo: Creating Tabbed Form

Posted by Faheem Abbas on January 15, 2009

I have been playing with Zend framework and dojo for the last few weeks. Its really fun to create a nice and user friendly form in Zend framework using dojo.

Create a form in Zend framework and dojo will do the client side validation and formatting etc.

Today I am going to show you how to create and place form elements in different tabs.

At he end of this we will have a form like the following.

Zend Framework and dojo Tabbed Form

Zend Framework and dojo Tabbed Form

First we will need to create our form as

<?

class MyForm extends Zend_Dojo_Form

{

public function init()

{

$this->setDecorators(array(

‘FormElements’,

array(‘TabContainer’, array(

‘id’          => ‘tabContainer’,

’style’       => ‘width: 600px; height: 500px;’,

‘dijitParams’ => array(

‘tabPosition’ => ‘top’

),

)),

‘DijitForm’,

));

$subForm1 = new Zend_Dojo_Form_SubForm();

$subForm1->setAttribs(array(

‘name’   => ‘textboxtab’,

‘legend’ => ‘Text Elements’,

‘dijitParams’ => array(

‘title’ => ‘Text Elements’,

),

));

$subForm1->addElement(

‘ComboBox’,

‘combobox’,

array(

‘label’        => ‘ComboBox (select)’,

‘value’        => ‘blue’,

‘autocomplete’ => false,

‘multiOptions’ => array(

‘red’    => ‘Rouge’,

‘blue’   => ‘Bleu’,

‘white’  => ‘Blanc’,

‘orange’ => ‘Orange’,

‘black’  => ‘Noir’,

‘green’  => ‘Vert’,

),

));

$subForm1->addElement(

‘DateTextBox’,

‘datebox’,

array(

‘value’ => ‘2008-07-05′,

‘label’ => ‘DateTextBox’,

‘required’  => true,

)

);

$subForm2 = new Zend_Dojo_Form_SubForm();

$subForm2->setAttribs(array(

‘name’   => ‘toggletab’,

‘legend’ => ‘Toggle Elements’,

));

$subForm2->addElement(

‘NumberSpinner’,

‘ns’,

array(

‘value’             => ‘7′,

‘label’             => ‘NumberSpinner’,

’smallDelta’        => 5,

‘largeDelta’        => 25,

‘defaultTimeout’    => 1000,

‘timeoutChangeRate’ => 100,

‘min’               => 9,

‘max’               => 1550,

‘places’            => 0,

‘maxlength’         => 20,

)

);

$subForm2->addElement(

‘CheckBox’,

‘checkbox’,

array(

‘label’ => ‘CheckBox’,

‘checkedValue’  => ‘foo’,

‘uncheckedValue’  => ‘bar’,

‘checked’ => true,

)

);

$subForm2->addElement(

‘RadioButton’,

‘radiobutton’,

array(

‘label’ => ‘RadioButton’,

‘multiOptions’  => array(

‘foo’ => ‘Foo’,

‘bar’ => ‘Bar’,

‘baz’ => ‘Baz’,

),

‘value’ => ‘bar’,

)

);

$this->addSubForm($subForm1, ‘textboxtab’)

->addSubForm($subForm2, ‘editortab’);

}

}

?>

In the above code, beside extending our form from Zend_Dojo_Form, we set form decorators as

$this->setDecorators(array(

‘FormElements’,

array(‘TabContainer’, array(

‘id’          => ‘tabContainer’,

’style’       => ‘width: 600px; height: 500px;’,

‘dijitParams’ => array(

‘tabPosition’ => ‘top’

),

)),

‘DijitForm’,

));

Setting form decorators in this way will automatically put your sub forms in separate tabs.

Next we create two sub form, set their legend and add elements to them.

An the end we add sub forms to our form.

In controller, write

$form = new MyForm();

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

And in the view write

<?

Echo $this->form;

?>

That’s it. You will now see a nice user interface with tab container having sub form in each.

Posted in Zend Framework | 17 Comments »

Zend Framework and dojo-grid sorting example

Posted by Faheem Abbas on January 12, 2009

In my previous post “dojo-grid-in-zend-framework:creating-nice-and-cool-grid-in-php-using-zend-framework-and-dojo” I discuss how to creat nice and cool gird using Zend framework and dojo.

In this article I am going one step further and show you how easy it is to apply sorting to your dojo grid.

Please read my previous article befor writing this code.

In your model write

public function getJobsData($sort,$order)

{

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

->from($this->_name)

->order(” “.$sort.” ” . $order);

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

return $results;

}

If you compare this model with the previous one, you will find that we are passing tow extra parameter here and a line

->order(” “.$sort.” ” . $order);

This will sort our data according to the field we will click on.

Now In your controller, write

public function  recordsAction()

{

$jobs = new Jobs();

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

$sort=$this->getRequest()->getParam(’sort’);

}

if($sort==”"){

$sort=”id”;

}

if(strchr($sort,’-')){

$sort = substr($sort,1,strlen($sort));

$order = “Desc”;

} else {

$order=”Asc”;

}

$data= $jobs->getJobsData($sort,$order);

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

echo $dojoData->toJson();

exit;

}

Here we first check if we get ajax request. If yes, we get the value of the variable sort (dojo grid passed this as parameter when we click on it field), so we should not worry about it. Dojo grid either pass “field name” or field name with -ve sign.

we check if the sort variable has -ve sign attached with it. If we found we then remove the first character and set sort order to “Desc”. if we don’t find -ve sign we simply set sort order to “Asc”. we then call our model function

getJobsData() giving it $sort and $order variable. the result return is converted to json.

The last minor change we will do in our view template code

<div dojoType=”dojox.data.QueryReadStore” clientSort=”true jsId=”activeStore”, url=”records” ></div>

The only change we did is highlited in red.

That’s it nice and cool dojo grid with sorting.

Hopefully in next article I’d discuss how to implement pagging in the dojo grid.

Posted in Zend Framework | 3 Comments »

Dojo Ajax Combo box in Zend Framework: Creating Ajax combo box using dojo in zend framework

Posted by Faheem Abbas on January 9, 2009

Damn it. I wasn’t even imagining that Zend team has done such a wonderful job for creating ajax enabled application. Last night I was amazed by dojo grid and today by combo box.

I don’t have words to appreciate Zend developers.

Lets see how much time and efforts it takes to make a fabulous ajax enabled combo box using dojo and zend framework.

Create a controller and place the following code

<?

class TestController extends Zend_Controller_Action

{

function indexAction()

{

$form= new Zend_Dojo_Form();

$form->addElement(

‘ComboBox’,

‘foo’,

array(

‘label’       => ‘ComboBox (datastore)’,

’storeId’     => ’stateStore’,

’storeType’   => ‘dojo.data.ItemFileReadStore’,

’storeParams’ => array(

‘url’ => ‘records’,

),

‘dijitParams’ => array(

’searchAttr’ => ‘name’,

),

)

);

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

}

function recordsAction()

{

$db=Zend_Registry::get(‘db’);

$sql = ‘SELECT * FROM company’;

$result = $db->fetchAll($sql);

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

echo $dojoData->toJson();

exit;

}

}

We define our form as

$form = new Zend_Dojo_Form();

 

And combo box element to it. Few of it properties are important, such as storeId, storeType and storeParams. In the store Params we have given the url of the action.

Next we define our action which fetch data form the table and create Json response for us. That’s it we have done.

In view/scripts/index.phtml, only write

<? echo $this->form?>

 

Only one thing. Write following lines in your layout file

<? $this->dojo()->setDjConfigOption(‘usePlainJson’,true)

->addStylesheetModule(‘dijit.themes.tundra’)

->setLocalPath(“http://localhost/Zend/js/dojo/dojo/dojo.js”)

->addLayer(“http://localhost/Zend/js/dojo/dojo/dojo.js”);

echo $this->dojo();

?>

That’s it.  You will now see a nice and beautiful combo box sending ajax request and fetching data on the fly.

Posted in Zend Framework | 1 Comment »

Dojo grid in Zend Framework: Creating nice and cool grid in php using Zend Framework and Dojo

Posted by Faheem Abbas on January 8, 2009

“Create new version here”.http://zendgeek.blogspot.com/2009/07/create-dojo-grid-in-zend-framework-nice.html

About a month or two earlier when I used dojo calendar in my application and write article about the Zend Framework and dojo I was wondering why zend make collaboration with zend. But today when I created a grid using zend dojo I feel the real power of the dojo in Zend framework. In this article I am going to give a simple example and create a grid using Zend framework and dojo.

At the end of this tutorial we will have a grid like the following

Dojo Grid in Zend Framework

Dojo Grid in Zend Framework

So let’s feel the power of dojo in zend.

First execute the following query for creating a table.

CREATE TABLE ‘jobs’ (

‘id’ int(11) NOT NULL auto_increment,

‘title’ varchar(50) NOT NULL,

‘description’ text,

‘posted_date’ datetime default NULL,

PRIMARY KEY  (‘id’)

)

This will create a table in your database.

Create a model in your models directory and write the following code in it

<?php

class Jobs extends Zend_Db_Table_Abstract

{

protected $_name=’jobs’;

public function getJobsData()

{

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

->from($this->_name);

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

return $results;

}

}

?>

and save this table as Jobs.php

In the code above, we first extend our model from Zend_Db_Table_Abstract, define its name and define our custom function getJobsData() that fetch all the rows in the jobs table. We return the results as an array.

Next create a controller JobsController in you controller’s directory and place the following code in it.

<?php

class JobsController extends Zend_Controller_Action

{

public function  viewAction()

{

}

public function  recordsAction()

{

$jobs = new Jobs();

$data= $jobs->getJobsData();

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

echo $dojoData->toJson();

exit;

}

}

In the above code we create two action view and records. We have placed nothing in the view action. In the recordsAction, we create an instance of Jobs model class.and then call its getJobsData() method which will give us an array of records. Next we create an instance of Zend_Dojo_Data() and give the fetched data to it. And finally we echo the data converted it into the Json.

We don’t need to create a view for the records action because we have placed exit it the end of this action which will stop rendering of the view. As we will call this action form our grid view template page so no need to define phtml file for it.

However we will need to create template file for our viewAction. In scripts/views/ directory create view.phtml file and place the following code in it.

<?php

Zend_Dojo_View_Helper_Dojo::setUseDeclarative();

$this->dojo()->setLocalPath(‘http://localhost/Zend/js/dojo/dojo/dojo.js’)

->addStyleSheetModule(‘dijit.themes.tundra’)

->addStylesheet(‘http://localhost/Zend/js/dojo/dojox/grid/_grid/tundraGrid.css’);

echo $this->dojo();

?>

<script type=”text/javascript”>

dojo.require(“dojox.data.QueryReadStore”);

dojo.require(“dojox.grid.Grid”);

dojo.require(“dojo.parser”);

</script>

<body class=”tundra”>

<div dojoType=”dojox.data.QueryReadStore” jsId=”activeStore”, url=”records”></div>

<div dojoType=”dojox.grid.data.DojoData” jsId=”model” rowsPerPage=”20″ store=”activeStore”></div>

<table id=”activePastes” dojoType=”dojox.grid.Grid” model=”model” style=”height:300px; width:700px;”>

<thead>

<tr>

<th field=”id”>Id</th>

<th field=”title”>Title</th>

<th field=”description”>Description</th>

<th field=”posted_date”>Posted</th>

</tr>

</thead>

</table>

</body>

Keep in mind this is the main template file where we are creating our gird.

In the first statement I told zend to use declarative instead of programmatic behavior which is default. Next I set local path and add specific stylesheets. Then in the javascript code I used statement

Dojo.requre(‘dojox.data.’) etc

To include specific dojo js modules.

In the body tag I specify a class “tundra”. This is important for the stylesheet I have added.

Next tow div’s and table are  the main code for creating grid.

The first div fetch the records from the url specified. This url may be different if you fetch records form the other controller or source. Please specify valid url otherwise you will not get what you want.

The next div act as a bridge between our first div and the table. This div take data from the first div and give it to the table for display purposes.

Keep in mind that all the attributes of the div’s and table are compulsory. Removing any of the attribute may result in unvalid records or empty page. So define everything that I have defined. Once you become able to display your records, you can play with these attributes.

Posted in Zend Framework | 57 Comments »

Improve dojo performance in Zend Framework

Posted by Faheem Abbas on January 7, 2009

After using dojo calendar in my application, I feel that it take lot of time loading dojo js files. This not only bothered me but also the client I am working with. However yesterday when listen a webinar  of Methew -Zend framework architect and responsible for framework and dojo integration, I come to conclusion that the requests can be limited to one or two by using custom builds.

As I was new and was unable to understand it from the webinar, I visited dojo toolkit website and read article about custom builds there. Although that article can help you however they don’t have given how to use it with the Zend Framework.

So in this post I am going to discuss how you can improve performance of dojo by limiting the number of request.

So let’s get started.

First go to “dojo/util/buildscripts/profiles” and create foo.profile.js and write the following code in it.

dependencies={

 

 

layers: [

{

name: "custom.js",

dependencies: [

'dijit.form.Form',

'dijit.form.Button',

'dijit.form.DateTextBox',

'dijit.form.Checkbox'

]

},

],

prefixes:[

['dijit','../dijit'],

['dojox','../dojox'],

]

}

Save this file and open command prompt in window/linux

Now in script go to the util/buildscripts using command as

C:\> cd xampp/htdocs/Zend/js/dojo/util/buildscripts/

Keep in mind that you may have different directory structure. So you will need to change this path. Now write

C:\ xampp/htdocs/Zend/js/dojo/util/buildscripts>  build.bat profile=foo action=release

After executing

build.bat profile=foo action=release

You will find a new directory “release” created in you dojo directory. This is the compact version of the dojot toolkit.

Note: use build.sh instead of build.bat in the command if you are using linux.

Now this is the directory for your production. Copy this directory to your application and set your apths in the layout file as

$this->dojo()->setDjConfigOption(‘usePlainJson’,true)

->addStylesheetModule(‘dijit.themes.tundra’)

->setLocalPath(“/js/dojo/release/dojo/dojo/dojo.js”)

->addLayer(“/js/dojo/release/dojo/dojo/custom.js”);

echo $this->dojo();

Not that we have only setLocalPath and addLayer(). addLayer() contain path to the cutom file you create in the foo.profil.js. this file will be generate for you and will be placed in the realease/dojo/dojo/ directory.

Posted in Zend Framework | Leave a Comment »

cakePhp authentication example continued

Posted by Faheem Abbas on January 5, 2009

In previous post I discuss the basic and general usage of cakephp authentication. In this post I am going to code and explain how to write a simple sign up application. This article will not only cover authentication but also models, forms and view etc.

So lets get started.

First of all create a table named “user”  by executing the following sql query.

CREATE TABLE 'user' (

'id' int(11) NOT NULL auto_increment,

‘username’ varchar(30) NOT NULL,

‘password’ varchar(30) NOT NULL,

‘email’ varchar(255) NOT NULL,

‘created’ datetime NOT NULL,

‘modified’ datetime NOT NULL,

PRIMARY KEY (‘id’)

)

Now create a model in app/models with name user.php and write following code in that model.

 

<?
 

class User extends AppModel

{

var $name=’User’;

var $useTable=’user’;

var $validate=array(

‘username’ => array(

‘notempty’ => array(

‘rule’ => array(‘minLength’,1),

‘required’ => true,

‘allowEmpty’ => false,

‘message’ => ‘Enter Username’

),

‘checkUnique’ => array(

‘rule’ => array(‘checkUnique’,'username’),

‘message’ => ‘Name already taken. Choose another.’

)

),

‘password’=>array(

‘notempty’ => array(

‘rule’ => array(‘minLength’,1),

‘required’ => true,

‘allowEmpty’ => false,

‘message’ => ‘Enter Password’

),

‘passwordsimilar’=>array(

‘rule’ => ‘checkPasswords’,

‘message’ => ‘Passwords must match.’

)

),

‘email’ => array(

‘rule’ => ‘email’,

‘required’ => true,

‘allowEmpty’ => false,

‘message’ => ‘Enter valid email’

),

);

function checkUnique($data,$fieldName){

$valid = false;

if(isset($fieldName)&&($this->hasField($fieldName))){

$valid = $this->isUnique(array($fieldName=>$data));

}

return $valid;

}

function checkPasswords($data) {

if($data['password'] == $this->data['User']['password2hashed'])

return true;

return false;

}

}

Explanation:

First we extend our model form cakePhp AppModel class. By doing so, we inherit all the method of that class.

Next we define name of the model and the table (database table) used by this model class. We then define our validate array that is crucial for validating submitting data against the database table. This will insure that the data will not be inserted until and unless valid.

You can put as many table fields as you want and cake will do the rest for you.

You can clearly see in this array that we are defining validation rules for some of the table fields. The first one is the username. We will not insert data in the database until user enter a valid and unique name. if user enter empty username through form. He will be notified with error message. Similarly if he enter a name which already exist in the table another error message will be display saying that “username already taken choose another one”. Although cake provide us validation rules for “allowEmpty” and “required” to ensure that user don’t left fields empty, however to check uniqueness we will need to define our own rule. The lines

 

'checkUnique' => array(

‘rule’ => array(‘checkUnique’,'username’),

‘message’ => ‘Name already taken. Choose another.’

)

in our validate array call our custom defined method

function checkUnique($data,$fieldName){
                        }

$valid = false;

if(isset($fieldName)&&($this->hasField($fieldName))){

$valid = $this->isUnique(array($fieldName=>$data));

                        return $valid;

            }

in this function we check if the $fieldName is passed and is in the User table. If yes then we check its uniqueness by calling a mehod isUnique() provided by cakePhp and passing it the field data. If the name is not already taken, isUnique() method will return true, false otherwise. And at the end of the function we return this value.

 

Next we define validation rules for password field. Make sure that it is not empty and matched to the “confirm password”. Here again we define our own function for ensuring that both password match. The function

 

function checkPasswords($data) {

if($data['password'] == $this->data['User']['password2hashed'])

return true;

return false;
}

check that both password match. If not it will return false, data will not be inserted in the database table and user will be notified with “password must match” error.

Next we define validation rule for email field and make sure that user enter a valid email address.

That’s it we have now defined our own model and will go forward to create our controller and call this model on appropriate action.

So lets define our own controller.

In app/controllers create users_controller.php and write following code

 

<?php
 

class UsersController extends AppController {

var $name = ‘Users’;

var $uses=array(‘User’);

var $components = array(‘Auth’);

function beforeFilter(){

$this->Auth->allow(’signup’);

}

function signup(){

if (!empty($this->data)) {

if(isset($this->data['User']['password2']))

$this->data['User']['password2hashed'] =$this->Auth->password($this->data['User']['password2']);

$this->User->create();

if ($this->User->save($this->data)) {

$this->Session->setFlash(‘Congratulations! You have signed up!’);

$this->redirect(array(‘controller’ => ‘questions’,'action’=>’home’));

} else {

$this->Session->setFlash(‘There was an error signing up. Please, try again.’);

$this->data = null;

}

      }

}

}

Explanation:

We first extend our controller form AppController, define its name, model and components its uses.

Next we define beforFilter() method and allow singup action to be executed whether or not user is authentic.

The action “signup” is important. We are putting most of our code in this action.

First we check if the form is posted by checking the data as $this->data. If it is not empty we then check that the passowrd2 is set. If it is true then we create hashed password with the statement

$this-> Auth->password($this->data['User']['password2']);

and assign it to the $this->data['User']['password2hashed'];

this is important to save hashed password.

Next we call $this->User->create() to load the model and prepare it for the next action.

We then call save action of the model as

$this->User->save($this->data) by passing it the data posted. This function return true if data is successfully inserted in the database table.

If it return true we set flash message and redirect to the home page of the question controller otherwise we set error message to flash helper and set posted data to null.

 

We have now defined our model and controller, now its time to write our view code.

Create views/users/signup.ctp and write the following code in it.

 

<?php if($form->isFieldError('User.username')) e($form->error('User.username', null, array('class' => 'message'))); ?>
 

<?php if($form->isFieldError(‘User.password’)) e($form->error(‘User.password’, null, array(‘class’ => ‘message’))); ?>

<?php if($form->isFieldError(‘User.email’)) e($form->error(‘User.email’, null, array(‘class’ => ‘message’))); ?>

<h2>Sign Up</h2>

<?php e($form->create(‘User’, array(‘action’ => ’signup’)));?>

<fieldset>

<label for=”UserUsername” class=”usernamelabel”><span>

Your Name</span></label>

<?php e($form->text(‘username’, array(‘class’=> ‘fullwidth’))); ?>

<label for=”UserEmail” class=”emaillabel”><span>Your Email

</span></label>

<?php e($form->text(‘email’, array(‘class’=> ‘fullwidth’))); ?>

<label for=”UserPassword” class=”passwordlabel”><span>

Password</span></label>

<?php e($form->password(‘password’, array(‘class’=> ‘fullwidth’))); ?>

<label for=”UserPasswordRepeat” class=”passwordrepeatlabel”>

<span>Re Password</span></label>

<?php e($form->password(‘password2′, array(‘class’=> ‘fullwidth’))); ?>

<?php e($form->submit(‘Sign Up’, array(‘div’ => false,

‘class’ => ’submitbutton’))); ?>

</fieldset>

<?php e($form->end()); ?>

The code seem a bit complex, however it is very simple if you break it.

In the first three line we check for the error in case of submitting un valid form. If any of the error occur we display it.

 Next we create our our form and set its action.

 

That’s it we have now create a simple sign up application. If you point to

http://localhost/cake/users/signup/

you will see a simple sign up form. You can fill it and it will do everything for you.

Any question feel free to ask.

Posted in CakePhp | 1 Comment »