从数据库中预先选择的选项值

时间:2016-09-28 06:49:03

标签: php html codeigniter html-select

我有一个包含select option输入的编辑表单,我想根据条件选择默认选项。这是:

<select class="form-control locationid" id="locationid" name="locationid" required>
   <option value="" disabled selected> Select branch</option>
   <option data-id="0" value="0">NONE</option>
        <?php foreach ($vendor as $v) { ?>
   <option data-id="<?php echo $v['location_id']; ?>" value="<?php echo $v['location_id']?>" ><?php echo $v['name'] ;?></option>
        <?php };?> 
</select>

我的控制器:

$this->db->select("d.user_id as id, d.plate_number as plate_number, d.current_lat as lat, d.current_lon as lon, d.created_on as created_on, d.updated_on as updated_on, d.available as available, d.location_id as location_id, u.user_name as name, u.user_email as email, u.user_phone as phone, v.name as location_name");
        $this->db->from('user_driver as d');
        $this->db->join('user as u', 'd.user_id = u.user_id','left');
        $this->db->join('vendor_location as v', 'd.location_id = v.location_id','left');
        $query = $this->db->get();
        $data['driver'] = $query->result_array();

        $this->db->select("location_id, name");
        $this->db->from('vendor_location');
        $query2 = $this->db->get();
        $data['vendor'] = $query2->result_array();

user_driver表包含与location_id表中location_id列相关的vendor_location列。如何使select option显示来自location_id表的现有user_driver以及来自vendor_location表的选项?目前,上面的代码仅显示已禁用的选项Select branch

2 个答案:

答案 0 :(得分:1)

您可以使用in_array()获取所选内容,但是location_id来自$data['driver']的商店位于一个单独的数组中:

<?php
// in your view file
$location = array();
foreach ($driver as $value) { // getting from $data['driver']
  $location[] = $value['location_id']; // store all location_id in an array
}
?>

<option>内使用in_array(),如:

<?=(in_array($v['location_id'], $location) ? 'selected=""' : '')?>

示例:

<select class="form-control locationid" id="locationid" name="locationid" required>
  <option value="" disabled selected> Select branch</option>
  <option data-id="0" value="0">NONE</option>
  <?php foreach ($vendor as $v) { ?>
    <option <?=(in_array($v['location_id'], $location) ? 'selected=""' : '')?> data-id="<?php echo $v['location_id']; ?>" value="<?php echo $v['location_id']?>" ><?php echo $v['name'] ;?></option>
  <?php };?> 
</select>

答案 1 :(得分:1)

  • 首先从“选择分支”选项中删除所选属性
  • 您可以将所有location_ids存储在一个数组变量中(例如$ locations_ids)。
  • 在foreach中使用in_array,我们可以检查位置是否存在。

参考下面的代码 -

<select class="form-control locationid" id="locationid" name="locationid" required>
   <option value="" disabled > Select branch</option>
   <option data-id="0" value="0">NONE</option>
        <?php foreach ($vendor as $v) { ?>
   
   <option data-id="<?php echo $v['location_id']; ?>" value="<?php echo $v['location_id']?>" <?php echo in_array($v['location_id'], $locations_ids) ? 'selected' : ''; ><?php echo $v['name'] ;?></option>
    
        <?php };?> 
</select>