Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zend Framework - Set 'selected' value in select box dropdown list

I am adding a select element to a Zend_Form instance as follows:

  $user = $form->createElement('select','user')->setLabel('User: ')->setRequired(true);
  foreach($users as $u)
        {
            if($selected == $u->id)
            {
                $user->addMultiOption($u->id,$u->firstname.' '.$u->lastname);
                //*** some way of setting a selected option? selected="selected"

            }
            else
                $user->addMultiOption($u->id,$u->firstname.' '.$u->lastname);
        }

I have been searching the docs but cannot find a simple way of pre-setting an option of the select element to 'selected'.

like image 908
Tom Avatar asked Oct 19 '09 11:10

Tom


4 Answers

$form->addElement('select','foo',
array(
        'label'        => 'ComboBox (select)',
        'value'        => 'blue',
        'multiOptions' => array(
            'red'    => 'Rouge',
            'blue'   => 'Bleu',
            'white'  => 'Blanc',
        ),
    )
);

As above, you can use 'value' => 'blue' for making 'blue' => 'Bleu' selected.

I hope this will help you..

like image 24
Tony Avatar answered Nov 10 '22 06:11

Tony


I've just worked out how to do it.

You have to use the setValue() method of the element:

$user = $form->createElement('select','user')->setLabel('User: ')->setRequired(true);
    foreach($users as $u)
        $user->addMultiOption($u->id,$u->firstname.' '.$u->lastname);

$user->setValue($selected); //$selected is the 'value' of the <option> that you want to apply selected="selected" to.
like image 95
Tom Avatar answered Nov 10 '22 05:11

Tom


In Zend Framework 2 set the 'value' attribue. For example to default the Select to 'Yes':

    $this->add( array(
        'name'     => 'isFlexible',
        'type'     => 'Select',
        'options'  => array(
             'label'            => 'Is it flexible?'
            ,'label_attributes' => array( 'placement' => 'APPEND')
            ,'value_options'    => array(
                    ''  => 'Select Below',
                    '0' => 'No',
                    '1' => 'Yes',
                    '2' => 'N/A',
            ),
        ),
        'attributes' => array(
            'id'     => 'is_flexible',
            'value'  => 1,
        ),
    ));
like image 7
Onshop Avatar answered Nov 10 '22 06:11

Onshop


i think this should work:

$form->setDefault('user', 'value'); // Set default value for element
like image 1
opHASnoNAME Avatar answered Nov 10 '22 04:11

opHASnoNAME