Reputation: 2540
I've got a complicated re-population system that works, but it's cumbersome.
I've got a dropdown menu for a country of birth, and when the users submit the form it gets thrown in a database. The dropdown menu then gets repopulated with whatever is in the database if there is something.
I get the value from the database like this:
$birthplacecountry = (!set_select('birthplacecountry') && $birth_citizenship) ? $birth_citizenship[0]['birthplacecountry'] : (set_select('birthplacecountry') ? set_select('birthplacecountry') : '');
That works fine, as I've then got my options looking like this:
<option value="Afganistan" <?php if ($birthplacecountry == 'Afganistan') echo 'selected="selected"';?>>Afghanistan</option>
<option value="Albania" <?php if ($birthplacecountry == 'Albania') echo 'selected="selected"';?>>Albania</option>
<option value="Algeria" <?php if ($birthplacecountry == 'Algeria') echo 'selected="selected"';?>>Algeria</option>
<option value="American Samoa" <?php if ($birthplacecountry == 'American Samoa') echo 'selected="selected"';?>>American Samoa</option>
However, it's annoying having to compare $birthplacecountry to the name of the value manually. Is there a general way to compare something to the options value?
Some sort of functionality that works like: if ($birthplacecountry == this.option.value)
Upvotes: 0
Views: 648
Reputation: 146269
In codeIgniter, you should use Form helper to produce a select/dropdown, i.e.
$options = array(
'Afganistan' => 'Afganistan',
'Albania' => 'Albania',
);
echo form_dropdown('birthplacecountry', $options, 'Albania');
In this example, a dropdown
with name birthplacecountry
will be created and selected option
will be Albania
, the seconf one. The third parameter sets the selected option
, so, when you want to repopulate the form with selected option, you can do something like this
echo form_dropdown('birthplacecountry', $options, set_select('birthplacecountry', $this->input->post('birthplacecountry') );
Upvotes: 1