Welcome Guest, Not a member yet? Register   Sign In
Combination of form_dropdown() and set_select() possible?
#1

I'm trying to build a form with two dropdown lists. Both lists have the same source (populated by a database query). The user must select two different values. If they are the same, form validation must display an error message.
I load the form helper and the form_validation library.
On open, the form must display a default value in both dropdown lists. If the user makes the wrong selection, the form must be shown again, with the error message, and the faulty selection in the dropdowns.

In my controller I have this code:
PHP Code:
$cities = array(
 
 0 => '-- select a city --',
 
 1 => 'New York',
 
 2 => 'Dallas',
 
 3 => 'Washington DC'
);

$mycity 2;

$data['fields'] = array(
 
  'city' => array(
 
    'name' => 'city',
 
    'options' => $cities,
 
    'selected' => set_select('cities',$mycity,0)
 
  )
);
$this->load->view('select_city',$data); 

In my view:
PHP Code:
echo form_dropdown($fields['city']); 

Problem: the default choice ('Dallas') does not appear at all. The dropdown itself does contain the list of cities, but none is selected.
How can I do this the right way?
Reply
#2

form_helper set_value
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply
#3

(This post was last modified: 05-14-2016, 02:04 PM by Wouter60.)

(05-14-2016, 01:46 PM)InsiteFX Wrote: form_helper set_value

Right, these two terms are in my question. I'm looking for a solution.
As a workaround, I created my own helper function that does this:

PHP Code:
function make_options_list($field,$list,$value)
{
    
$rw = array();
    foreach( 
$list as $key=>$item) {
        
$rw[] = '<option value="' $key '" ' set_select($field,$key$key == $value) . '>' $item '</option>';
    }        
    return 
implode("\n",$rw);

The output is a string with all options.

In my view, I do this:
PHP Code:
<select name="city">
<?= 
$fields['cities']['options'];?>
</select> 

This does work, but without the form_dropdown() helper function.
Reply
#4

I've found a solution by making my own form_dropdown() function in MY_Form_helper.php.
PHP Code:
form_dropdown([$name ''[, $options = array()[, $selected = array()[, $extra ''[,$unselectable = array()]]]]]) 

The $unselectable array contains the options that are marked as "disabled". I avoided $disabled here, because the disabled attribute must be available for marking the entire dropdown-list as "disabled".
Reply




Theme © iAndrew 2016 - Forum software by © MyBB