在codeigniter中选择的选项

时间:2015-03-23 10:22:00

标签: php codeigniter

我正在尝试使用Codeigniter

在表单选择元素中选择选项

模型

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();
}

控制器

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

视图

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

结果是最后一个id 对不起,我无法详细描述问题因为我的英语不好

3 个答案:

答案 0 :(得分:1)

这可能会帮助您尝试使用此代码,如果它适合您..

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

答案 1 :(得分:1)

尝试:

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

答案 2 :(得分:0)

$selected是一个数组。如果您想比较foreach中的一个元素,请尝试:

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

比较发生的前景:

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