我有一个包含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
。
答案 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)
参考下面的代码 -
<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>