Welcome to Abdul Malik Ikhsan's Blog

Zend Framework 2 : Zend\Form – a Flexible Form Generator

Posted in Tutorial PHP, Zend Framework 2 by samsonasik on June 12, 2012

Form Generator adalah fitur yang biasa ada dalam web application Framework. Kelebihan dari Form generator adalah simple dan clean. Kekurangannya adalah hal ini sering membuat pusing designer karena tak tahu harus mengedit di bagian mana karena semua sudah dibungkus dalam sourcecode. Zend Framework 2 menghadirkan Form Generator yang flexible dalam menggenerate form sehingga tidak mewajibkan mem-build semua hal di ‘model’, sehingga urusan design diserahkan kepada designer.

Berikut contoh kode program membuat sample form :

namespace Test\Form;

use Zend\Form\Form,
    Zend\InputFilter\InputFilter,
    Zend\InputFilter\Factory as InputFactory,
    Zend\InputFilter\InputFilterAwareInterface,
    Zend\InputFilter\InputFilterInterface,

    Zend\Form\Element\Csrf as CsrfElement,
    Zend\Validator\Csrf as CsrfValidator;

class SampleForm extends Form
    implements InputFilterAwareInterface
{
    protected $inputFilter;
    protected $csrf;

    public function __construct()
    {
        parent::__construct();

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

        $this->add(array(
            'name' => 'id',
            'attributes' => array(
                'type' => 'text',
                'label' => 'Id'
            )
        ));

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

        $csrfValidator = new CsrfValidator(array('name'=> 'csrf',
                          'salt' => 'veryverys3cretT0KENZ'
                        ));

        $csrf = new CsrfElement('security');
        $csrf->setCsrfValidator($csrfValidator);
        $this->add($csrf);

        //assign!
        $this->csrf = $csrf;

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

    public function setInputFilter(InputFilterInterface $inputFilter)
    {
        throw new \Exception("Not used");
    }

    public function getInputFilter()
    {
        if (!$this->inputFilter) {
            $inputFilter    = new InputFilter();
            $factory = new InputFactory();

            $inputFilter->add($factory->createInput(array(
                'name'     => 'id',
                'required' => true,

                'validators' => array(
                    array(
                        'name'    => 'Int'
                    ),
                ),

            )));

            $inputFilter->add($factory->createInput(array(
                'name'     => 'name',
                'required' => true,
                'filters'  => array(
                    array('name' => 'StripTags'),
                    array('name' => 'StringTrim'),
                ),
                'validators' => array(
                    array(
                        'name'    => 'StringLength',
                        'options' => array(
                            'encoding' => 'UTF-8',
                            'min'      => 1,
                            'max'      => 25,
                        ),
                    ),
                ),
            )));

            $inputFilter->add($factory->createInput(array(
                'name'     => 'security',
                'required' => true,
                'validators' => array( $this->csrf->getCsrfValidator())
            )));

            $this->inputFilter = $inputFilter;
        }

        return $this->inputFilter;
    }
}

Tugas si ‘klas’ tadi mendaftarkan element-element, filter, validator, serta atribut tertentu saja. Sedang sisi view bisa dikelola oleh designer seperti layaknya kode berikut :

<?php
    $this->form->setAttribute('action',
                              $this->url('default',
                                    array('controller'=>'test-sample', 'action' => 'input')));
    echo $this->form()->openTag($this->form);

?>
<?php  echo $this->formElementErrors($this->form->get('security')); ?>
<table>
   <?php echo $this->formElement($this->form->get('security')); ?>

   <tr>

    <td>ID</td>
    <td>: </td>
    <td><?php echo $this->formInput( $this->form->get('id')); ?>
        <?php  echo $this->formElementErrors($this->form->get('id')); ?>
    </td>
   </tr>

    <tr>

    <td>NAME</td>
    <td>: </td>
    <td><?php echo $this->formInput( $this->form->get('name')); ?>
        <?php  echo $this->formElementErrors($this->form->get('name')); ?>
    </td>
   </tr>

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

</table>

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

Nah, coding Controllernya bisa seperti berikut :

namespace Test\Controller;

use Zend\Mvc\Controller\ActionController,
    Zend\View\Model\ViewModel,
    Test\Form\SampleForm;

class SampleController extends ActionController
{
    public function inputAction()
    {
        $sampleform = new SampleForm();

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

            $sampleform->setData($request->getPost());
            if ($sampleform->isValid()) {
                $this->redirect()->toRoute('default',
                                        array('controller'=>'test-sample', 'action'=>'success'));

            }

        }

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

    public function successAction()
    {
        return array();
    }
}

Done !

Referensi :
http://stackoverflow.com/questions/7157589/should-i-use-zend-form
http://stackoverflow.com/questions/9193769/disabling-view-with-in-action-in-zf2
http://akrabat.com/zend-framework-2/zend-framework-2-beta-4-released/
http://www.wjgilmore.com/blog/entry/how_i_learned_to_stop_worrying_and_love_zend_form

4 Responses

Subscribe to comments with RSS.

  1. Ahmed Sliman said, on November 21, 2013 at 8:41 pm

    How can i change attribute of the element after create:

    This is the code that create the form:

    $user = new User();
    $builder = new AnnotationBuilder();
    $this->form = $builder->createForm($user);

    I can change a form label with: $this->form->setLabel(‘test label’);, How can i access to the specific element label like ‘telephone’ ?

    • samsonasik said, on November 21, 2013 at 10:16 pm
      $this->form->get('telephone')->setOptions(
          array('label' => "TelePhoneee")
      );
      echo $this->formLabel($this->form->get('telephone'));
      
  2. Chukwuma Nze said, on January 23, 2014 at 3:48 am

    Perfect Example. Saved me a ton of time! As an extra tip, you should update this code to zend 2.2: $this->csrf->setValidator() and $this->csrf->getValidator() are now $this->csrf->setCsrfValidator() and $this->csrf->getCsrfValidator()


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

%d bloggers like this: