2
votes

I have a class with a multiple choice property:

...

/**
 * @ORM\Column(type="array", name="majority_types")
 * @Constraints\Choice(callback="getAvailableMajorityTypes", multiple="true")
 */
private $majorityTypes;

...

public static function getAvailableMajorityTypes()
{
    return array(
        self::SIMPLE_MAJORITY,
        self::UNANIMITY_MAJORITY,
        self::THREE_FIFTHS_MAJORITY,
        self::ONE_THIRD_MAJORITY,
        self::FOUR_FIFTHS_MAJORITY
    );
}

...

I also have a form class for this class:

...

/**
 * @param FormBuilderInterface $builder
 * @param array $options
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ...
        ->add('majorityTypes', ChoiceType::class, array(
            'multiple' => true,
        ))
        ...
        ->getForm();
}

/**
 * @param OptionsResolver $resolver
 */
public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'MyClass',
    ));
}

But the choices from getAvailableMajorityTypes are not rendered.

I simply followed these steps: http://symfony.com/doc/master/reference/constraints/Choice.html#supplying-the-choices-with-a-callback-function, but for some reason it doesn't work.

Edit:

I see that using static choices as annotations neither works (choices={"foo1", "foo2"}). The only way it works is passing the choices directly in the add method when creating the form. I've not found out the problem yet.

2

2 Answers

2
votes

If I refer to your words:

But the choices from getAvailableMajorityTypes are not rendered.

It seems you're confused between rendering of options in your form's select field and the Choice constraint.

You've only implemented the constraint in your code, but you also need to add the options to your select. Like this:

/**
 * @param FormBuilderInterface $builder
 * @param array $options
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ...
        ->add('majorityTypes', ChoiceType::class, array(
            'multiple' => true,
            'choices' => YourEntity::getAvailableMajorityTypes()
        ))
0
votes

I've never used this annotation, however in the documentation the callback is public static:

// src/AppBundle/Entity/Author.php
namespace AppBundle\Entity;

class Author
{
    public static function getGenders()
    {
        return array('male', 'female');
    }
}

If you follow the documentation and make your method static as well the annotation should work.