Created
October 9, 2014 18:01
-
-
Save liverbool/0e06f53aa10848ebe5b3 to your computer and use it in GitHub Desktop.
fix sylius form attribute choice.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace BugFix\Sylius\CoreBundle\Form\Type; | |
use Sylius\Component\Attribute\Model\AttributeTypes; | |
use Symfony\Component\EventDispatcher\EventSubscriberInterface; | |
use Symfony\Component\Form\FormEvent; | |
use Symfony\Component\Form\FormEvents; | |
use Symfony\Component\Form\FormFactoryInterface; | |
class BuildAttributeFormChoicesListener implements EventSubscriberInterface | |
{ | |
/** | |
* Form factory. | |
* | |
* @var FormFactoryInterface | |
*/ | |
private $factory; | |
/** | |
* Constructor. | |
* | |
* @param FormFactoryInterface $factory | |
*/ | |
public function __construct(FormFactoryInterface $factory) | |
{ | |
$this->factory = $factory; | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public static function getSubscribedEvents() | |
{ | |
return array( | |
FormEvents::PRE_SET_DATA => 'buildChoices', | |
FormEvents::PRE_SUBMIT => 'addConfiguration', | |
); | |
} | |
public function addConfiguration(FormEvent $event) | |
{ | |
$data = $event->getData(); | |
$choices = array(); | |
if (AttributeTypes::CHOICE === $data['type'] && !empty($data['choices'])) { | |
foreach($data['choices'] as $choice) { | |
$choices[$choice] = $choice; | |
} | |
$choices = array('choices' => $choices); | |
} | |
$data['configuration'] = $choices; | |
if (!$event->getForm()->has('configuration')) { | |
$event->getForm()->add( | |
$this->factory->createNamed('configuration', 'collection', null, array( | |
'allow_add' => true, | |
'allow_delete' => true, | |
'by_reference' => false, | |
'auto_initialize' => false | |
)) | |
); | |
} | |
$event->setData($data); | |
} | |
public function buildChoices(FormEvent $event) | |
{ | |
$attribute = $event->getData(); | |
if (null === $attribute) { | |
return; | |
} | |
$type = $attribute->getType(); | |
if (null === $type || AttributeTypes::CHOICE === $type) { | |
$data = null; | |
$config = $attribute->getConfiguration(); | |
if (!empty($config['choices'])) { | |
$data = $config['choices']; | |
} | |
$event->getForm()->add( | |
$this->factory->createNamed('choices', 'collection', null, array( | |
'type' => 'text', | |
'allow_add' => true, | |
'allow_delete' => true, | |
'by_reference' => false, | |
'auto_initialize' => false, | |
'mapped' => false, | |
'data' => $data, | |
) | |
)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment