আগামী ১৫ ডিসেম্বর -২০১৭ তারিখ থেকে শুরু হচ্ছে পাঁচ মাস ব্যাপী 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-2 : Insert a User to Database

Hello everyone Welcome back!  I assume that you have already completed Our  Part-1.. now In this 2nd part we show you how insert a new user to database table using Zend Framework 2 . Lets Start….

We can now update our existing functionality and add new functions to add new users. There are two parts:

  • Display add form for user to add details
  • Process the add form for submission and store to database

We use Zend\Form Component to do this. The Zend\Form component manages the form and, form validation,. We start by creating a new class Users\Form\Users Form that extends from Zend\Form\Form to define our form. Create a file called UsersForm.php inmodule/Users/src/Users/Form:

<?php

// module/Users/src/Users/Form/UsersForm.php:

namespace Users\Form;

use Zend\Form\Form;

class UsersForm extends Form {

    public function __construct($name = null) {

        parent::__construct('users');

        $this->setAttribute('method', 'post');


        $this->add(array(
            'name' => 'id',
            'type' => 'Hidden',
        ));

        $this->add(array(
            'name' => 'name',
            'type' => 'Text',
            'options' => array(
                'label' => 'Name',
            ),
        ));

        $this->add(array(
            'name' => 'email',
            'type' => 'Email',
            'options' => array(
                'label' => 'Email Address',
            ),
        ));

        $this->add(array(
            'name' => 'mobile',
            'type' => 'Text',
            'options' => array(
                'label' => 'Mobile',
            ),
        ));

        $this->add(array(
            'name' => 'address',
            'type' => 'Textarea ',
            'options' => array(
                'label' => 'Address',
            ),
        ));

        $this->add(array(
            'name' => 'submit',
            'type' => 'Submit',
            'attributes' => array(
                'value' => 'Save',
                'id' => 'submitbutton',
            ),
        ));
    }

}

Within the constructor of UsersForm we do several things. First, we set the name of the form as we call the parent’s constructor. We then set the form’s method, in this case, post.

Finally, we create four form elements: the id, name,email,mobile,address and submit button. For each item we set various attributes and options, including the label to be displayed.

Back To Controller

Now we need to get the form to display and then process it on submission. This is done by addAction() method within theUsersController.php. add addAction() method in your UsersController.php file inside the directory ” / zf2/module/Users/view/users/users ” :

//-----
//-----
    public function addAction() {

        $form = new UsersForm();

        $request = $this->getRequest();

        if ($request->isPost()) {

            $users = new Users();

            $form->get('submit')->setAttribute('value', 'Add New User');

            $form->setData($request->getPost());

            if ($form->isValid()) {

                $users->exchangeArray($form->getData());

                $this->getUsersTable()->saveUsers($users);

// Redirect to list of users

                return $this->redirect()->toRoute('users');
            }
        }

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

//-----
//-----

Above  we implement addAction() method. Let’s look at the addAction() method code in a little more detail:

$form = new UsersForm();

$form->get('submit')->setValue('Add');

We instantiate UsersForm and set the label on the submit button to “Add New User”. We do this here as we’ll want to re-use the form when editing a User and will use a different label.

if ($request->isPost()) {

$users = new Users();

$form->setData($request->getPost());

if ($form->isValid()) {

If the Request object’s isPost() method is true, then the form has been. We then set the posted data to the form and check to see if it is valid using the isValid() member function of the form.

$users->exchangeArray($form->getData());

$this->getUsersTable()->saveUsers($users);

If the form is valid, then we grab the data from the form and store to the model using saveUsers().

// Redirect to list of users

return $this->redirect()->toRoute('users');

After we have saved the new users row, we redirect back to the list of users using the Redirect controller.

return array('form' => $form);

Go Back to the Model

Now we update UsersTable.php Code with getUser() and saveUser() methods. file in module/Users/src/Users/Model directory like this:

//------
//------
    public function getUser($id) {

        $id  = (int) $id;

        $rowset = $this->tableGateway->select(array('id' => $id));

        $row = $rowset->current();

        if (!$row) {

            throw new \Exception("Could not find row $id");
        }

        return $row;
    }

    public function saveUser(Users $users) {

        $data = array(
            'name' => $users->name,
            'email' => $users->email,
            'mobile' => $users->mobile,
            'address' => $users->address,
        );

        $id = (int) $users->id;

        if ($id == 0) {

            $this->tableGateway->insert($data);
        } else {

            if ($this->getUsers($id)) {

                $this->tableGateway->update($data, array('id' => $id));
            } else {

                throw new \Exception('Users id does not exist');
            }
        }
    }
//-----
//-----

Update Our Add Form

Finally, we return the variables that we want assigned to the view. In this case, just the form object. Note that Zend Framework 2 also allows you to simply return an array containing the variables to be assigned to the view and it will create a ViewModel behind the scenes for you. This saves a little typing.

We now need to render the form in the add.phtml view script within module/Users/view/users/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();
?>

Above Code The form() view helper has an openTag() and closeTag() method which we use to open and close the form. Then for each element with a label, but for the element that are standalone, we use formHidden() .

Finally Our Add New User Successfully Done.See Below screenshot

Zend Framework 2 Add Form

GoodGood VeryGood 🙂

CRUD with Zend Framework 2 Part-2

Hi, My name is Masud Alam, love to work with Open Source Technologies, living in Dhaka, Bangladesh. I’m 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, Canadian International Development Agency (CIDA), World Vision, Care Bangladesh, Helen Keller, US AID and MAX Group where I worked on ERP software and web development., but now i’m a founder and CEO of TechBeeo Software Company 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.

11 comments on “CRUD with Zend Framework 2 Part-2 : Insert a User to Database
  1. I have two questions here .
    1: Inside the title “Back To Controller”, the following lines are there in your post .

    “Now we need to get the form to display and then process it on submission. This is done by addAction() method within theUsersController.php. add addAction() method in your UsersController.php file inside the directory ” / zf2/module/Users/view/users/users ” :”

    The last line path is not correct …..Please correct it. It should be related to controllers not in view

    2: I have got the falatal error like this .

    Fatal error: Class ‘Pilots\Controller\PilotsForm’ not found in C:\xampp\htdocs\aerowaze\module\Pilots\src\Pilots\Controller\PilotsController.php on line 22

    In line 22 ….in the controller… $form = new PilotsForm(); code is there…..

    Please help here so that it can be corrected.

  2. I may think that you have a error in your code in the model with getUser() and saveUser() methods.

    I worked in this way:
    getUsers() and saveUsers()

    • I thinks so but
      – saveUsers(); on the model have (s) should be change to saveUser(); without (s);
      – getUsers(); change to getUser(); without (s)

      I think are correct because I testing already

Leave a Reply

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