Skip to content

4. Edit profile form

You will bind an object to a form, so that it fills the fields and receives the new values. You will also use a select, radio buttons and optional fields.

Try it: Mezzio ยท laminas-mvc

Assumes you have done chapter 0 and chapter 3.

shared/src/Profile/ProfileForm.php
<?php

declare(strict_types=1);

namespace App\Forms\Profile;

use App\Forms\Csrf\AbstractCsrfProtectedForm;
use App\Forms\Register\EmailAvailabilityInterface;
use App\Forms\Register\EmailAvailableValidator;
use Laminas\Filter\StringTrim;
use Laminas\Filter\ToNull;
use Laminas\Form\Element\Email;
use Laminas\Form\Element\Radio;
use Laminas\Form\Element\Select;
use Laminas\Form\Element\Submit;
use Laminas\Form\Element\Text;
use Laminas\Form\Element\Textarea;
use Laminas\Form\Element\Url;
use Laminas\Hydrator\ReflectionHydrator;
use Laminas\InputFilter\InputFilterProviderInterface;
use Laminas\Validator\AbstractValidator;
use Laminas\Validator\NotEmpty;
use Laminas\Validator\Regex;
use Laminas\Validator\StringLength;
use LogicException;
use Override;

/**
 * Edits a Profile object. Bind one before validating
 *
 * It needs a service, so register ProfileFormFactory with the form element manager.
 *
 * @api
 *
 * @extends AbstractCsrfProtectedForm<Profile>
 */
final class ProfileForm extends AbstractCsrfProtectedForm implements InputFilterProviderInterface
{
    public const array COUNTRIES = [
        'AU' => 'Australia',
        'CA' => 'Canada',
        'GB' => 'United Kingdom',
        'NZ' => 'New Zealand',
        'US' => 'United States',
    ];

    public const array CONTACT = [
        'email' => 'By email',
        'post'  => 'By post',
        'none'  => 'Do not contact me',
    ];

    private const string EMAIL_FORMAT = 'Enter an email address in the format name@example.com';

    public function __construct(
        private readonly EmailAvailabilityInterface $emails,
    ) {
        parent::__construct();
    }

    /** @throws LogicException If the email element has been replaced by another type. */
    #[Override]
    public function getInputFilterSpecification(): array
    {
        /** @var object|null $profile */
        $profile = $this->getObject();
        $emails  = new OwnAddressAvailability($this->emails, $profile instanceof Profile ? $profile->email : null);

        return [
            'name'    => [
                'required'   => true,
                'filters'    => [['name' => StringTrim::class]],
                'validators' => [
                    $this->notEmpty('Enter your name'),
                    $this->maxLength(100, 'Your name must be 100 characters or fewer'),
                ],
            ],
            'email'   => [
                'required'   => true,
                'validators' => [
                    [...$this->notEmpty(self::EMAIL_FORMAT), 'priority' => 100],
                    new EmailAvailableValidator($emails, $this->email()->getEmailValidator()),
                ],
            ],
            'country' => [
                'required'      => true,
                'error_message' => 'Choose your country',
            ],
            // The Url element also accepts "javascript:" addresses, which are dangerous in a link
            'website' => [
                'required'      => false,
                'filters'       => [['name' => StringTrim::class], $this->emptyToNull()],
                'validators'    => [['name' => Regex::class, 'options' => ['pattern' => '#\Ahttps?://#i']]],
                'error_message' => 'Enter a web address that starts with http:// or https://',
            ],
            'bio'     => [
                'required'   => false,
                'filters'    => [['name' => StringTrim::class], $this->emptyToNull()],
                'validators' => [$this->maxLength(500, 'Your description must be 500 characters or fewer')],
            ],
            'contact' => [
                'required'      => true,
                'error_message' => 'Choose how we should contact you',
            ],
        ];
    }

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

        // Reads and writes the properties of the bound object
        $this->setHydrator(new ReflectionHydrator());

        $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',
            ],
        ]);

        $format = $this->email()->getEmailValidator();

        if ($format instanceof AbstractValidator) {
            $format->setMessage(self::EMAIL_FORMAT);
        }

        $this->add([
            'name'       => 'country',
            'type'       => Select::class,
            'options'    => [
                'label'         => 'Country',
                'empty_option'  => 'Choose a country',
                'value_options' => self::COUNTRIES,
            ],
            'attributes' => ['id' => 'country', 'required' => true, 'autocomplete' => 'country'],
        ]);

        $this->add([
            'name'       => 'website',
            'type'       => Url::class,
            'options'    => ['label' => 'Website (optional)', 'hint' => 'For example, https://example.com.'],
            'attributes' => ['id' => 'website', 'maxlength' => 2048, 'autocomplete' => 'url'],
        ]);

        $this->add([
            'name'       => 'bio',
            'type'       => Textarea::class,
            'options'    => ['label' => 'About you (optional)', 'hint' => 'Up to 500 characters.'],
            'attributes' => ['id' => 'bio', 'rows' => 4],
        ]);

        $this->add([
            'name'       => 'contact',
            'type'       => Radio::class,
            'options'    => ['label' => 'How should we contact you?', 'value_options' => self::CONTACT],
            'attributes' => ['id' => 'contact', 'required' => true],
        ]);

        $this->add([
            'name'       => 'save',
            'type'       => Submit::class,
            'attributes' => ['value' => 'Save changes'],
        ]);
    }

    /** @throws LogicException If the email element has been replaced by another type. */
    private function email(): Email
    {
        $element = $this->get('email');

        return $element instanceof Email ? $element : throw new LogicException('The email element is missing');
    }

    /** @return array{name: class-string<ToNull>, options: array{type: int}} */
    private function emptyToNull(): array
    {
        return ['name' => ToNull::class, 'options' => ['type' => ToNull::TYPE_STRING]];
    }

    /** @return array{name: class-string<StringLength>, options: array{max: int, messages: array<string, string>}} */
    private function maxLength(int $max, string $message): array
    {
        return [
            'name'    => StringLength::class,
            'options' => ['max' => $max, 'messages' => [StringLength::TOO_LONG => $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]],
        ];
    }
}

The object the form edits:

shared/src/Profile/Profile.php
<?php

declare(strict_types=1);

namespace App\Forms\Profile;

/**
 * What a person can change about their own account
 *
 * @api
 */
final class Profile
{
    public function __construct(
        public string $name,
        public string $email,
        public string $country,
        public ?string $website = null,
        public ?string $bio = null,
        public string $contact = 'email',
    ) {}
}

The handler or controller asks for the signed-in person's profile through a one-method interface:

shared/src/Profile/ProfileProviderInterface.php
<?php

declare(strict_types=1);

namespace App\Forms\Profile;

/** @api */
interface ProfileProviderInterface
{
    /**
     * The profile of the signed-in person.
     */
    public function current(): Profile;
}
shared/src/Profile/DemoProfileProvider.php
<?php

declare(strict_types=1);

namespace App\Forms\Profile;

use Override;

/**
 * Returns the same made-up person every time. Replace it with your user storage
 *
 * @api
 */
final class DemoProfileProvider implements ProfileProviderInterface
{
    #[Override]
    public function current(): Profile
    {
        return new Profile(
            name: 'Sam Taylor',
            email: 'sam@example.com',
            country: 'AU',
        );
    }
}

People must be able to keep their own email address, which the lookup from chapter 3 reports as taken:

shared/src/Profile/OwnAddressAvailability.php
<?php

declare(strict_types=1);

namespace App\Forms\Profile;

use App\Forms\Register\EmailAvailabilityInterface;
use Override;

use function strcasecmp;

/**
 * Lets people keep the address they already have, which a plain lookup would report as taken
 *
 * @api
 */
final readonly class OwnAddressAvailability implements EmailAvailabilityInterface
{
    public function __construct(
        private EmailAvailabilityInterface $emails,
        private ?string $own,
    ) {}

    #[Override]
    public function isAvailable(string $email): bool
    {
        if (null !== $this->own && 0 === strcasecmp($this->own, $email)) {
            return true;
        }

        return $this->emails->isAvailable($email);
    }
}

The lookup and its validator are the ones from chapter 3:

shared/src/Register/EmailAvailabilityInterface.php
<?php

declare(strict_types=1);

namespace App\Forms\Register;

/** @api */
interface EmailAvailabilityInterface
{
    public function isAvailable(string $email): bool;
}
shared/src/Register/EmailAvailableValidator.php
<?php

declare(strict_types=1);

namespace App\Forms\Register;

use Laminas\Validator\AbstractValidator;
use Laminas\Validator\ValidatorInterface;
use Override;

use function is_string;

/**
 * Rejects an address that already has an account
 *
 * Only well formed addresses are looked up. Anything else is left for the format validator to report.
 *
 * @api
 */
final class EmailAvailableValidator extends AbstractValidator
{
    public const string TAKEN = 'emailTaken';

    public const string MESSAGE = 'An account already uses this email address. Sign in instead';

    /**
     * @mago-expect analysis:missing-property-type The parent declares this property without a type
     *
     * @var array<string, string>
     */
    protected $messageTemplates = [
        self::TAKEN => self::MESSAGE,
    ];

    public function __construct(
        private readonly EmailAvailabilityInterface $emails,
        private readonly ValidatorInterface $format,
    ) {
        parent::__construct();
    }

    #[Override]
    public function isValid(mixed $value): bool
    {
        if (! is_string($value) || ! $this->format->isValid($value) || $this->emails->isAvailable($value)) {
            return true;
        }

        $this->error(self::TAKEN);

        return false;
    }
}
shared/src/Register/DemoEmailAvailability.php
<?php

declare(strict_types=1);

namespace App\Forms\Register;

use Override;

use function in_array;
use function strtolower;

/**
 * Treats two addresses as taken, so that the examples can be tried. Replace it with your user storage
 *
 * @api
 */
final class DemoEmailAvailability implements EmailAvailabilityInterface
{
    private const array TAKEN = ['pat@example.com', 'sam@example.com'];

    #[Override]
    public function isAvailable(string $email): bool
    {
        return ! in_array(strtolower($email), self::TAKEN, strict: true);
    }
}
shared/src/Profile/ProfileFormFactory.php
<?php

declare(strict_types=1);

namespace App\Forms\Profile;

use App\Forms\Register\EmailAvailabilityInterface;
use Psr\Container\ContainerInterface;

/** @api */
final class ProfileFormFactory
{
    public function __invoke(ContainerInterface $container): ProfileForm
    {
        return new ProfileForm($container->get(EmailAvailabilityInterface::class));
    }
}

The Url element needs laminas-uri, and the hydrator comes from laminas-hydrator. Both are in the install command.

Mezzio

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

declare(strict_types=1);

namespace App\Handler;

use App\Forms\Profile\ProfileProviderInterface;
use Laminas\Form\FormElementManager;
use Mezzio\Template\TemplateRendererInterface;
use Psr\Container\ContainerInterface;

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

declare(strict_types=1);

namespace App;

use App\Forms\Profile\DemoProfileProvider;
use App\Forms\Profile\ProfileForm;
use App\Forms\Profile\ProfileFormFactory;
use App\Forms\Profile\ProfileProviderInterface;
use App\Forms\Register\DemoEmailAvailability;
use App\Forms\Register\EmailAvailabilityInterface;
use App\Handler\ProfileHandler;
use App\Handler\ProfileHandlerFactory;
use Laminas\ServiceManager\Factory\InvokableFactory;

/** @api */
final class ProfileConfigProvider
{
    /** @return array<string, mixed> */
    public function __invoke(): array
    {
        return [
            'dependencies'  => [
                'aliases'   => [
                    EmailAvailabilityInterface::class => DemoEmailAvailability::class,
                    ProfileProviderInterface::class   => DemoProfileProvider::class,
                ],
                'factories' => [
                    DemoEmailAvailability::class => InvokableFactory::class,
                    DemoProfileProvider::class   => InvokableFactory::class,
                    ProfileHandler::class        => ProfileHandlerFactory::class,
                ],
            ],
            'form_elements' => [
                'factories' => [
                    ProfileForm::class => ProfileFormFactory::class,
                ],
            ],
        ];
    }
}

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

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

declare(strict_types=1);

use App\Handler\ProfileHandler;
use Mezzio\Application;

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

laminas-mvc

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

declare(strict_types=1);

namespace Application\Controller;

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

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

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

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

declare(strict_types=1);

namespace Application;

use App\Forms\Profile\DemoProfileProvider;
use App\Forms\Profile\ProfileForm;
use App\Forms\Profile\ProfileFormFactory;
use App\Forms\Profile\ProfileProviderInterface;
use App\Forms\Register\DemoEmailAvailability;
use App\Forms\Register\EmailAvailabilityInterface;
use Laminas\Router\Http\Literal;
use Laminas\ServiceManager\Factory\InvokableFactory;

return [
    'router'          => [
        'routes' => [
            'profile' => [
                'type'    => Literal::class,
                'options' => [
                    'route'    => '/profile',
                    'defaults' => ['controller' => Controller\ProfileController::class, 'action' => 'form'],
                ],
            ],
        ],
    ],
    'controllers'     => [
        'factories' => [
            Controller\ProfileController::class => Controller\ProfileControllerFactory::class,
        ],
    ],
    'service_manager' => [
        'aliases'   => [
            EmailAvailabilityInterface::class => DemoEmailAvailability::class,
            ProfileProviderInterface::class   => DemoProfileProvider::class,
        ],
        'factories' => [
            DemoEmailAvailability::class => InvokableFactory::class,
            DemoProfileProvider::class   => InvokableFactory::class,
        ],
    ],
    'form_elements'   => [
        'factories' => [
            ProfileForm::class => ProfileFormFactory::class,
        ],
    ],
    'view_manager'    => [
        'template_map' => [
            'forms::profile' => __DIR__ . '/../../../vendor/laminas-howto/forms-shared/templates/profile.phtml',
            'forms::radios'  => __DIR__ . '/../../../vendor/laminas-howto/forms-shared/templates/radios.phtml',
        ],
    ],
];
shared/templates/profile.phtml
<?php

declare(strict_types=1);

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

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

<h1>Edit your profile</h1>

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

<p>All fields are required unless marked optional.</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('country')]) ?>
    <?= $this->partial('forms::field', ['element' => $form->get('website')]) ?>
    <?= $this->partial('forms::field', ['element' => $form->get('bio')]) ?>
    <?= $this->partial('forms::radios', ['element' => $form->get('contact')]) ?>
    <?= $this->formElement($form->get('save')) ?>
<?= $this->form()->closeTag() ?>

Radio buttons need their own partial, which names the group with a fieldset and legend:

shared/templates/radios.phtml
<?php

declare(strict_types=1);

/**
 * @var Laminas\View\Renderer\PhpRenderer $this
 * @var Laminas\Form\Element\Radio $element
 */

$id = (string) $element->getAttribute('id');
$hasErrors = $element->getMessages() !== [];

if ($hasErrors) {
    $element->setAttribute('aria-invalid', 'true');
}
?>
<fieldset class="field radios"<?= $hasErrors ? ' aria-describedby="' . $this->escapeHtmlAttr($id) . '-error"' : '' ?>>
    <legend><?= $this->escapeHtml($element->getLabel()) ?></legend>
    <?= $this->formElementErrors($element, ['class' => 'error', 'id' => $id . '-error']) ?>
    <?= $this->formRadio($element) ?>
</fieldset>
mezzio/src/App/Handler/ProfileHandler.php
<?php

declare(strict_types=1);

namespace App\Handler;

use App\Csrf\MezzioCsrfGuard;
use App\Forms\Profile\Profile;
use App\Forms\Profile\ProfileForm;
use App\Forms\Profile\ProfileProviderInterface;
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 ProfileHandler implements RequestHandlerInterface
{
    public function __construct(
        private FormElementManager $forms,
        private TemplateRendererInterface $renderer,
        private ProfileProviderInterface $profiles,
    ) {}

    #[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(ProfileForm::class);
        $form->setCsrfGuard(new MezzioCsrfGuard($guard));
        // Fills the fields now, and receives the new values when they are valid
        $form->bind($this->profiles->current());

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

            if ($form->isValid()) {
                /** @var Profile $profile */
                $profile = $form->getData();
                // Save $profile here
                $flash->flash('status', "Saved the profile for {$profile->name}.");

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

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

declare(strict_types=1);

namespace Application\Controller;

use App\Forms\Csrf\CsrfGuardInterface;
use App\Forms\Profile\Profile;
use App\Forms\Profile\ProfileForm;
use App\Forms\Profile\ProfileProviderInterface;
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 ProfileController extends AbstractActionController
{
    public function __construct(
        private readonly FormElementManager $forms,
        private readonly CsrfGuardInterface $guard,
        private readonly ProfileProviderInterface $profiles,
    ) {}

    public function formAction(): Response|ViewModel
    {
        $form = $this->forms->get(ProfileForm::class);
        $form->setCsrfGuard($this->guard);
        // Fills the fields now, and receives the new values when they are valid
        $form->bind($this->profiles->current());

        /** @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()) {
                /** @var Profile $profile */
                $profile = $form->getData();
                // Save $profile here
                $flash->addSuccessMessage("Saved the profile for {$profile->name}.");

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

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

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

How it works

Bind, then set the data. bind() fills the fields from the object. After setData() and a successful isValid(), the filtered values are written back, and getData() returns that same object. If validation fails, the object is not touched.

The hydrator does the copying. ReflectionHydrator matches field names to properties, including private ones. Keys without a matching property, such as csrf, are ignored.

Only your fields get through. Extra values in the request, such as role=administrator, are not part of the input filter, so they never reach the object. A property with no field keeps its value.

Optional means null. An empty box submits an empty string. ToNull turns it into null, which suits a ?string property.

Web addresses need a second check. The Url element accepts any absolute address, including javascript: ones that run code when used in a link. The extra rule allows only http and https.

Radio buttons are one question. Without a fieldset and legend, a screen reader announces "By post" with no hint of what is being asked.

Help people fill it in. The country and url autocomplete values work on selects and web addresses too. Optional fields say so in their label.

Before you use this for real

  • Load the profile of the signed-in person. Never take a user ID from the form or the address bar without checking it belongs to them.
  • Save the object where the "Save $profile here" comment is.
  • Confirm a new email address before using it, and tell the old address about the change.
  • Ask for the password again before changing an email address.
  • Escape the stored values wherever you show them, with escapeHtml and escapeHtmlAttr.
  • Put a unique index on the email column.

Further opportunities

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

Opportunity Where How
Group related fields A fieldset class with its own hydrator Useful when an address or similar group appears on several forms
Use richer types Hydrator strategies Convert dates, enums and value objects on the way in and out
Detect conflicting edits Form and storage Add a version field, and refuse to overwrite a newer record
Record what changed Handler or controller Compare the object before binding and after validation
Load countries from data Form factory Set the select's value_options from your own source
Check that a website exists A background job Fetching addresses while handling the request is slow, and can be abused to reach your internal network
Add a picture A file field Uploads need their own care

Common mistakes

  • Calling bind() after setData(). The fields are refilled from the object, so a failed submission shows the old values instead of what was typed.
  • Using ObjectPropertyHydrator here. It creates a new property for every key that has none, such as csrf, and PHP deprecates that.
  • Giving a property a type that cannot hold what the form sends, such as a non-nullable string for an optional field.
  • Trusting the Url element alone.
  • Building radio buttons without a legend.