CodeIgniter Forums
Combination of form_dropdown() and set_select() possible? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: Best Practices (https://forum.codeigniter.com/forumdisplay.php?fid=12)
+--- Thread: Combination of form_dropdown() and set_select() possible? (/showthread.php?tid=65205)



Combination of form_dropdown() and set_select() possible? - Wouter60 - 05-14-2016

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?


RE: Combination of form_dropdown() and set_select() possible? - InsiteFX - 05-14-2016

form_helper set_value


RE: Combination of form_dropdown() and set_select() possible? - Wouter60 - 05-14-2016

(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.


RE: Combination of form_dropdown() and set_select() possible? - Wouter60 - 05-16-2016

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".