Thứ Năm, 24 tháng 4, 2014

Zend\Form [Creating a Communication Application]

Forms are usually built by creating the HTML pagfor the form, writing separatvalidation and filtering for various form events, and finally writing the controllers and actions for the form actions. With Zend Framework, theZend\Form component provides all the previously stated features in a single component.

Zend\Form allows developerto programmatically create and handle forms in your applications. Zend\Form supports form renderingform handling, input filtering and validation, and form configurations. In our nextaskwe will set up our first form in ZF2.
To create our first registration form, we will create a necontroller to display a registration form; we will also create neforms and views. We need to make the following changes to the Users module:

1.       Form – We will also need to create a registration form under src/Users/Form/ RegisterForm.php:
1.       The RegisterForm class extends Zend\Form\Form; the form's configuration is added to the constructor:

<?php
// filename : module/Users/src/Users/Form/RegisterForm.php namespace Users\Form;
use Zend\Form\Form;
class RegisterForm extends Form
{
public function   construct($name = null)
{
parent:: construct('Register');
$this->setAttribute('method', 'post');
$this->setAttribute('enctype','multipart/form- data');

2.       All fields are added to the form using the $this->add() method on the form's constructor:

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

3.       Additional validators/filtercan be added to the fields while declaring the fields in the form. In this case we are adding special validation for the EmailAddress field:

$this->add(array( 'name' => 'email', 'attributes' => array(
'type'  => 'email',
),


'options' => array( 'label' => 'Email',
),
'attributes' => array( 'required' => 'required'
),
'filters' => array(
array('name' => 'StringTrim'),
),
'validators' => array( array(
'name' => 'EmailAddress', 'options' => array(
'messages' => array(
\Zend\Validator\ EmailAddress::INVALID_FORMAT => 'Email address format is invalid'
)
)
)
)
));

4.       Use the same method to add passwordconfirm_password, and submit fields; password and confirm_password will be of type password, whereas submit will be of type button.

2.       Views – The following views will havto be created to support the registration process:
1.       Registration page: The viefor registration page is created in src/view/ users/register/index.phtml.
2.       The vieconsists of three main sections—the section to display error messages, the view logic which is used tgenerate the form tag, and the view helpers used tgenerate the actual form elements. Thefollowing logic is used to display error messages:

<section class="register">
<h2>Register</h2>
<?php if ($this->error): ?>
<p class="error">
There were one or more issues with your submission.
Please correct them as indicated below.
</p>
<?php endif ?>


3.      The following block is used tgenerate the <form> HTML tag using the
form object assigned to the view in the controller:
<?php
$form = $this->form;
$form->prepare();
$form->setAttribute('action', $this->url(NULL, array('controller'=>'Register', 'action' => 'process')));
$form->setAttribute('method', 'post'); echo $this->form()->openTag($form);
?>

4.      The following section is used tgenerate individual form elements for the
NameEmailPasswordConfirm Password, and Submit fields:
<dl class="zend_form">
<dt><?php echo $this->formLabel($form->get('name')); ?></dt>
<dd><?php
echo $this->formElement($form->get('name'));
echo $this->formElementErrors($form->get('name'));
?></dd>
<dt><?php echo $this->formLabel($form->get('email')); ?></ dt>
<dd><?php
echo $this->formElement($form->get('email'));
echo $this->formElementErrors($form->get('email'));
?></dd>
<dt><?php echo $this->formLabel($form->get('password'));
?></dt>
<dd><?php
echo $this->formElement($form->get('password'));
echo $this->formElementErrors($form->get('password'));
?></dd>
<dt><?php echo $this->formLabel($form->get('confirm_ password')); ?></dt>
<dd><?php
echo $this->formElement($form->get('confirm_password')); echo $this->formElementErrors($form->get('confirm_
password'));
?></dd>
<dd><?php
echo $this->formElement($form->get('submit'));
echo $this->formElementErrors($form->get('submit'));
?></dd>
</dl>


5.       Finally the form HTML tag needs to be closed:
<?php echo $this->form()->closeTag() ?>
</section>

6.       Confirmation page: The viefor the confirmation page is pretty straightforward, the view is created in src/view/users/register/ confirm.phtml.

<section class="register-confirm">
<h2>Register Sucessfull</h2>
<p> Thank you for your registration. </p>
</section>

3.       Controller – Now thawe have the form and viewready, our nexstep will be to have a controller in place, which will help us to access this form. We will create a neRegisterController class and load the newly created form in its index action. The necontroller will be created in the src/Users/Controller/ RegisterController.php file:
<?php
namespace Users\Controller;
use Zend\Mvc\Controller\AbstractActionController; use Zend\View\Model\ViewModel;
use Users\Form\RegisterForm;
class RegisterController extends AbstractActionController
{

public function indexAction()
{
$form = new RegisterForm();
$viewModel  = new ViewModel(array('form' =>
$form));
return $viewModel;
}
public function confirmAction()
{
$viewModel  = new ViewModel(); return $viewModel;
}
}


4.       Configuration – Nowe have created all the necessarcomponents to display our form, we need to add our controller to the invokables list in the module config (config/module.config.php):
'controllers' => array( 'invokables' => array(
'Users\Controller\Index' => 'Users\Controller\IndexController', 'Users\Controller\Register' => 'Users\Controller\RegisterController',
),

5.       Ttest the registration form's display, open anweb browser and try accessing the following URL: http://comm-app.local/users/register
The registration form should look like the following:


What just happened?
Until now we have created a form that can be used to display all the necessary fields thacan be used during the registration process. Let us try to understand how the form is being rendered. When we invoke the http://comm-app.local/users/register page, the controller creates a new instance of the RegisterForm class and displays it on the webrowser. We have added the following fields to the RegisterForm class using its constructor:

        Name
        Email
        Password
        Confirm Password
        The Submit button

These fields are added to the newly created Form object. The ViewModel pattern renders the form, and the form object gets passed over to the viefor rendering, and each field is rendered as per the logic in the view using the FormElement view helper.

Beforwe move on to the next section, please create a login form in the same way thawe used to create the registration form. The form will contain the following fields:

        Email
        Password
        The Submit button

We will be using this login form to perform authentication towards the end of this chapter.

Form validation


If you had taken a closer look at the form code, you would have noticed thawe have added some validation for the Email Address field as shown in the following snippet:

'attributes' => array( 'required' => 'required'
),
'filters' => array(
array('name' => 'StringTrim'),
),
'validators' => array( array(
'name' => 'EmailAddress', 'options' => array(
'messages' => array(
\Zend\Validator\EmailAddress::INVALID_ FORMAT => 'Email address format is invalid'
)

Sowe added the following:

        An attribute to make the field required field
        A filter to trim the string that is passed
        validator tverify if the e-mail address is in the valid format

With the introduction on Zend Framework's InputFilterwcan validate entire forms instead of attaching validation to each and everform field. This allows much cleaner code and better scalability of Zend Forms. So effectivelywcan have the same form being used in multiple sections of the website, each having its own set of validation rules that are not
dependant on the form's validation. In our next section we will set up a nevalidator for the registration form.

Không có nhận xét nào:

Đăng nhận xét