How to set selected option to ObjectSelect

1.9k Views Asked by At

I'm working with ZF2 and Doctrine2, and created a form for a Place class. This Place has a Province property which I'd like to render as a Select field. Everything works fine when I add new Places, but when I try to edit one, I don't know how to set the "selected" attribute to the correct Option in the Select field. In the edit screen I get the following code:

...
<select name="lugar[localidad][provincia][select]">
    <option value="">Seleccione provincia...</option>
    <option value="1">Capital Federal</option>
    <option value="2">Buenos Aires</option>
</select>
...

I would like to get the this instead (assuming the object being edit has Province=Buenos Aires):

...
<select name="lugar[localidad][provincia][select]">
    <option value="">Seleccione provincia...</option>
    <option value="1">Capital Federal</option>
    <option value="2" selected>Buenos Aires</option>
</select>
...

This is the code of the fieldset which contains the ObjectSelect:

class LocalidadFieldSet extends Fieldset /*implements InputFilterAwareInterface*/
{

    public function __construct(ObjectManager $objectManager)
    {
        parent::__construct('localidad');

        $this->setHydrator(new DoctrineObject($objectManager))->setObject(new Localidad());

        $provinciaFieldSet = new ProvinciaFieldSet($objectManager);
        $this->add($provinciaFieldSet);

        $this->add(array(
            'name' => 'select',
            'type' => 'DoctrineModule\Form\Element\ObjectSelect',
            'options' => array(
                'object_manager' => $objectManager,
                'target_class' => 'Application\Entity\Localidad',
                'property' => 'nombre',
                'label' => 'Localidad',
                'empty_option' => 'Seleccione localidad...'
            )
        ));
    }
}

This is where the previous FieldSet is included in his parent FieldSet:

$localidadFieldSet = new LocalidadFieldSet($objectManager);
$this->add($localidadFieldSet);

If my entity has the following properties: $id $name

I understand its corresponding FieldSet should only have a Select element, and when an object is bound, it should set the appropriate option as "selected". Am I right?

1

There are 1 best solutions below

0
On BEST ANSWER

I got the name of the Select element wrong. I changed it from "select" to "id", and now it's setting the value properly.