grogers
grogers

Reputation: 85

Symfony2 How to set option value in choice entity field

I'd like to know if there's a way to set the value of an option in a select list. This select is a choice entity field.

Everything is working fine in my code. The point is that in my view I got the ID of each field in the value option and I need to have another field in there.

I'm using the option property to set what will be showed in the option name, but I need to set what will appear in the value field also.

I have no success to found a solution until now, so if anyone could help me out, it will be really appreciated.

A little part of my field in form type.

->add('fieldName','entity', array(
    'class'    => 'path\to\entity',
    'property' => 'name',
    'multiple' => true,
    'expanded' => false,
    )

Thanks.

My returned HTML code looks like this

<select>
    <option value="4">ROLE_EXAMPLE</option>
</select>

What I'm trying to do is get a result like this:

<select>
    <option value="specific_property_from_entity">ROLE_EXAMPLE</option>
</select>

Upvotes: 4

Views: 5550

Answers (3)

Akhmed
Akhmed

Reputation: 1179

You can pass choice_value option, which uses callable or property path (getProperty()) to populate your choice values

->add('fieldName','entity', array(
    'class'    => 'path\to\entity',
    'property' => 'name',
    'multiple' => true,
    'expanded' => false,
    'choice_value => 'Property'
)

If you are using a callable to populate choice_value, you need to check for the case that the value of the field may be null.

Upvotes: 0

Bartek
Bartek

Reputation: 1359

You can use choice type instead of entity, here's some example:

class YourType extends AbstractType
{
    protected $em;

    // Injecting EntityManager into YourType
    public function __construct(EntityManager $em)
    {
        $this->em = $em;
    }

    private function getChoices()
    {
        // some logic here using $this->em
        // it should return key-value array, example:
        return [
            'foo' => 'bar',
            'test' => 'abc', // and so on...
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
         $builder->add('fieldName', 'choice', [
            'choices' => $this->getChoices(),
             ]
         )
    }

}

You can read about creating field types as a service

Upvotes: 4

Einenlum
Einenlum

Reputation: 620

If I understand your question, you are asking how to set a preferred choice on an entity field.

You can look at this answer: https://stackoverflow.com/a/12000289/3524372

Upvotes: 0

Related Questions