How to create a form in Zend Framework 2.5

Hi guys! In this tutorial I will explain how to create a new form in Zend Framework 2.5. I will follow the Zend Framework 2.5's documentation to create a form.

To create a form in Zend Framework, we must create a new folder called Forms in the same folder where we have the Controllers and Models folders.

Then, we must create a file called Album.php with this code:


namespace Newapp\Form;

use Zend\Form\Form;

class AlbumForm extends Form
{
public function __construct($name = null)
{
// we want to ignore the name passed
parent::__construct('album');

$this->add(array(
'name' => 'id',
'type' => 'Hidden',
));
$this->add(array(
'name' => 'title',
'type' => 'Text',
'options' => array(
'label' => 'Title',
),
));
$this->add(array(
'name' => 'artist',
'type' => 'Text',
'options' => array(
'label' => 'Artist',
),
));
$this->add(array(
'name' => 'submit',
'type' => 'Submit',
'attributes' => array(
'value' => 'Go',
'id' => 'submitbutton',
),
));
}
}

You can add new fields by adding this array:


$this->add(array(
'name' => 'artist',
'type' => '(Text Textarea Submit Button Checkbox)',
'options' => array(
'label' => 'Artist',
),
));

inside the __construct function.

Now, we need to set up validation for this form by using an input filter. We can add the input filter to the Album class, which resides in the Album.php file in module/Album/src/Album/Model:

Now I will add these import statements at the top of file Album.php:

use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;

In the class Album I will add the filter:


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

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

$inputFilter->add(array(
'name' => 'id',
'required' => true,
'filters' => array(
array('name' => 'Int'),
),
));

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

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

$this->inputFilter = $inputFilter;
}

return $this->inputFilter;
}

In my Controller I will add this statesment:

use Album\Form\AlbumForm;

I will add also a new action:


public function addAction()
{
$form = new AlbumForm();
$form->get('submit')->setValue('Add');

$request = $this->getRequest();
if ($request->isPost()) {
$album = new Album();
$form->setInputFilter($album->getInputFilter()); // will check the submitted data
$form->setData($request->getPost());

if ($form->isValid()) {
$album->exchangeArray($form->getData());
$this->getAlbumTable()->saveAlbum($album);

// Redirect to list of albums
return $this->redirect()->toRoute('add'); // you will redirect at the add page after submission
}
}
return array('form' => $form);
}

I will create also a route:


'add' => array(
'type' => 'segment',
'options' => array(
'route' => '/add[/:action][/:id]',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]+',
),
'defaults' => array(
'controller' => 'Newapp\Controller\Newapp', // my controller
'action' => 'add', // the name of the Controller's action
),
),
),

I will create a new file called add.phtml in my view folder. Inside of the file add.phtml I will add this code:

$title = 'Add new album';
$this->headTitle($title);
?>
escapeHtml($title); ?>
setAttribute('action', $this->url('thenameoftheroute', array('action' => 'theactionname')));
$form->prepare();

echo $this->form()->openTag($form);
echo $this->formHidden($form->get('id'));
echo $this->formRow($form->get('title'));
echo $this->formRow($form->get('artist'));
echo $this->formSubmit($form->get('submit'));
echo $this->form()->closeTag();

This function from my model:


public function saveAlbum(Album $album)
{
$data = array(
'artist' => $album->artist,
'title' => $album->title,
);

$id = (int) $album->id;
if ($id == 0) {
$this->tableGateway->insert($data);
} else {
if ($this->getAlbum($id)) {
$this->tableGateway->update($data, array('id' => $id));
} else {
throw new \Exception('Album id does not exist');
}
}
}

will save the submitted data in the database.

Video tutorial:









Leave a Comment