Add, Edit & Delete Operations in Zend Framework

Hello Everyone! This blog will help you to get start with Zend Framework with performing basic operations (add, edit and delete) in Zend Framework. When I started to learn Zend Framework I didn’t find any application which easily help me to get start with Zend. So I decided to write this blog to get start with Zend.Hope with this blog you can easily perform basic operations of any application in Zend Framework.

Before starting this blog assumes that you have already downloaded ZF if not then download it from the link below. If you are new in Zend then I advise you to start with version 1 (minimal package) of Zend instead of version 2.

http://framework.zend.com/downloads/latest#ZF1

Once you download. First extract it and then rename it to Zend now copy this folder (Zend) to your C:\xampp\php directory another thing to do is setting the path of Zend in our php.ini file (c:\xampp\php\php.ini). Open php.ini file and set

include_path = “.;C:\xampp\php\PEAR;”
TO
include_path=“.;C:\xampp\php\PEAR;C:\xampp\php\Zend\library\;C:\xampp\php\PEAR\PHPUnit” .

One more thing we can do to not get error(php.ini not found) which occur in some cases we can append ;c:\xampp\php\ in path of system variables.

For making easy to understand Zend I start it integrating with Net Beans IDE. I suggest you do the same. So now if you already have Net Beans IDE then open it otherwise download it from here http://netbeans.org/downloads/

After Starting Net Beans first we have to integrate Zend .bat file to Net Beans for this go to Tools-> Options. A window will appear  now click on PHP tab then on Zend tab.Now we have to browse for zf.bat file which we will find here C:\xampp\php\Zend\bin\zf.bat now click OK. That’s it we have integrated our Net Beans with Zend. Now we have to create new project. For this go to File->New Project,  a Window will appear select PHP Application click Next give the name to php project BookManagement click Next select PHP Version 5.2.4(or higher as it is must to Zend) click next then again click next now you have to check on Zend PHP Web Framework to call all functions of Zend for our project. That’s it we have created a BookManagement Project.

 So now when we run our project on localhost we will have the following  URL http://localhost/BookManagement/public/

we will get like this

When we have created the project, we have our directory structure like this

BookManagement
|- – –  application
|          |- – – Bootstrap.php
|          |- – – configs
|                    | `- – – application.ini
|          |- – – controllers
|                    | `- – – ErrorController.php
|                    | `- – – IndexController.php
|          |- – – models
|          |- – – views
|                    |- – – helpers
|                    |- – – scripts
|                              |- – – error
|                                        | `- – – error.phtml
|                              |- – – index
|                                       | `- – –  index.phtml
|- – –  library
|- – –  public
|         |`- – – .htaccess
|         |`- – – index.php
|- – –  tests
|         |` – – – application
|         |`- – – bootstrap.php
|         |`- – – library
|         |`- – – phpunit.xml
|- – – .zfproject.xml

Now what we are going to do. We create a website in which main page show the List Of Books with some details and there are some actions to perform like add new book, edit book & delete book.

Step 1 . First we have to create a database named zf

CREATE DATABASE `zf`;


and a table named books

CREATE TABLE `zf`.`books` (
`id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
`book_name` VARCHAR(150) NOT NULL,
`author` VARCHAR(150) NOT NULL,
`price` FLOAT NOT NULL,
`edition` VARCHAR(45) NOT NULL,
PRIMARY KEY (`id`)
)
ENGINE = InnoDB;



** Add some dummy values

INSERT INTO `books` (`id`, `book_name`, `author`, `price`, `edition`) VALUES
(1, ‘PHP’, ‘Rasmus’, 300, ‘3’),
(2, ‘Zend Framework’, ‘Mannu’, 550, ‘2’),
(3, ‘JavaScript’, ‘Babu’, 350, ‘3’);


Step 2 . We can do all these things with IndexController but it is a good way if we create separate controller for each new scenario.

So Now create a controller.For this right click on project select zend -> RunCommand . A window will appear now in the matching tasks select create controller and write Books in parameter field and Press Run to execute the command. Or use the folllowing command in cmd.

zf create controller Books

 

Note : you can create shortcut command for performing command of Zend. In net beans IDE go to Tools -> Options -> keymap . Now search for Zend you will see Zend: Run Command then press Alt in shortcut then you will see Alt+A , Alt+B, ….. Alt+Z . Select Alt+Z and click OK. Now when you press Alt+Z you get Zend Run Command Window.

If everything is going fine then now we have BooksController.php in controllers directory. Whenever Controller is created a directory under  application\views\scripts is automatically gets created with the name of controller and under that new directory one new file index.phtml is also gets created automatically i.e now we have one more directory books .so now we have BookManagement\application\views\books\index.phtml


Step 3 .
An efficient way of creating website in Zend is to enable layout.So for this press Alt+z  to open Zend Run Command window.In matching tasks select enable layout and press Run to execute command. Or use following command in cmd.

zf enable layout



After running this command we will get one new line of code in Production part of application.ini file under configs directory resources.layout.layoutPath = APPLICATION_PATH “/layouts/scripts/”

A new directory will get created BookManagement\layout\scripts\layout.phtml

Step 4 . Edit index.phtml file under BookManagement\application\views\scripts\index directory. Put the following line of code at the top of file.

<a href=”<?=$this->url(array(‘controller’=>’books’,’action’=>’index’))?>”>BookManagement</a>



** This will show a link on index file  which will redirect to BooksController index action. in above url controller is “book” which means BooksController and action is index. So when we click on the above url it will take us to localhost/BookManagement/public/books or localhost/BookManagement/public/books/index/

 where :-

  1. “localhost” is server name
  2. “BookManagement” is project name(directory)
  3. “public” is initial directory
  4. “books” is our controller name(i.e BooksController)
  5. “index” is the default action name


Step 5 . In next step we will write some code for connecting our application with database. Write these following lines of code in application.ini  file

resources.db.adapter = “PDO_MYSQL”
resources.db.params.dbname = “zf”
resources.db.params.host = “localhost”
resources.db.params.username = “your mysql user name”
resources.db.params.password = “your mysql password”

Step 6 . In step 6 we will create a model for our database table where we actually write our code for performing operations with database.Open Zend run command window and find the create db-table in matching tasks and write books books in parameters Or use the following command in cmd.

zf create db-table books books


** first books means name of the model i.e Books.php and second books is our table name.A new directory is gets created "BookManagement\application\models\DbTable\" and under this directory the name of new php file is Books.php . This is our model where we will write all of our code that relates with database.

Step 7.Now we will start our Coding part.First we will show a list of books containing full information.We will do this at the indexAction of BooksController.php under “BookManagement\application\controllers\” directory and update it as follows.

<?php

class BooksController extends Zend_Controller_Action
{

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

public function indexAction()
{
$books = new Application_Model_DbTable_Books();          // Line 1
$this->view->books = $books->fetchAll();                               // Line 2
}

}

  1. Line 1 –  Creates object of DbTable Books.
  2. Line 2 – fetchAll() method returns the all records present in books table.This result is stored in books variable for view file.

Step 8 . When ever any action is called it’s corresponding phtml file executed in indexAction() case index.phtml file is loaded which is “under BookManagement\application\views\scripts\books”\ directory. This is a html file of php which is used to display html. So update this file as follows.

<a href=”<?=$this->url(array(‘controller’=>’books’,’action’=>’add’))?>”>Add Book</a> <!– line 1 –>
<br /><br />

  1. line 1 – It is a URL for adding new Book in our database. Here controller is “books” and action is “add” which will we create shortly don’t worry about that.
  2. line 2 – Creates a table for books.
  3. line 3 – This is a foreach loop which will loop up to the number of rows in “books” table.We take each record one by one in $row variable.
  4. line 4 – This is a URL for editing the book entry. Here controller is “books” and action is “edit” and one new thing is “id”(this is a unique id of each record) which will we create shortly.
  5. line 5 – This is a URL for deleting the book entry. Here controller is “books” and action is “delete” which will we create shortly.

** Now it’s time to run our project by following url.

localhost/BookManagement/public/books

Following output will come after running.

Step 9 . Ok Our first task is completed to show a list of books. Now we will write some codes for adding a new book in our database. For creating a new entry we need a form (a view) that has all fields as Book Name , author etc. Because of this form Zend MVC is also called Zend MVCF(Model View Controller Form). So open Zend run command window and search for create form in matching tasks and then give name book in parameter field OR use the following command in cmd

zf create form book


A new directory gets created after running the above command under “BookManagement\application\forms\”  and file name is Book.php. This is our form we will use Zend library functions to write HTML components . Edit this Book.php as

<?php
class Application_Form_Book extends Zend_Form
{
public function init()
{
$this->setName(‘BookForm’);
$id = new Zend_Form_Element_Hidden(‘id’);
$id->addFilter(‘Int’);
$book_name = new Zend_Form_Element_Text(‘book_name’);
$book_name->setLabel(‘Book Name’)
->setRequired(true)
->addFilter(‘StripTags’)
->addFilter(‘StringTrim’)
->addValidator(‘NotEmpty’);
$author = new Zend_Form_Element_Text(‘author’);
$author->setLabel(‘Author’)
->setRequired(true)
->addFilter(‘StripTags’)
->addFilter(‘StringTrim’)
->addValidator(‘NotEmpty’);
$price = new Zend_Form_Element_Float(‘price’);
$price->setLabel(‘Price’)
->setRequired(true)
->addFilter(‘StripTags’)
->addFilter(‘StringTrim’)
->addValidator(‘NotEmpty’);
$edition = new Zend_Form_Element_Text(‘edition’);
$edition->setLabel(‘Edition’)
->setRequired(true)
->addFilter(‘StripTags’)
->addFilter(‘StringTrim’)
->addValidator(‘NotEmpty’);
$submit = new Zend_Form_Element_Submit(‘submit’);
$submit->setAttrib(‘id’, ‘submitbutton’);
$this->addElements(array($id, $book_name, $author, $price, $edition));
}
}

* As the name is explaining everything. We have created text box for Book Name ,Price,  Author and Edition where Price type is of float and rest are of Strings.

Step 10 . Now we will create add action for adding new book. Open Run command window and search for create action and write add books in parameter field where add is the action name and books is the controller name. So a new method (i.e action) addAction is created in BooksController.php under “BookManagement\application\controllers\”  directory.Edit BooksController.php as

<?php

class BooksController extends Zend_Controller_Action
{

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

public function indexAction()
{
$books = new Application_Model_DbTable_Books();
$this->view->books = $books->fetchAll();
}

public function addAction()
{
$form = new Application_Form_Book(); // Line 1
$form->submit->setLabel(‘Add’); // Line 2
if ($this->getRequest()->isPost()) { //Line 3
$formData = $this->getRequest()->getPost(); //Line 4
if ($form->isValid($formData)) { // Line 5
$book_name = $form->getValue(‘book_name’); //Line 6
$author = $form->getValue(‘author’); //Line 7
$price = $form->getValue(‘price’); //Line 8
$edition = $form->getValue(‘edition’); //Line 9
$add_book = new Application_Model_DbTable_Books(); //Line 10
$add_book->addBook($book_name,$author,$price,$edition); //Line 11
$this->_helper->redirector(‘index’); //Line 12
} else {
$form->populate($formData); //Line 13
}
}$this->view->form = $form; //Line 14
}
}

  1. Line 1. Create object of form Book.
  2. Line 2. set label(“value”) Add of submit button.
  3. Line 3. if statement code inside if statement(Line 4 to Line 13 ) will execute when form is submitted.
  4. We will discuss from Line 4 to Line 13 shortly because our first task is to see the form to add new book then we will submit it.
  5. Line 14. As we know whenever any action is called its corresponding view file is loaded automatically. Hence we assign $form (object) to form variable to view file (i.e $this->view->form).

Step 11 .Now open add.phtml under “BookManagement\application\views\books\” directory and update it as follows.

<a href=”<?=$this->url(array(‘controller’=>’books’,’action’=>’index’))?>”>BookManagement</a> <!– line 1 –>
<br /><br />

form?>
  1. Line 1. link to get back to index where list of all books is shown.

Now we will discuss the remaining point which we left before.

  1. Line 4. Get all the data posted via the form in $formdata variable.
  2. Line 5. If condition statement checking for whether all the fields are valid when submitting the form or not. If not then form will redirect to itself again with form data (Line 13).
  3. Line 6,Line 7, Line 8, Line 9. Get the value in $book_name, $author, $price, $edition variable of book_name , author, price and edition fields respectively.
  4. Line 10. Create object of Books model (“BookManagement\application\models\DbTable\Books.php”) assign it to $add_book variable.
  5. Line 11. Call addBook function of Books.php (“BookManagement\application\models\DbTable\Books.php”) to add new Book.
  6. Line 12. After successfully adding new book it will redirect to index page where list of books is shown.

Step 12.Now time to write code for adding book to database. Open Books.php under “BookManagement\application\models\DbTable\Books.php” directory and update this as follows.

<?php

class Application_Model_DbTable_Books extends Zend_Db_Table_Abstract
{

protected $_name = ‘books’;

public function addBook($book_name,$author,$price,$edition){                          //Line 1
$data = array(‘book_name’=>$book_name,’author’=>$author,’price’=>$price,’edition’=>$edition);   //Line 2
$this->insert($data);
}

}

  1.  Line 1. Create array $data to store all the fields value in single array variable.
  2. Line 2. Using in built function insert to inset all the values in database.

** Now it’s time to run our project by (clicking on Add Book link seen on the index page) or via the  following url.

localhost/BookManagement/public/books
/add

Add New Book

Step 13.After successfully performing add operation time to write code for edit operation. For edit we will use the same form. So open Zend run command window and search for create action in matching tasks and write edit books in parameter field. Where edit
is the name of action and books is our controller and then Press Run to execute command. Or use the following command via cmd

zf create action edit books



** This command will create another method (i.e editAction) in BooksController.php under “BookManagement\application\controllers\” directory. Open this file and update it as follows.

<?php
class BooksController extends Zend_Controller_Action
{
public function init()
{
/* Initialize action controller here */
}
public function indexAction()
{
$books = new Application_Model_DbTable_Books();
$this->view->books = $books->fetchAll();
}
public function addAction()
{
$form = new Application_Form_Book();
$form->submit->setLabel(‘Add’);
if ($this->getRequest()->isPost()) {
$formData = $this->getRequest()->getPost();
if ($form->isValid($formData)) {
$book_name = $form->getValue(‘book_name’);
$author = $form->getValue(‘author’);
$price = $form->getValue(‘price’);
$edition = $form->getValue(‘edition’);
$add_book = new Application_Model_DbTable_Books();
$add_book->addBook($book_name,$author,$book_price,$edition);
$this->_helper->redirector(‘index’);
} else {
$form->populate($formData);
}
}
$this->view->form = $form;
}
public function editAction()
{
$data = $this->getRequest()->getParams();                                                      // Line 1
$id = $data[‘id’];                                                                                                             //Line 2
$form = new Application_Form_Book();
$form->submit->setLabel(‘Update’);                                                                    //Line 3
if($this->getRequest()->isPost()){
$formData = $this->getRequest()->getPost();
if($form->isValid($formData)){
$id = $form->getValue(‘id’);                                                                                   //Line 4
//echo $id;
$book_name = $form->getValue(‘book_name’);
$author = $form->getValue(‘author’);$book_price = $form->getValue(‘book_price’);
$edition = $form->getValue(‘edition’);
$edit_book = new Application_Model_DbTable_Books();
$edit_book->editBook($id, $book_name, $book_price, $author, $edition);                  //Line 5
$this->_helper->redirector(‘index’);
}
else{
$form->populate($formData);
}
}
else{                                                                                                                                                                      //Line 6
$edit_book = new Application_Model_DbTable_Books();
$values = $edit_book->getBook($id);                                                                                               //Line 7
$form->id->setValue($values[‘id’]);                                                                                                   //Line 8
$form->book_name->setValue($values[‘book_name’]);
$form->book_price->setValue($values[‘book_price’]);
$form->author->setValue($values[‘author’]);
$form->edition->setValue($values[‘edition’]);
}
$this->view->form = $form;                         //Line 9
}
}

** Many lines of code are just same as we did at the time of addition of Book so We will discuss only new lines of code here.

** Let us see again the edit url

<a href=”<?=$this->url(array(‘controller’=>’books’,’action’=>’edit’,’id’=>$books->id))?>”>Edit</a>



** Here Controller is books , action is edit and most important is that we are passing id as a parameter having the ‘id’ of book entry that uniquely distinguish one book from another book.

  1. Line 1. Store all the variables passed as parameter in $data array (e.g id).
  2. Line 2. Get the id value in $id variable.
  3. Line 3. Setting the value (Label) Update of submit button.
  4. Line 6. First we should consider Line no 6 because initially our form fields must be filled with all the values of book when we want to edit any particular book. So initially Line 6 gets executed first because till now our form is not submitted.
  5. Line 7. Calling a getBook method which returns values of that book entry and we store it in $values array.
  6. Line 8. Setting the values to form fields.
  7. Line 9. we assign $form (object) to form variable to view file (i.e $this->view->form).

Step 14.   Code for getting details of book from database and method for editing book detail (i.e editBook on line 5 ) under “BookManagement\application\models\DbTable\” directory (i.e in Books.php) update it as follows.

<?php

class Application_Model_DbTable_Books extends Zend_Db_Table_Abstract
{

protected $_name = ‘books’;

public function addBook($book_name,$author,$price,$edition){
$data = array(‘book_name’=>$book_name,’author’=>$author,’price’=>$price,’edition’=>$edition);
$this->insert($data);
}

public function getBook($id)
{
$id = (int)$id;                                                                 //Line 1
$row = $this->fetchRow(‘id = ‘ . $id);                 //Line 2
if (!$row) {
throw new Exception(“Could not find row $id”);  //Line 3
}
return $row->toArray();                                              //Line 4
}

public function editBook($id, $book_name, $author, $price, $edition)
{
$data = array(‘book_name’=>$book_name,’author’=>$author,’price’=>$price,’edition’=>$edition); //Line 5
$this->update($data, ‘id = ‘. (int)$id);                                                                                                                                  //Line 6
}
}

  1. Line 1. Stroing value of parameter id in $id variable.
  2. Line 2. Using fetchRow method to get values where id = $id.
  3. Line 3. If values not find then throw exception.
  4. Line 4. Returning array of values.
  5. Line 5. Storing all values in a single array.
  6. Line 6. Calling update in built function to update data where id=$id.

Step 15. Now open edit.phtml under “BookManagement\application\views\books\” directory and update it as follows.

<br /><br />

form; ?>


Now let us see Line no 6

** Now it’s time to run our project by (clicking on Edit link seen on the index page) or via the  following url.

localhost/BookManagement/public/books
/edit/id/3

Edit Book

Step 16. Last operation is remaining to perform i.e Delete operation. This operation is very easy to perform.Ok so lets start it.Again the same thing open Zend run command window search for create action in matching tasks and write delete books in parameter field where delete is action name and books is controller. Press run to execute command OR use the following command via cmd.

zf create action delete books



** Now update BooksController.php under “BookManagement\application\controllers\” directory as follows.

<?php
class BooksController extends Zend_Controller_Action
{
public function init()
{
/* Initialize action controller here */
}
public function indexAction()
{
$books = new Application_Model_DbTable_Books();
$this->view->books = $books->fetchAll();
}
public function addAction()
{
$form = new Application_Form_Book();
$form->submit->setLabel(‘Add’);
if ($this->getRequest()->isPost()) {
$formData = $this->getRequest()->getPost();
if ($form->isValid($formData)) {
$book_name = $form->getValue(‘book_name’);
$author = $form->getValue(‘author’);
$price = $form->getValue(‘price’);
$edition = $form->getValue(‘edition’);
$add_book = new Application_Model_DbTable_Books();
$add_book->addBook($book_name,$author,$book_price,$edition);
$this->_helper->redirector(‘index’);
} else {
$form->populate($formData);
}
}
$this->view->form = $form;
}
public function editAction()
{
$data = $this->getRequest()->getParams();
$id = $data[‘id’];
$form = new Application_Form_Book();
$form->submit->setLabel(‘Update’);
if($this->getRequest()->isPost()){
$formData = $this->getRequest()->getPost();
if($form->isValid($formData)){
$id = $form->getValue(‘id’);
//echo $id;
$book_name = $form->getValue(‘book_name’);
$author = $form->getValue(‘author’);$book_price = $form->getValue(‘book_price’);
$edition = $form->getValue(‘edition’);
$edit_book = new Application_Model_DbTable_Books();
$edit_book->editBook($id, $book_name, $book_price, $author, $edition);
$this->_helper->redirector(‘index’);
}
else{
$form->populate($formData);
}
}
else{
$edit_book = new Application_Model_DbTable_Books();
$values = $edit_book->getBook($id);
$form->id->setValue($values[‘id’]);
$form->book_name->setValue($values[‘book_name’]);
$form->book_price->setValue($values[‘book_price’]);
$form->author->setValue($values[‘author’]);
$form->edition->setValue($values[‘edition’]);
}
$this->view->form = $form;
}

public function deleteAction()
{

$id = $this->_getParam(‘id’, 0);                                                                   //Line 1
$books = new Application_Model_DbTable_Books();                      //Line 2
$books->deleteBook($id);                                                                           //Line 3

$this->_helper->redirector(‘index’);                                                      //Line 4

}

}

  1.  Line 1. Getting the value of parameter id and storing it in $id.
  2. Line 2. Creating Object of model Books.
  3. Line 3. calling function deleteBook of model.
  4. Line 4. redirecting it to index (i.e List of Books).

Step 17. Updating Books.php under “BookManagement\application\models\DbTable\” directory as follows.

<?php

class Application_Model_DbTable_Books extends Zend_Db_Table_Abstract
{

protected $_name = ‘books’;

public function addBook($book_name,$author,$price,$edition){
$data = array(‘book_name’=>$book_name,’author’=>$author,’price’=>$price,’edition’=>$edition);
$this->insert($data);
}

public function getBook($id)
{
$id = (int)$id;
$row = $this->fetchRow(‘id = ‘ . $id);
if (!$row) {
throw new Exception(“Could not find row $id”);
}
return $row->toArray();
}

public function editBook($id, $book_name, $author, $price, $edition)
{
$data = array(‘book_name’=>$book_name,’author’=>$author,’price’=>$price,’edition’=>$edition);
$this->update($data, ‘id = ‘. (int)$id);
}

public function deleteBook($id)
{
$this->delete(‘id =’ . (int)$id);                                   //Line 1
}
}

  1.  Line 1. Very easy to understand. Simply deleting the record of book where id=$id.

* That is it ! We have performed all the operation Add , Edit, Delete.Hope You find it easy to perform.

Become a member to increase sales and leads of your business. Click below to Join Now

Advertisements

26 thoughts on “Add, Edit & Delete Operations in Zend Framework

  1. One cake can be made by spreading on strawberry preserves.

    Restaurants are often hard to recommend because my idea of a $40
    and yours might be different. We came back to Columbus, OH from our
    Smokey Mountains vacation with beautiful memories & a Pancake bug.

  2. thanks alot this is very helpfl, im tryin to use the edit operation on my code ( as edit user) but i got an error with the foreach loop in the phtml .. somethin is wrong with the part foreach($this->books as $row): it prints “books as $row): ?>” and says undefined variable row ! any help will be nice !!

  3. hi administrator, your articles are so nice, can you send to me the sorcecodes i want to test the zend frameworks and create by own but i want to use your code as my reference. Thanks…

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