views:

5389

answers:

3

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'.

A: 

Hi,

i think this should work:

$form->setDefault('user', 'value'); // Set default value for element
ArneRie
That doesn't seem to work. I have set 'value' to the corresponding value of the <option> that i want to apply selected="selected" to but it does not get set to the selected state.
Tom
`setDefault()` is a form method. Tom's solution, `setValue()`, is an element method. It just depends which object you're working with when setting the value.
Sonny
+7  A: 

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.
Tom
thx. saved me some time.
easement
+1  A: 

$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..

Tony