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'.
$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..
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.
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,
),
));
i think this should work:
$form->setDefault('user', 'value'); // Set default value for element
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With