<?php
declare(strict_types=1);
namespace Harmonizely\Form\EventListener;
use Harmonizely\Model\EventTypeInterface;
use Misd\PhoneNumberBundle\Form\Type\PhoneNumberType;
use Misd\PhoneNumberBundle\Validator\Constraints\PhoneNumber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Validator\Constraints\NotBlank;
class AddPhoneNumberFieldSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [FormEvents::PRE_SUBMIT => 'preSubmit'];
}
public function preSubmit(FormEvent $event): void
{
$form = $event->getForm();
/** @var EventTypeInterface $eventType */
$eventType = $form->getParent()->get('eventType')->getData();
if ($eventType->isShowPhone()) {
$constraints = [];
$constraints[] = new PhoneNumber();
if ($eventType->isPhoneFieldRequired()) {
$constraints[] = new NotBlank();
}
$form->add('phoneNumber', PhoneNumberType::class, [
'constraints' => $constraints,
]);
}
}
}