2
votes

I'm trying to get the option item selected in a form select element using Codeigniter

model

function get_sections_provider($provider)
{
    $this->db->select('*');
    $this->db->from('providers');
    $this->db->where('providers.id', $provider);
    $this->db->join('sections', 'sections.id = providers.section_id');
    $query = $this->db->get();
    return $query->result();
}

function get_all_sections_element()
{
    $query = $this->db->get('sections');
    return $query->result();
}

controller

public function edit($id)
{
    $data['element'] = $this->admin_model_providers->get_element_provider($id);
    $data['element']->sections = $this->admin_model_providers->get_sections_provider($id);
    $data['element']->sections_all = $this->admin_model_providers->get_all_sections_element();
    $data['title'] = '';
    $this->load->view('admin/admin_provider_edit', $data);
}

view

<?
foreach($element->sections as $key => $row){
    $selected[$key] = $row->id;
}?>
<select name="sections" class="chosen-select" id="" data-placeholder="" multiple>                           
    <?
    foreach($element->sections_all as $key => $value){?>
        <option value="<?=$value->id?>" <?=(in_array($value->id, $selected) ) ? "selected = 'selected'" : "" ;?> ><?=$value->title;?></option>
    <?}
    ?>
</select>

The result is the last id Sorry, I can not describe in detail the problem because my English is bad

3
Can you please show us the array structure you are getting within $element - Narendrasingh Sisodia
I updated the question - Alexandex Grigorean
Are you getting an array within $data['element']->sections or single value. - Narendrasingh Sisodia
If I do so foreach($element->sections as $key => $row){ echo $row->id; } there are multiple - Alexandex Grigorean
So are you using $data['element']->sections at multiple places within page or its been used just for select option if its been used for one select than please consider that you will receive only particular id from query - Narendrasingh Sisodia

3 Answers

2
votes

Try It:

<?php
  $array = null ; // $array[''] = 'Select'; // Use of need Default like Select 
  $select_value='';
   foreach ($element->sections as $value) {
     $array[$value->id] = $value->name;
   }
  echo form_dropdown('name', $array, $select_value, $style);
?>                 
1
votes

This will may help you try this code if it works for you..

foreach($element->sections_all as $key => $value){
    <option value="<?php echo $value['id'];>" <?php echo (in_array($value['id']),$element['sections'][$key]['id']) ? "selected = 'selected'" : "" ;?>><?php echo $value['title'];?></option>
}
0
votes

$selected is an array. If you want to compare one of its elements in a foreach, try:

 foreach($element->sections as $key => $row){
    $selected[$key] = $row->id;
}

Foreach where comparison occurs:

foreach ($element->sections_all as $k => $section) {
    if ($section->id == $selected[$k]){
    //etc...