Blagi
Blagi

Reputation: 45

Zend Framework 2: Set options as "selected" in select list

I'm trying to set second product as selected in list, but code below doesn't work. Any idea. Thanks

$this->add(array(
        'type' => 'Zend\Form\Element\Select',
        'name' => 'manufacturer',
        'options' => array(
            'label' => 'Manufacturer name',
            'value_options' => $this->getManufacturer(),
            'empty_option'  => '--- select manufacturer ---',
        ),
        'attributes' => array(
            'value' => 2,
            'selected' => true,
        ),
    ));

Upvotes: 3

Views: 4698

Answers (2)

Jangya satapathy
Jangya satapathy

Reputation: 906

I am giving a simple example here, hope it may help you. As you mentioned for to get selected element, simple use the value attribute has the value of that selected element like:

    $this->add(array(
        'type' => 'Zend\Form\Element\Select',
        'name' => 'gender',
        'options' => array(
            'label' => 'Gender',
            'value_options' => array(
                '1' => 'Select your gender',
                '2' => 'Female',
                '3' => 'Male'
            ),
        ),
        'attributes' => array(
            'value' => '1' //set selected to '1'
        )
    ));

you can prefer this link for more And if you are getting

haystack option is mandatory

then Add the disable_inarray_validator to the options:

    $this->add(array(
    ...
    'options' => array(
      'disable_inarray_validator' => true,
      'label' => 'county',
    ),
 ));

Upvotes: 5

peterpeterson
peterpeterson

Reputation: 1325

If I am not mistaken the value is part of the options not an attribute.

$this->add(array(
    'type' => 'Zend\Form\Element\Select',
    'name' => 'manufacturer',
    'options' => array(
        'label' => 'Manufacturer name',
        'value_options' => $this->getManufacturer(),
        'empty_option'  => '--- select manufacturer ---',
        'value' => '2'
    )
));

Upvotes: 0

Related Questions