pavelartlover
pavelartlover

Reputation: 202

How to make item selected in dropdown list

here is a piece of my php code, related to dropdown list creation:

$s_t = array(
"key1" => "value1",
"key2" => 'value2',
"key3" => 'value3');
$default_select = "value2";

$attr = array("id" => "name");
$form->addElement('select','name',"Choose your option:",$s_t, $attr);

How to make default selected item in the list, according to $default_select value?

(when user load the page, he will see that $default_select value has been already chosen in the dropdown list)

Upvotes: 0

Views: 67

Answers (4)

pavelartlover
pavelartlover

Reputation: 202

Here is my solution:

    $s_t = array(
    "key1" => "value1",
    "key2" => 'value2',
    "key3" => 'value3');
    $default_select = "value2";

    $attr = array("id" => "name");
    $element = $form->createElement('select','name',"Choose your option:",$s_t, $attr);
    $element->setValue($default_key);
    $form->addElement($element);

Upvotes: 0

doydoy44
doydoy44

Reputation: 5782

Seeing your code, I guess you're in a controller.
To create a select element, you should do this:

$s_t = array(
    "key1" => "value1",
    "key2" => 'value2',
    "key3" => 'value3');

$form->addElement('select','name');
$form->getElement('name')->setLabel('Choose your option:')
                         ->addMultiOptions($s_t);

Or with a single instruction:

$form->addElement('select','name', array('label'=>'Choose your option:', 
                                         'MultiOptions' => $s_t));

It's the same principle if you are in a class Form.

To put a default value, you must use the key, so if you only have a value, you can do this:

$default_select = "value2";
$form->getElement('name')->setValue(array_search($default_select, $s_t));

Hope it will help you.

Upvotes: 1

drozdo
drozdo

Reputation: 515

Easy use.

$form->setValue($default_select);

$default_select - must be option "key" not "value"

Upvotes: 0

I'm Geeker
I'm Geeker

Reputation: 4637

Use this

$default_select = "value2";
$form->setValue($default_select);

Upvotes: 0

Related Questions