ikucheriavenko
2/26/2019 - 3:48 PM

Param recipient form type

<?php

namespace Lycan\NotificationBundle\Form\Type;

use Lycan\NotificationBundle\Entity\EmailPipe;
use Lycan\NotificationBundle\Entity\Notification;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Class ParamRecipientsType
 */
class ParamRecipientsType extends AbstractType
{
    /**
     * @var string
     */
    private $adminUniqid;

    /**
     * @var array
     */
    private $recipients = [];

    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
            $this->adminUniqid = $event->getForm()->getParent()->getName();
            /** @var Notification|null $notification */
            if (null !== $notification = $event->getForm()->getParent()->getData()) {
                $pipe = $notification->getPipe();
                if ($pipe instanceof EmailPipe) {
                    $this->recipients = $pipe->getParamRecipients();
                }
            }
        });

        $builder->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) {
            $pipe = $event->getForm()->getParent()->get('pipe')->getData();
            if ($pipe instanceof EmailPipe) {
                $recipients = \array_values($event->getForm()->getExtraData());
                $pipe->setParamRecipients($recipients);
            }
        });
    }

    /**
     * {@inheritdoc}
     */
    public function buildView(FormView $view, FormInterface $form, array $options): void
    {
        $view->vars['adminUniqid'] = $this->adminUniqid;
        $view->vars['recipients'] = $this->recipients;
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'allow_extra_fields' => true,
            'mapped' => false,
        ]);
    }
}