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

Tom picture Tom · Oct 19, 2009 · Viewed 75.8k times · Source

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

Answer

Tom picture Tom · Oct 19, 2009

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.