Osny Netto
Osny Netto

Reputation: 572

Set a selected option in menu dropdown with codeigniter

I chose to use tag instead of form_dropdown() from Form Helper because i can't set a class atribute to <option> tag. So I have a <select> and want to set a item with as "selected". This data is coming from database. How I set this? I saw this: set_select() but I can't make work. Does anyone have a solution?

Upvotes: 1

Views: 18867

Answers (3)

Whole Hat
Whole Hat

Reputation: 21

<?php echo form_label('Gender:'); ?>
<?php echo form_dropdown(array('id'=>'selectinform', 'name'=>'gender', 'options'=>array('1'=>'Select', '2'=>'2','3'=>'3'), 'selected'=>'1')); ?>

'selected'=>'1'

Upvotes: -1

Ruben M&#252;ller
Ruben M&#252;ller

Reputation: 471

There are two things to keep in mind: First you have to use the validation class to be able to use the set_select() function. Second you have to pass the database information to that function, like this:

<select name="myselect">
  <option value="one" <?php echo set_select('myselect', 'one', ($model->selection == 'one')); ?> >One</option>
  <option value="two" <?php echo set_select('myselect', 'two', ($model->selection == 'two')); ?> >Two</option>
  <option value="three" <?php echo set_select('myselect', 'three', ($model->selection == 'three')); ?> >Three</option>
</select>

If $model->selection is two, then the second option will be selected in the example above.

Upvotes: 2

swatkins
swatkins

Reputation: 13630

From the docs on the form_dropdown function:

form_dropdown()

Lets you create a standard drop-down field. The first parameter will contain the name of the field, the second parameter will contain an associative array of options, and the third parameter will contain the value you wish to be selected.

echo form_dropdown('shirts', $options, 'large'); // 'large' will be "selected"

Upvotes: 4

Related Questions