src/Form/EventSubscriber/Quote/AddAttributeValueSubscriber.php line 33

  1. <?php
  2. namespace App\Form\EventSubscriber\Quote;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
  5. use Symfony\Component\Form\Extension\Core\Type\TextType;
  6. use Symfony\Component\Form\FormEvent;
  7. use Symfony\Component\Form\FormEvents;
  8. use Sylius\Component\Locale\Context\LocaleContextInterface;
  9. use Symfony\Component\HttpFoundation\RequestStack;
  10. class AddAttributeValueSubscriber implements EventSubscriberInterface
  11. {
  12.  
  13.     public $request;
  14.     private $contextLocale
  15.     public function __construct(RequestStack $requestLocaleContextInterface $localeContext)
  16.     {
  17.         $this->request $request->getCurrentRequest();
  18.         $this->contextLocale $localeContext;  
  19.     }
  20.     public static function getSubscribedEvents()
  21.     {
  22.         // Tells the dispatcher that you want to listen on the form.pre_set_data
  23.         // event and that the preSetData method should be called.
  24.         return [FormEvents::PRE_SET_DATA => 'preSetData'];
  25.     }
  26.     public function preSetData(FormEvent $event)
  27.     {
  28.         dd($this->contextLocale->getLocaleCode());
  29.         $data $event->getData();
  30.         $attribute $data->getAttribute();
  31.         $configuration $attribute->getConfiguration();
  32.   
  33.         switch ($attribute->getType()) {
  34.             case 'select':
  35.                 $type ChoiceType::class;
  36.                 $optionConf $this->buildFormOptions($attribute);
  37.                 break;
  38.             default:
  39.                 $type TextType::class;
  40.                 $optionConf =  $attribute->getConfiguration();
  41.                 break;
  42.         }
  43.         $form $event->getForm();
  44.         $form
  45.             ->add('value'$type$optionConf);
  46.     }
  47.     private function buildFormOptions($attribute)
  48.     {
  49.         $optionConf $attribute->getConfiguration();
  50.         $choices = [];
  51.         foreach ($optionConf['choices'] as $value) {
  52.             foreach ($value as  $ele) {
  53.                 
  54.                 $choices[] = $ele;
  55.             }
  56.         }
  57.         //dd(array_($choices));
  58.         $optionConf['choices'] = $choices;
  59.         return array(
  60.             'choices' =>  $choices,
  61.             'multiple' =>  $optionConf['multiple'],
  62.             'expanded' => false,
  63.             'required' => true);
  64.     }
  65. }