Zend framework 1 article

Home >> Zend framework 1 >>

  Zend framework 1 CRUD operations part - 6

This article will explain you about the CRUD operations of Zend framework 1 in details include topics such as Save, Edit and Delete blog topics.

Save blog topic
For creating blog topics, We need to edit saveAction() method of BlogController found in application/controllers/BlogController.php, so it reads as follows:

    /**
     * Save/Update blog topic.
     */
    public function saveAction()
    {
        $form = new Application_Form_TopicBootstrapForm();

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

                $blogTopicId = $this->getRequest()->getParam('id');
                $blogFormData = new Application_Model_Blog($form->getValues());
                $blogMapper = new Application_Model_BlogMapper();

                if (trim($blogTopicId) >= 1) {
                    // For update the record.
                    if ($blogMapper->saveTopic($blogFormData)) {
                        $this->_helper->FlashMessenger->addMessage(array('success' => "Blog topic has been successfully updated."));
                        $this->_redirect('/');
                    } else {
                        $this->_helper->FlashMessenger->addMessage(array('danger' => "Some error occurred while updating blog topic, Please try after some time."));
                        $this->_redirect('/');
                    }
                } else {
                    // For insert new record.
                    if ($blogMapper->saveTopic($blogFormData)) {
                        $this->_helper->FlashMessenger->addMessage(array('success' => "Blog topic has been successfully posted."));
                        $this->_redirect('/');
                    } else {
                        $this->_helper->FlashMessenger->addMessage(array('danger' => "Some error occurred while posting blog topic, Please try after some time."));
                        $this->_redirect('/');
                    }
                }
            }
        }

        // For meta title.
        $this->view->title = 'Add blog topic';
        $this->view->blogTopicForm = $form;
    }

We have performed many logic inside saveAction(), which are as follows.
1. First we are validation the form request, whether it is post or not, like below code:

 if ($this->getRequest()->isPost()) {
        // valid post request
 }

2. We have to validate form fields, if validation is ok then proceed further else display validation error, like below code:

 if ($form->isValid($request->getPost())) {
        // validation is ok
 }

Note :- Form field validation rule has defined in Application_Form_TopicBootstrapForm classs

3. Here we are taking hidden field value to check which action need to be performed save/update, like below code:

$blogTopicId = $this->getRequest()->getParam('id'); 

4. Next getting all the form field values and passing it to Application_Model_Blog class for setter and getter property, like below code:

$blogFormData = new Application_Model_Blog($form->getValues());

5. Next calling the saveTopic() method of Application_Model_BlogMapper class to save or update the topics, like below code:

 $blogMapper = new Application_Model_BlogMapper();
 $blogMapper->saveTopic($blogFormData);

6.  Finally We are doing URL redirection using FlashMessenger of Zend.

Note:- To display FlashMessenger of Zend we need to edit init() method of  BlogController controller as well as layout file also.

Let's, edit init() method of BlogController found in application/controllers/BlogController.php, so it reads as follows:

    /**
     * Get flash messages and pass to the view.
     */
    public function init()
    {
        if ($this->_helper->FlashMessenger->hasMessages()) {
            $this->view->messages = $this->_helper->FlashMessenger->getMessages();
        }
    }

Let's, edit layout found in application/layouts/scripts/layout.phtml, so newly added code reads as follows:

        <div class="container-fluid">
            <div class="row">
                <div class="col-md-10 col-md-offset-1">
                    <?php
                    // Newly added code for FlashMessenger start here
                    $flashMessage = $this->messages;
                    if (is_array($flashMessage) && count($flashMessage) >= 1) {
                        foreach ($flashMessage[0] as $key => $value) {
                            echo '<div class="alert alert-' . $key . '">
                                    ' . $value . '
                                  </div>';
                        }
                    }
                    // Newly added code for FlashMessenger end here
                    ?>

                    <?php echo $this->layout()->content ?>
                </div>
            </div>
        </div>

Edit blog topic
For editing blog topics, We need to edit editAction() method of BlogController found in application/controllers/BlogController.php, so it reads as follows:

    /**
     * Edit blog topic.
     */
    public function editAction()
    {
        $request = $this->getRequest();
        $form = new Application_Form_TopicBootstrapForm();

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

            $blogTopicId = $this->getRequest()->getParam('id');
            $blogFormData = new Application_Model_Blog($form->getValues());
            $blogMapper = new Application_Model_BlogMapper();

            $editTopic = $blogMapper->findTopic($blogTopicId, $blogFormData);
            $this->view->blogTopicEditForm = $form->populate($editTopic->toArray());
        }

        // For meta title.
        $this->view->title = 'Edit blog topic';
    }

We have performed many logic inside editAction(), which are as follows.
1. First we are validation the form request, whether it is get or not, like below code:

 if ($this->getRequest()->isGet()) {
  // valid get request
 }

2. Here we are taking hidden field value to performed update, like below code:

  $blogTopicId = $this->getRequest()->getParam('id');

3. Next getting all the form field values and passing it to Application_Model_Blog class for setter and getter property, like below code:

$blogFormData = new Application_Model_Blog($form->getValues());

4. Next calling the findTopic() method of Application_Model_BlogMapper class to get the topic  details, like below code:

 $blogMapper = new Application_Model_BlogMapper();
 $editTopic = $blogMapper->findTopic($blogTopicId, $blogFormData);

5. Finally calling the populate() function of Zend_Form class and binding with the form to display the particular topic data in the editable mode form, like below code:

$this->view->blogTopicEditForm = $form->populate($editTopic->toArray());

Next edit view file found in application/views/scripts/blog/edit.phtml to render this form, so it reads as follows:

// Add form action URL
$this->blogTopicEditForm->setAction($this->baseURL('blog/create'));

// Add the edit button
$this->blogTopicEditForm->addElement(
    'submit', 'Update Topic', array(
    'required' => false,
    'ignore' => true,
    'label' => 'Update Topic',
    'class' => 'btn btn-small btn-success'
        )
);

echo $this->blogTopicEditForm;

Delete blog topic
For editing blog topics, We need to edit deleteAction() method of BlogController found in application/controllers/BlogController.php, so it reads as follows:

    /**
     * Delete blog topic.
     */
    public function deleteAction()
    {
        $request = $this->getRequest();

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

            $blogTopicId = $this->getRequest()->getParam('id');
            $modelObj = new Application_Model_BlogMapper();
            if ($modelObj->deleteTopic($blogTopicId)) {
                $this->_helper->FlashMessenger->addMessage(array('success' => "Blog topic has been successfully deleted."));
                $this->_redirect('/');
            } else {
                $this->_helper->FlashMessenger->addMessage(array('danger' => "Some error occurred while deleting blog topic, Please try after some time."));
                $this->_redirect('/');
            }
        }

        // For meta title.
        $this->view->title = 'Delete blog topic';
    }

Congratulation Zend Framework 1 CRUD Operation is completed, you can download the source code. If you face any problem please comment below in the comment box, we will reach out to you.

Once you have downloaded the source code then you need to change the database credentials according to database server in application.ini file found in application/configs/application.ini and then browse to http://localhost/zf1app/public/. You should see the following in your browser:

  Download code

Write your comment now