<?php
namespace Aqarmap\Bundle\ListingBundle\EventListener;
use Aqarmap\Bundle\ListingBundle\Entity\ListingAttribute;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
class CustomFieldSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return [FormEvents::PRE_SET_DATA => 'preSetData'];
}
public function preSetData(FormEvent $event): void
{
$data = $event->getData();
$exists_fields = [];
foreach ($data->getAttributes() as $attribute) {
$exists_fields[] = $attribute->getCustomField()->getName();
}
if ($data->getPropertyType()) {
foreach ($data->getPropertyType()->getCustomFields() as $customField) {
if (\in_array($customField->getName(), $exists_fields)) {
continue;
}
$attribute = new ListingAttribute();
$attribute->setCustomField($customField);
$data->addAttribute($attribute);
$exists_fields[] = $customField->getName();
}
}
}
}