Tom Tom - 1 year ago 100
PHP Question

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

Tom Tom
Answer Source

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.