Skip to content

Instantly share code, notes, and snippets.

@liverbool
Created October 9, 2014 18:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liverbool/0e06f53aa10848ebe5b3 to your computer and use it in GitHub Desktop.
Save liverbool/0e06f53aa10848ebe5b3 to your computer and use it in GitHub Desktop.
fix sylius form attribute choice.
<?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