Skip to content

1. Contact form

You will create, filter, validate and render a form.

Try it: Mezzio ยท laminas-mvc

Assumes you can set up a Mezzio handler or an MVC controller and register routes, and that you have done chapter 0.

Start with formRow

formRow renders a label, a field and its errors in one call, and is a good way to see a form working:

shared/templates/comparison/contact-form-row.phtml
<?php

declare(strict_types=1);

/**
 * The shortest way to render a field, for comparison with the field partial
 *
 * @var Laminas\View\Renderer\PhpRenderer $this
 * @var App\Forms\Contact\ContactForm $form
 */

$form->prepare();
?>
<?= $this->form()->openTag($form) ?>
    <?= $this->formElement($form->get('csrf')) ?>
    <?= $this->formRow($form->get('name')) ?>
    <?= $this->formRow($form->get('email')) ?>
    <?= $this->formRow($form->get('message')) ?>
    <?= $this->formElement($form->get('send')) ?>
<?= $this->form()->closeTag() ?>

On its own it does not print the hint option, set aria-invalid or tie errors to their field with aria-describedby, and it puts the errors after the field. The field partial adds those, and the finished version below uses it.

The finished form

shared/src/Contact/ContactForm.php
<?php

declare(strict_types=1);

namespace App\Forms\Contact;

use App\Forms\Csrf\AbstractCsrfProtectedForm;
use Laminas\Filter\StringTrim;
use Laminas\Form\Element\Email;
use Laminas\Form\Element\Submit;
use Laminas\Form\Element\Text;
use Laminas\Form\Element\Textarea;
use Laminas\InputFilter\InputFilterProviderInterface;
use Laminas\Validator\NotEmpty;
use Laminas\Validator\StringLength;
use Override;

/**
 * @api
 *
 * @extends AbstractCsrfProtectedForm<array<string, mixed>>
 */
final class ContactForm extends AbstractCsrfProtectedForm implements InputFilterProviderInterface
{
    #[Override]
    public function getInputFilterSpecification(): array
    {
        return [
            'name'    => [
                'required'   => true,
                'filters'    => [['name' => StringTrim::class]],
                'validators' => [
                    $this->notEmpty('Enter your name'),
                    [
                        'name'    => StringLength::class,
                        'options' => [
                            'max'      => 100,
                            'messages' => [StringLength::TOO_LONG => 'Your name must be 100 characters or fewer'],
                        ],
                    ],
                ],
            ],
            'email'   => [
                'required'      => true,
                'filters'       => [['name' => StringTrim::class]],
                'error_message' => 'Enter an email address in the format name@example.com',
            ],
            'message' => [
                'required'   => true,
                'filters'    => [['name' => StringTrim::class]],
                'validators' => [
                    $this->notEmpty('Enter your message'),
                    [
                        'name'    => StringLength::class,
                        'options' => [
                            'min'      => 10,
                            'max'      => 5000,
                            'messages' => [
                                StringLength::TOO_SHORT => 'Your message must be at least 10 characters',
                                StringLength::TOO_LONG  => 'Your message must be 5,000 characters or fewer',
                            ],
                        ],
                    ],
                ],
            ],
        ];
    }

    #[Override]
    public function init(): void
    {
        parent::init();

        $this->add([
            'name'       => 'name',
            'type'       => Text::class,
            'options'    => ['label' => 'Your name'],
            'attributes' => ['id' => 'name', 'required' => true, 'maxlength' => 100, 'autocomplete' => 'name'],
        ]);

        $this->add([
            'name'       => 'email',
            'type'       => Email::class,
            'options'    => ['label' => 'Email address'],
            'attributes' => [
                'id'             => 'email',
                'required'       => true,
                'autocomplete'   => 'email',
                'autocapitalize' => 'none',
                'spellcheck'     => 'false',
            ],
        ]);

        $this->add([
            'name'       => 'message',
            'type'       => Textarea::class,
            'options'    => ['label' => 'Message', 'hint' => 'Between 10 and 5,000 characters.'],
            'attributes' => ['id' => 'message', 'required' => true, 'rows' => 6],
        ]);

        $this->add([
            'name'       => 'send',
            'type'       => Submit::class,
            'attributes' => ['value' => 'Send message'],
        ]);
    }

    /** @return array{name: class-string<NotEmpty>, break_chain_on_failure: true, options: array{messages: array<string, string>}} */
    private function notEmpty(string $message): array
    {
        return [
            'name'                   => NotEmpty::class,
            'break_chain_on_failure' => true,
            'options'                => ['messages' => [NotEmpty::IS_EMPTY => $message]],
        ];
    }
}

Mezzio

mezzio/src/App/Handler/ContactHandlerFactory.php
<?php

declare(strict_types=1);

namespace App\Handler;

use Laminas\Form\FormElementManager;
use Mezzio\Template\TemplateRendererInterface;
use Psr\Container\ContainerInterface;

/** @api */
final class ContactHandlerFactory
{
    public function __invoke(ContainerInterface $container): ContactHandler
    {
        return new ContactHandler(
            $container->get(FormElementManager::class),
            $container->get(TemplateRendererInterface::class),
        );
    }
}
mezzio/src/App/ContactConfigProvider.php
<?php

declare(strict_types=1);

namespace App;

use App\Handler\ContactHandler;
use App\Handler\ContactHandlerFactory;

/** @api */
final class ContactConfigProvider
{
    /** @return array<string, mixed> */
    public function __invoke(): array
    {
        return [
            'dependencies' => [
                'factories' => [
                    ContactHandler::class => ContactHandlerFactory::class,
                ],
            ],
        ];
    }
}

Add the provider to config/config.php, and register the route:

mezzio/config/routes/contact.php
<?php

declare(strict_types=1);

use App\Handler\ContactHandler;
use Mezzio\Application;

return static function (Application $app): void {
    $app->route('/contact', ContactHandler::class, ['GET', 'POST'], 'contact');
};

laminas-mvc

mvc/module/Application/src/Controller/ContactControllerFactory.php
<?php

declare(strict_types=1);

namespace Application\Controller;

use App\Forms\Csrf\CsrfGuardInterface;
use Laminas\Form\FormElementManager;
use Psr\Container\ContainerInterface;

/** @api */
final class ContactControllerFactory
{
    public function __invoke(ContainerInterface $container): ContactController
    {
        return new ContactController(
            $container->get(FormElementManager::class),
            $container->get(CsrfGuardInterface::class),
        );
    }
}

Merge this file into your module configuration, as Module does in chapter 0:

mvc/module/Application/config/contact.config.php
<?php

declare(strict_types=1);

namespace Application;

use Laminas\Router\Http\Literal;

return [
    'router'       => [
        'routes' => [
            'contact' => [
                'type'    => Literal::class,
                'options' => [
                    'route'    => '/contact',
                    'defaults' => ['controller' => Controller\ContactController::class, 'action' => 'form'],
                ],
            ],
        ],
    ],
    'controllers'  => [
        'factories' => [
            Controller\ContactController::class => Controller\ContactControllerFactory::class,
        ],
    ],
    'view_manager' => [
        'template_map' => [
            'forms::contact' => __DIR__ . '/../../../vendor/laminas-howto/forms-shared/templates/contact.phtml',
        ],
    ],
];
shared/templates/contact.phtml
<?php

declare(strict_types=1);

/**
 * @var Laminas\View\Renderer\PhpRenderer $this
 * @var App\Forms\Contact\ContactForm $form
 * @var string|null $status
 */

$form->prepare();
$this->headTitle($form->getMessages() === [] ? 'Contact us' : 'Error: Contact us', 'SET');
?>
<?= $this->partial('forms::error-summary', ['form' => $form]) ?>

<h1>Contact us</h1>

<?php if ($status !== null): ?>
    <p role="status" tabindex="-1" autofocus><?= $this->escapeHtml($status) ?></p>
<?php endif; ?>

<p>All fields are required.</p>

<?= $this->form()->openTag($form) ?>
    <?= $this->formElement($form->get('csrf')) ?>
    <?= $this->partial('forms::field', ['element' => $form->get('name')]) ?>
    <?= $this->partial('forms::field', ['element' => $form->get('email')]) ?>
    <?= $this->partial('forms::field', ['element' => $form->get('message')]) ?>
    <?= $this->formElement($form->get('send')) ?>
<?= $this->form()->closeTag() ?>
mezzio/src/App/Handler/ContactHandler.php
<?php

declare(strict_types=1);

namespace App\Handler;

use App\Csrf\MezzioCsrfGuard;
use App\Forms\Contact\ContactForm;
use Laminas\Diactoros\Response\HtmlResponse;
use Laminas\Diactoros\Response\RedirectResponse;
use Laminas\Form\FormElementManager;
use Mezzio\Csrf\CsrfGuardInterface;
use Mezzio\Csrf\CsrfMiddleware;
use Mezzio\Flash\FlashMessageMiddleware;
use Mezzio\Flash\FlashMessagesInterface;
use Mezzio\Template\TemplateRendererInterface;
use Override;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

/** @api */
final readonly class ContactHandler implements RequestHandlerInterface
{
    public function __construct(
        private FormElementManager $forms,
        private TemplateRendererInterface $renderer,
    ) {}

    #[Override]
    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        /** @var CsrfGuardInterface $guard */
        $guard = $request->getAttribute(CsrfMiddleware::GUARD_ATTRIBUTE);
        /** @var FlashMessagesInterface $flash */
        $flash = $request->getAttribute(FlashMessageMiddleware::FLASH_ATTRIBUTE);

        $form = $this->forms->get(ContactForm::class);
        $form->setCsrfGuard(new MezzioCsrfGuard($guard));

        if ($request->getMethod() === 'POST') {
            /** @var array<string, mixed> $data */
            $data = $request->getParsedBody();
            $form->setData($data);

            if ($form->isValid()) {
                // Send the message here, using $form->getData()
                $flash->flash('status', 'Thanks, your message has been sent.');

                return new RedirectResponse('/contact', 303);
            }
        }

        return new HtmlResponse($this->renderer->render('forms::contact', [
            'form'   => $form,
            'status' => $flash->getFlash('status'),
        ]));
    }
}
mvc/module/Application/src/Controller/ContactController.php
<?php

declare(strict_types=1);

namespace Application\Controller;

use App\Forms\Contact\ContactForm;
use App\Forms\Csrf\CsrfGuardInterface;
use Laminas\Form\FormElementManager;
use Laminas\Http\Request;
use Laminas\Http\Response;
use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\Mvc\Plugin\FlashMessenger\FlashMessenger;
use Laminas\Stdlib\Parameters;
use Laminas\View\Model\ViewModel;

/** @api */
final class ContactController extends AbstractActionController
{
    public function __construct(
        private readonly FormElementManager $forms,
        private readonly CsrfGuardInterface $guard,
    ) {}

    public function formAction(): Response|ViewModel
    {
        $form = $this->forms->get(ContactForm::class);
        $form->setCsrfGuard($this->guard);

        /** @var Request $request */
        $request = $this->getRequest();
        /** @var FlashMessenger $flash */
        $flash = $this->plugin('flashMessenger');

        if ($request->isPost()) {
            /** @var Parameters $post */
            $post = $request->getPost();
            $form->setData($post->toArray());

            if ($form->isValid()) {
                // Send the message here, using $form->getData()
                $flash->addSuccessMessage('Thanks, your message has been sent.');

                return $this->redirect()->toRoute('contact')->setStatusCode(303);
            }
        }

        $view = new ViewModel([
            'form'   => $form,
            'status' => $flash->getSuccessMessages()[0] ?? null,
        ]);

        return $view->setTemplate('forms::contact');
    }
}

How it works

Elements describe the HTML. Labels, hints and attributes belong on the element. autocomplete, autocapitalize and type="email" help people fill the form in correctly, especially on phones.

The input filter describes the data. Filters run first, so " " is trimmed to an empty string and rejected.

Messages are written for people. The default messages are technical, so each rule supplies its own. error_message replaces every message for the email field, including the one from the Email element's built-in validator.

Redirect after success. The 303 response stops a page refresh from sending the message twice.

Do your work where the comment is. Send mail, queue a job or save a record at "Send the message here", using only $form->getData(), never the raw request.

Make it look right

See Styling forms for the stylesheet behind this form.

Common mistakes

  • Creating the form with new ContactForm() in application code. init() is not called, so the form is empty.
  • Forgetting parent::init(), which removes CSRF protection. The form then throws when you set the guard.
  • Reading the request body instead of getData(), which skips your filters.
  • Using placeholder text as a label.

Further opportunities

None of these are built or tested here. Add the ones your site needs.

Opportunity Where How
Limit how often someone can send Middleware (Mezzio), a dispatch listener (MVC) or your web server Count submissions per IP address over a time window, and answer with status 429 when it is exceeded
Block or allow addresses Middleware, listener or firewall Behind a proxy, trust X-Forwarded-For only when your own proxy set it
Catch simple bots Form Add a "honeypot" field that must stay empty. Hide it from everyone, including assistive technology and the Tab key
Add a challenge service A custom element and validator Verify the response on the server. Prefer a service that asks people to solve no puzzle
Filter spam Input filter Add a validator to message, for example one that rejects many links
Send mail in the background Where the "Send the message here" comment is Put a job on a queue, so a slow mail server does not slow the page
Send mail safely Your mailer Send from your own address, and use the visitor's only as Reply-To
Keep a record Handler or controller Save the filtered data, and decide how long you keep it
Fill in known details Before the form is rendered Call setData() with the name and email of a signed-in visitor

Run the tests

cd examples/forms/shared && composer install && composer check
cd ../mezzio && composer install && composer check
cd ../mvc && composer install && composer check