Advertisement

Google Ad Slot: content-top

Zend Form Introduction


Zend Forms – Introduction

Zend\Form is a powerful component used to manage HTML forms. It supports form creation, validation, filtering, CSRF protection, and file uploads — all using PHP code, not HTML.


Why Use Zend Forms?

  • Abstracts form creation and validation into reusable classes.
  • Easily attach validators and filters.
  • Automatically handles form rendering and input handling.
  • Built-in support for CSRF and file upload fields.



Creating a Simple Form

1. Install Packages

composer require laminas/laminas-form
composer require laminas/laminas-i18n


2.Create a class that extends Laminas\Form\Form: (module/Application/src/Form/LoginForm.php)

namespace Application\Form;
use Laminas\Form\Form;

class LoginForm extends Form
{
    public function __construct($name = null)
    {
        parent::__construct('login');
        $this->add([
            'name' => 'email',
            'type' => 'Text',
            'options' => ['label' => 'Email'],
        ]);
        $this->add([
            'name' => 'password',
            'type' => 'Password',
            'options' => ['label' => 'Password'],
        ]);
        $this->add([
            'name' => 'submit',
            'type' => 'Submit',
            'attributes' => [
                'value' => 'Login',
                'class' => 'btn btn-primary'
            ],
        ]);
    }
}


3.Using the Form in a Controller

use Application\Form\LoginForm;

public function loginAction()
{
  $form = new LoginForm();
  $request = $this->getRequest();
  if ($request->isPost()) {
    $form->setData($request->getPost());
    if ($form->isValid()) {
      // Process login
    }
  }
  return new ViewModel(['form' => $form]);
}


4.Rendering the Form in View

// In login.phtml
$form->prepare();
echo $this->form()->openTag($form);
echo $this->formRow($form->get('email'));
echo $this->formRow($form->get('password'));
echo $this->formSubmit($form->get('submit'));
echo $this->form()->closeTag();

 You can use:

  • formRow() – full label + input + error
  • formInput() – just input
  • formLabel() – just label

Output (Rendered Form)

<form method="post">
 <label>Email</label>
 <input type="text" name="email">

 <label>Password</label>
 <input type="password" name="password">

 <input type="submit" value="Login">
</form>



Real-World Usage

Use Case

Form Class

Login Form

LoginForm

Registration Form

RegisterForm

Product Entry Form

ProductForm