Skip to content

Using the Action Subscribers

Iltar van der Berg edited this page Apr 6, 2017 · 3 revisions

In some cases you might want to the use ActionSubscriberInterface instead of registering your onSuccess and onFailure callbacks. This provides a more traditional form handler and allows for easier unit testing of your code.

To do so, your handler need to also implement the ActionSubscriberInterface which requires a single static method called ::getSubscribedActions(). This method returns an array indexed by action names and whose values are the method name to call.

For action names, see the HandlerActions class.

A simple example of a HandlerType which implements the ActionSubscriberInterface is shown below.

<?php
use Hostnet\Component\FormHandler\ActionSubscriberInterface;
use Hostnet\Component\FormHandler\HandlerActions;
use Hostnet\Component\FormHandler\HandlerConfigInterface;
use Hostnet\Component\FormHandler\HandlerTypeInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\RouterInterface;

class MyFormHandler implements HandlerTypeInterface, ActionSubscriberInterface
{
    private $router;

    public function __construct(RouterInterface $router)
    {
        $this->router = $router;
    }

    /** {@inheritdoc} */
    public function configure(HandlerConfigInterface $config)
    {
        $config->setType(MyFormType::class);
        $config->registerActionSubscriber($this);
    }

    /** {@inheritdoc} */
    public function getSubscribedActions()
    {
        return [
            HandlerActions::SUCCESS => 'onSuccess',
            HandlerActions::FAILURE => 'onFailure',
        ];
    }

    public function onSuccess(MyFormData $data, FormInterface $form, Request $request)
    {
        // do something with the form data, like setting some data in the user
        $data->getUser()->setUsername($data->getUsername());

        // ...
        
        return new RedirectResponse($this->router->generate('my-route'));
    }

    public function onFailure(MyFormData $data, FormInterface $form, Request $request)
    {
        $request->getSession()->getFlashBag()->add('error', 'Something was wrong');
    }
}

To register a subscriber with the handler, use the ::registerActionSubscriber() method in the HandlerConfigInterface. You should do this in the ::configure() method of the HandlerType.

Clone this wiki locally