src/Aqarmap/Bundle/ListingBundle/EventListener/CustomFieldSubscriber.php line 17

Open in your IDE?
  1. <?php
  2. namespace Aqarmap\Bundle\ListingBundle\EventListener;
  3. use Aqarmap\Bundle\ListingBundle\Entity\ListingAttribute;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\Form\FormEvent;
  6. use Symfony\Component\Form\FormEvents;
  7. class CustomFieldSubscriber implements EventSubscriberInterface
  8. {
  9.     public static function getSubscribedEvents()
  10.     {
  11.         return [FormEvents::PRE_SET_DATA => 'preSetData'];
  12.     }
  13.     public function preSetData(FormEvent $event): void
  14.     {
  15.         $data $event->getData();
  16.         $exists_fields = [];
  17.         foreach ($data->getAttributes() as $attribute) {
  18.             $exists_fields[] = $attribute->getCustomField()->getName();
  19.         }
  20.         if ($data->getPropertyType()) {
  21.             foreach ($data->getPropertyType()->getCustomFields() as $customField) {
  22.                 if (\in_array($customField->getName(), $exists_fields)) {
  23.                     continue;
  24.                 }
  25.                 $attribute = new ListingAttribute();
  26.                 $attribute->setCustomField($customField);
  27.                 $data->addAttribute($attribute);
  28.                 $exists_fields[] = $customField->getName();
  29.             }
  30.         }
  31.     }
  32. }