Sunday, 25 September 2011

Simple Add - Edit - Delete in Zend Framework

Normally all the new developers starts with zend quickstart application initially.
But it contains only code for adding and listing all the other functionalities should be searched from other websites.

Here I have developed a user management module in my first project, and this will contains the code for simple listing, add, edit and delete users from that site.

Here is the query for creating my user table.

CREATE TABLE IF NOT EXISTS `users` (
`userid` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL,
`password` varchar(50) NOT NULL,
`email` varchar(100) NOT NULL,
PRIMARY KEY (`userid`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=19 ;

By referring the quick start guestbook application you will get idea to create mapper classes and Table classes. Another things if you need to connect mysql database you need write these code inside the application.ini inside the configs folder.

under the [development : production] section :

resources.db.adapter = "PDO_MYSQL"
resources.db.params.host = "localhost"
resources.db.params.username = "root"
resources.db.params.password = ""
resources.db.params.dbname = "dbName"


NetBeans

You can develop your application in NetBeans or Zend Studio, here I am using NetBeans ,
so I refer to follow the NetBeans IDE .This is some usefull links and a video to use zend framework in NetBeans IDE.

http://blogs.oracle.com/netbeansphp/entry/using_zend_framework_with_netbeans

http://blogs.oracle.com/netbeansphp/entry/zend_framework_support_added

This video will contains the basic methods to follow in NetBeans IDE.

http://netbeans.org/kb/docs/php/zend-framework-screencast.html

After referring these links you will get an idea to create classes using zf commands.

You can create controllers / models / table classes by executing the zf commands.

Here , there is some important things you need to understand is When you created a controller class with name User, its name will be like UserController and by default this class will contains two functions.


public function init()
{
/* Initialize action controller here */
}

public function indexAction()
{
$user = new Application_Model_UserMapper();
$this->view->entries = $user->fetchAll();
}

When you browse http://localhost/project/public/users the code inside the indexAction() will be execute first. You can create another action by giving name like addAction, then URL must be like
http://localhost/project/public/users/add

In index action there will be already contain its view file as index.phtml in the views\scripts\user folder. By creating other actions in a controller you need to create its view file in this folder. If addAction is the function name then view file name should be add.phtml.
If any other phtml need to use this action you need write
$this->render('index'); this function at the end of the function addAction. Inside the quote will contains the name of the phtml file inside that view folder.

Thus by creating the mapper classes

$user = new Application_Model_UserMapper();// creating mapper class for user

$this->view->entries = $user->fetchAll();// fetching as object arrays

$user->fetchAll(); will return the data as array of objects.
You can view this by printing as print_r($user->fetchAll()); exit;

This $this->view->entries can be directly get from the phtml file of that controller thus for listing the users inside the phtml file will be like

Step 1 : Listing Page in index.phtml


<div id="divList">

<table width="675" cellpadding="0" cellspacing="0">

<tr>

<th><strong>Username</strong></th>

<th><strong>Email</strong></th>

<th><strong>Edit</strong></th>

<th><strong>Delete</strong></th>

</tr>

<?php foreach ($this->entries as $entry): ?>

<tr>

<td><?php echo $this->escape($entry->getUsername()) ?></td>

<td><?php echo $this->escape($entry->getEmail()) ?></td>

<td>

<a href="<?php echo $this->url(array('controller'=>'user','action' => 'edit'),'default',true)."?user=".$this->escape($entry->getUserid());?>">

<img src="images/edit.png" border="0" class='edit' height="20px" alt="edit" />

</a>

</td>

<td><a href="<?php echo $this->url(array('controller'=>'user','action' => 'delete'),'default',true)."?user=".$this->escape($entry->getUserid());?>"><img src="images/delete.png" class='delete' border="0" height="20px" alt="delete" /></a></td>

</tr>

<?php endforeach ?>

</table>

</div>



<div id="view-content" style="float:left;margin-top:20px;">

<a href="<?php echo $this->url(array('controller' => 'user','action' => 'add')); ?>">Add new user</a>

</div>


Inside the foreach you will get the ojects as $this->entries and can access by the function $entry->getUsername(), getter function inside the Application_Model_User model class.

You can see the this->url() function for providing the links to other pages with controller name and action name inside an array.

In the next step I will give how to create a new form for user add page. Form class can be created from commands or simply adding new class to forms folder with extending the Zend_Form library class.

Here is the code inside the form class User.php in forms folder

class Application_Form_User extends Zend_Form
{

public function init()
{
// Set the method for the display form to POST

$this->setMethod('post');
$this->setAttrib('class', 'jNice');

// Add the comment element
$this->addElement('text', 'username', array(
'label' => 'Username:',
'class' => 'text-long',
'required' => true,
'validators' => array(
array('validator' => 'StringLength', 'options' => array(0, 20))
)
));

// Add the comment element
$this->addElement('password', 'password', array(
'label' => 'Password:',
'required' => true,
'class' => 'text-long',
'validators' => array(
array('validator' => 'StringLength', 'options' => array(0, 20))
)
));

// Add an email element
$this->addElement('text', 'email', array(
'label' => 'Your email address:',
'class' => 'text-long',
'required' => true,
'filters' => array('StringTrim'),
'validators' => array(
'EmailAddress',
)
));

// Add an userid element
$this->addElement('hidden', 'userid', array(
'required' => false,
));

// Add the submit button
$this->addElement('submit', 'submit', array(
'ignore' => true,
'label' => 'Save User',
));

// And finally add some CSRF protection
$this->addElement('hash', 'csrf', array(
'ignore' => true,
));
}
}


After creating this form you need add theses codes inside the function addAction()

Step 2 : Add Page With Form

public function addAction()
{
$request = $this->getRequest();
$form = new Application_Form_User();

if ($this->getRequest()->isPost()) {
if ($form->isValid($request->getPost())) {

$newUser = new Application_Model_User($form->getValues());

$mapper = new Application_Model_UserMapper();

$mapper->save($newUser);

return $this->_helper->redirector('index');
}
}

$this->view->form = $form;
$this->render('add');
}

Here you may not need to add $this->render('add'); this code , because if the name is addAction then it wil automatically render the view file add.phtml .

After this you can browse to view the form as http://localhost/projname/public/user/add

Inside add.phtml


<div id="divList" style="padding-top: 20px;">

<fieldset>

<?php

$this->form->setAction($this->url());

echo $this->form;

?>

</fieldset>

</div>



Here you can see the function for setting the action for the form User

$this->form->setAction($this->url());

You need to implement all the classes in model folder after this for saving the data in database.

Step 2 : Edit Page With Form Data

Next Step is for edit these data, for that we need to load this in form or we need to populate this form with a row data in the table. Here is the code for doing the edit function.

public function editAction()
{
$request = $this->getRequest();

$mapper = new Application_Model_UserMapper();

$id = $this->getRequest()->getParam('user',0);

$form = new Application_Form_User();

if($id != 0)
{
$data = $mapper->fetchRow($id);
$form->populate($data->toArray());
}

if ($this->getRequest()->isPost()) {
if ($form->isValid($request->getPost())) {

$updateuser = new Application_Model_User($form->getValues());

$mapper->save($updateuser);

return $this->_helper->redirector('index');
}
}

$this->view->form = $form;
$this->render('add');
}


Here $id = $this->getRequest()->getParam('user',0); is for getting the query string id of the user for editing.

For populating the form data you need to write these code

if($id != 0)
{
$data = $mapper->fetchRow($id);
$form->populate($data->toArray());
}

$updateuser = new Application_Model_User($form->getValues()); will set the model class of the user and $mapper->save($updateuser); same function is used in mapper for add and edit you can view this in quickstart project.

The last step in the function $this->render('add'); , I already mentioned about this function in the add section ie, Since it is not addAction() we need to use this statement for rendering or using the view phtml file add.phtml.

Step 3: Delete From the list

At the listing page I have added the links for the delete button and it like


<a href="<?php echo $this->url(array('controller'=>'user','action'     => 'delete'),'default',true)."?user=".$this->escape($entry->getUserid());?>"><img src="images/delete.png" class='delete' border="0" height="20px" alt="delete" /></a>


Here you can view the $this->url(array('controller'=>'user','action' => 'delete'),'default',true) that means from here it is calling the deleteAction() function.
Inside the deleteAction we need to write these code for deleting from the table.

public function deleteAction()
{
$id = $this->getRequest()->getParam('user');

$mapper = new Application_Model_UserMapper();
$mapper->delete($id);
return $this->_helper->redirector('index');
}

You need to write code for this in mapper class.
Here is my code inside my mappaer class UserMapper

https://docs.google.com/document/d/1FK_axlQRlDyxSnL95B0yP0_KGVL8NLqHU4YXoYa0Yc4/edit?hl=en_US

Next in my article I will share how to develop a login page with Zend_Authentication method.


Please enter your commands if you have any problem with my codes.


Friday, 2 September 2011

Installing Zend Framework

Hi
Now I am working in a project which I supposed to do in zend framework, here I am installed this in windows platform , so this article is only for windows users who need to install zend in Windows XP platform. I faced many problem while installing and using this frame work , So I am giving a step by step instructions to install create projects in this framework.

Step 1 : From here you will get the latest framework edition :
http://framework.zend.com/releases/ZendFramework-1.11.10/ZendFramework-1.11.10.zip

by unzipping copy the files to the C:\\ directory with folder name as zend.
One important thing is, if you are using the php as xampp or wampp you can copy all the files inside the folder ZendFramework-1.11.10\library\Zend to the folder C:\xampp\php\PEAR\Zend to get the latest libraries.

Step 2 : Now using the zend tool to create zend projects and other zend components. Initially you need to set two environment variable one is for php.exe file and other is for zf.bat for using zf commands.

Refer these article if you are unaware of setting the zend framework tool.
http://www.lametadesign.com/blog/admin/how-install-zend-framework-using-wamp-20-windows-xp

Step3 :After installing and setting the directory we can proceed to some helpful commands by zend command tool. Here you can execute the instruction by simply taking the command promp from start>> run.
Initially we can create project by typing

zf create project project-name

This command will create a project folder by the name you are provided and it will generate some folders and files like this structure

project name
application/
configs/
application.ini
controllers/
helpers/
forms/
layouts/
models/
views/
filters/
helpers/
scripts/
Bootstrap.php
indexes/
library/
public/
css/
images/
js/
.htaccess
index.php

Normally our images , js and css files will lie inside the public directory.
Here you will get more useful zend commands.

http://zendframework.com/manual/en/zend.tool.usage.cli.html

One thing is if you NetBeans or Zend studio there is options for executing and generating commands and some codes inside the zend. Now I am using net beans for my project and there is options to generate getters and setters in the model classes.

Here is the link for NetBeans
http://netbeans.dzone.com/news/generate-constructor-getters-a

For newbies it is very useful to create account in

http://forums.zend.com/
and post comments if you are in struck with any complex codes.