আগামী ৩০ নভেম্বর-২০১৭ তারিখ থেকে শুরু হচ্ছে পাঁচ মাস ব্যাপী Professional Web Design and Development with HTML, CSS PHP,MySQL,JavaScript, AJAX, JQUERY, Bootstrap and Live Project কোর্সের ৮৭ তম ব্যাচ এবং ৫ ডিসেম্বর-২০১৭ তারিখ থেকে শুরু হচ্ছে চার মাস ব্যাপী Zend PHP-7 Certified PHP Engineering (Advance PHP) কোর্সের ৩৫ তম ব্যাচ। প্রত্যেকটি কোর্স এর ফী নির্ধারণ করা হয়েছে ৩০,০০০/= আগ্রহীদেরকে অতিসত্বর মাসুদ আলম স্যার এর সাথে যোগাযোগ করতে অনুরোধ করা যাচ্ছে। স্যার এর মোবাইল: 01722 81 75 91

CRUD with Zend Framework 2 Part-3: Update and Delete

Hello everyone Welcome back and thanks for staying with this series. I assume that you have already completed Our  Part-1 and Part-2.. now In this 3rd part we show you how to update and delete a existing user to database table using Zend Framework 2 . Lets Start….

Editing an Existing User

Editing an existing user is almost identical to adding one, so the code is very similar. This time we use editAction() in the UsersController. Add editAction Method Code in your UsersController.php file inside the directory ” / zf2/module/Users/view/users/users “:


//----

//----

public function editAction() {
        $id = (int) $this->params()->fromRoute('id', 0);
        if (!$id) {
            return $this->redirect()->toRoute('users', array(
                        'action' => 'add'
            ));
        }

        // Get the Users with the specified id.  An exception is thrown
        // if it cannot be found, in which case go to the index page.
        try {
            $users = $this->getUsersTable()->getUser($id);
        } catch (\Exception $ex) {
            return $this->redirect()->toRoute('users', array(
                        'action' => 'index'
            ));
        }

        $form = new UsersForm();
        $form->bind($users);
        $form->get('submit')->setAttribute('value', 'Update');

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

            if ($form->isValid()) {
                $this->getUsersTable()->saveUser($users);

                // Redirect to list of users
                return $this->redirect()->toRoute('users');
            }
        }

        return array(
            'id' => $id,
            'form' => $form,
        );
    }

//----

//----

Above Code  Firstly, we look for the id that is in the matched route and use it to load the users to be edited:


$id = (int) $this->params()->fromRoute('id', 0);
        if (!$id) {
            return $this->redirect()->toRoute('users', array(
                        'action' => 'add'
            ));
        }
// Get the user with the specified id.  An exception is thrown

// if it cannot be found, in which case go to the index page.

try {

$users = $this->getUsersTable()->getUser($id);

}

catch (\Exception $ex) {

return $this->redirect()->toRoute('users', array(

'action' => 'index'

));

}

Params is a controller plugin that provides a convenient way to retrieve parameters from the matched route. We use it to retrieve the id from the route we created in the modules’ module.config.php. If the id is zero, then we redirect to the add action, otherwise, we continue by getting the users entity from the database.

 We have to check to make sure that the Users with the specified id can actually be found. If it cannot, then the data access method throws an exception. We catch that exception and re-route the user to the index page.


$form = new UsersForm();

$form->bind($users);

$form->get('submit')->setAttribute('value', 'Edit');

 The form’s bind() method attaches the model to the form. This is used in two ways:

  1. When displaying the form, the initial values for each element are extracted from the model.
  2. After successful validation in isValid(), the data from the form is put back into the model.

These operations are done using a hydrator object. There are a number of hydrators, but the default one isZend\Stdlib\Hydrator\ArraySerializable which expects to find two methods in the model: getArrayCopy() and exchangeArray().

Back to the Model

 We have already written exchangeArray() in our Users entity, so just need to write getArrayCopy()Now we add getArrayCopy() method to our  Users.php file within module/Users/src/Users/Model directory like this:


//----

//----

 public function getArrayCopy() {
        return get_object_vars($this);
    }

//----

//----

As a result of using bind() with its hydrator, we do not need to populate the form’s data back into the $users as that’s already been done, so we can just call the mappers’ saveUsers () to store the changes back to the database.

The view template, edit.phtml, looks very similar to the one for adding an users:


<style>
    .left-inner-addon {
        position: relative;
    }
    .left-inner-addon input {
        padding-left: 30px;    
    }
    .left-inner-addon i {
        position: absolute;
        padding: 10px 12px;
        pointer-events: none;
    }
</style>
<?php
// module/Users/view/users/users/add.phtml:
$title = 'Add New User';
$this->headTitle($title);
?>
<h1 style="text-align: center"><?php echo $this->escapeHtml($title); ?></h1>
<?php
$form = $this->form;
$form->prepare();
$form->setAttribute('action', $this->url(NULL, array('controller' => 'Users', 'action' => 'add')));
$form->setAttribute('method', 'post');
echo $this->form()->openTag($form);
echo $this->formHidden($form->get('id'));
?>
<table class="table table-bordered table-striped" style="width:80%;">
    <tr>
        <td width="40%"><?php echo $this->formLabel($form->get('name')); ?></td>
        <td width="60%"><div class="left-inner-addon ">
                <i class="glyphicon glyphicon-user"></i><?php echo $this->formElement($form->get('name')); ?></div></td>
    </tr>
    <tr>
        <td><?php echo $this->formLabel($form->get('email')); ?></td>
        <td><div class="left-inner-addon ">
                <i class="glyphicon glyphicon-envelope"></i><?php echo $this->formElement($form->get('email')); ?></div></td>
    </tr>
    <tr>
        <td><?php echo $this->formLabel($form->get('mobile')); ?></td>
        <td><div class="left-inner-addon ">
                <i class="glyphicon glyphicon-phone"></i><?php echo $this->formElement($form->get('mobile')); ?></div></td>
    </tr>
    <tr>
        <td><?php echo $this->formLabel($form->get('address')); ?></td>
        <td><?php echo $this->formElement($form->get('address')); ?></td>
    </tr>
    <tr>

        <td colspan="2"><?php echo $this->formElement($form->get('submit')); ?></div></td>
    </tr>

</table>
<?php echo $this->form()->closeTag();
?>

Finally Our Edit User System Successfully done. The only changes are to use the ‘Edit User’ title and set the form’s action to the ‘edit’ action too. See Below screenshot

Zend Framework 2 Edit Form

Deleting a User:

 Finally we need to create deletion system. We have a Delete link next to each user on our list page and the simple approach would be to do a delete when it’s clicked. This would be wrong. Remembering our HTTP spec, we recall that you shouldn’t do an irreversible action using GET and should use POST instead.

We will show a confirmation form when the user clicks delete and if they then click “yes”, we will do the deletion. As the form is trivial, we’ll code it directly into our view (Zend\Form is, after all, optional!).

Add deleteAction() method to your UsersController.php for delete action:


//-----

//-----

  public function deleteAction() {
        $id = (int) $this->params()->fromRoute('id', 0);
        if (!$id) {
            return $this->redirect()->toRoute('users');
        }

        $request = $this->getRequest();
        if ($request->isPost()) {
            $del = $request->getPost('del', 'No');

            if ($del == 'Yes') {
                $id = (int) $request->getPost('id');
                $this->getUsersTable()->deleteUser($id);
            }

            // Redirect to list of users
            return $this->redirect()->toRoute('users');
        }

        return array(
            'id' => $id,
            'users' => $this->getUsersTable()->getUser($id)
        );
    }

//----

//----

Above deleteAction() Function, we get the id from the matched route, and check the request object’s isPost() to determine whether to show the confirmation page or to delete the users. We use the table object to delete the row using the deleteUsers() method and then redirect back the list of users. If the request is not a POST, then we retrieve the correct database record and assign to the view, along with the id.

Now we need to add deleteUser() method to our UsersTable.php Model File within module/Users/src/Users/Model


//----

//----

 public function deleteUser($id) {
        $this->tableGateway->delete(array('id' => (int) $id));
    }
//-----

//-----

Now we need to add view script to our delete.php file within module/Users/view/users/users for confirmation message:


<?php
// module/Users/view/users/users/delete.phtml:

$title = 'Delete User';
$this->headTitle($title);
?>
<h1><?php echo $this->escapeHtml($title); ?></h1>

<p>Are you sure that you want to delete
    '<?php echo $this->escapeHtml($users->name); ?>'?
</p>
<?php
$url = $this->url('users', array(
    'action' => 'delete',
    'id' => $this->id,
        ));
?>
<form action="<?php echo $url; ?>" method="post">
    <div>
        <input type="hidden" name="id" value="<?php echo (int) $users->id; ?>" />
        <input type="submit" class="btn btn-success" name="del" value="Yes" />
        <input type="submit" name="del" class="btn btn-danger" value="No" />
    </div>
</form>

Above script, we display a confirmation message to the user and then a form with “Yes” and “No” buttons. In the action, we checked specifically for the “Yes” value when doing the deletion.

After completing all tasks successfully, the layout looks like image bellow.

Zend Framework 2 Delete Action

GoodGood VeryGood 🙂

CRUD with Zend Framework 2 Part-3

Hi, My name is Masud Alam, love to work with Open Source Technologies, living in Dhaka, Bangladesh. I graduated in 2009 with a bachelor’s degree in Engineering from State University Of Bangladesh, I’m also a Certified Engineer on ZEND PHP 5.3, I served my first five years a number of leadership positions at Winux Soft Ltd, SSL Wireless Ltd, CIDA and MAX Group where I worked on ERP software and web development., but now i’m a co-founder and Chief Executive Officer and Managing Director of TechBeeo Software Consultancy Services Ltd. I’m also a Course Instructor of ZCPE PHP 7 Certification and professional web development course at w3programmers Training Institute – a leading Training Institute in the country.

One comment on “CRUD with Zend Framework 2 Part-3: Update and Delete

Leave a Reply

Your email address will not be published. Required fields are marked *