<?php
namespace Aqarmap\Bundle\ListingBundle\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\Validator\Constraints\NotBlank;
class BuildListingAttributeFormListener implements EventSubscriberInterface
{
/**
* Form factory.
*
* @var FormFactoryInterface
*/
private $factory;
/**
* Constructor.
*/
public function __construct(FormFactoryInterface $factory)
{
$this->factory = $factory;
}
public static function getSubscribedEvents()
{
return [FormEvents::PRE_SET_DATA => 'buildForm'];
}
/**
* Builds proper listing form after setting the listing.
*/
public function buildForm(FormEvent $event): void
{
$data = $event->getData();
$form = $event->getForm();
if (null === $data) {
$form->add($this->factory->createNamed('value', TextType::class, null, ['auto_initialize' => false]));
return;
}
// Build field options
$options = ['label' => $data->getCustomField()->getLabel(), 'auto_initialize' => false];
if (\is_array($data->getCustomField()->getOptions())) {
$options = array_merge($options, $data->getCustomField()->getOptions());
if ('integer' === $data->getCustomField()->getType()) {
unset($options['attr']['choices']);
}
$options['attr']['required'] = $data->getCustomField()->getRequired() && !$data->getListing()->hasParent() ? true : false;
$options['attr']['inputmode'] = 'integer' === $data->getCustomField()->getType() ? 'numeric' : '';
// Add field constraints
$constraints = [];
if ($data->getCustomField()->getRequired() && !$data->getListing()->hasParent()) {
$constraints[] = new NotBlank();
}
$options = array_merge($options, ['constraints' => $constraints]);
if ('choice' == $data->getCustomField()->getType()) {
$options['choices'] = array_flip($options['choices']);
if (!$data->getCustomField()->getRequired()) {
$options['placeholder'] = $data->getCustomField()->getLabel();
}
}
}
$inputTypes = [
'integer' => IntegerType::class,
'text' => TextType::class,
'choice' => ChoiceType::class,
'textarea' => TextareaType::class,
'hidden' => HiddenType::class,
];
$formType = $this->factory
->createNamedBuilder('value', $inputTypes[$data->getCustomField()->getType()], null, $options);
if ('integer' === $data->getCustomField()->getType()) {
$formType->resetViewTransformers();
}
$form
->remove('custom_field')
->add($formType->getForm())
;
}
}