CodeIgniter Forums
set_value, set_select for form_multiselect in v2 - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: set_value, set_select for form_multiselect in v2 (/showthread.php?tid=40555)



set_value, set_select for form_multiselect in v2 - El Forum - 04-12-2011

[eluser]Brad K Morse[/eluser]
Using version 2

Unable to retain the items selected by the user within a form_multiselect when the form is redisplayed after the user did not complete the entire form

Code:
// controller
$this->form_validation->set_rules('goal_id[]', 'Goal', 'required'); // rule
$form_view['goals'] = $this->add_model->getGoals(); // getting goals
$this->load->view('add-assessment/form-view', $form_view);

// model
function getGoals() {
$this->db->cache_on();
$q = $this->db->order_by('id', 'asc')->get('goal');
    
if($q->num_rows() > 0) {
   foreach($q->result() as $row) {
    $data[$row->id] = $row->title;
   }
   return $data;
  }
}

// view
<?=form_label('Goals')?>
<?=form_error('goal_id[]')?>
<?=form_multiselect('goal_id[]', $goals, set_select('goal_id[]'))?>

It does not retain any items selected by the user when using set_select, but it retains one item if you use set_value


set_value, set_select for form_multiselect in v2 - El Forum - 04-12-2011

[eluser]zac[/eluser]
According to the user guide, set_select() is intended to be used when you're generating the select HTML by hand, like this:

Code:
<select name="myselect">
<option value="one" &lt;?php echo set_select('myselect', 'one', TRUE); ?&gt; >One</option>
<option value="two" &lt;?php echo set_select('myselect', 'two'); ?&gt; >Two</option>
<option value="three" &lt;?php echo set_select('myselect', 'three'); ?&gt; >Three</option>
</select>

Instead, form_multiselect() wants an array of values as its third parameter. The $_POST array will contain whatever values the user selected:

Code:
&lt;?=form_multiselect('goal_id[]', $goals, $_POST['goal_id[]'])?&gt;

Or if you're using CI's Input class, then something like this:

Code:
&lt;?=form_multiselect('goal_id[]', $goals, $this->input->post('goal_id[]'))?&gt;