Zend Framework - Set 'selected' value in select box dropdown list
76,640
Solution 1
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.
Solution 2
$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..
Solution 3
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,
),
));
Solution 4
i think this should work:
$form->setDefault('user', 'value'); // Set default value for element
Author by
GFaz23
Updated on July 09, 2022Comments
-
GFaz23 almost 2 years
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'.