Alexandex Grigorean
Alexandex Grigorean

Reputation: 39

Option selected in codeigniter

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

Upvotes: 2

Views: 15640

Answers (3)

Eng Acs
Eng Acs

Reputation: 66

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);
?>                 

Upvotes: 2

Narendrasingh Sisodia
Narendrasingh Sisodia

Reputation: 21437

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>
}

Upvotes: 1

Mudshark
Mudshark

Reputation: 3253

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

Upvotes: 0

Related Questions