Reputation: 755
I have an edit form which contains select option
input, I want to select the default option based on condition. Here it is :
<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>
My controller :
$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();
the user_driver
table contains location_id
column related to location_id
column in vendor_location
table. How can I make the select option
showing the existing location_id
from user_driver
table as well as options from vendor_location
table? For now, the code above only show the disabled option Select branch
.
Upvotes: 0
Views: 648
Reputation: 2151
Refer code below -
<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>
Upvotes: 1
Reputation: 16117
You can use in_array()
for getting selected options, but for this store location_id
from $data['driver']
in a separate array:
<?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
}
?>
Than use in_array()
inside the <option>
as like:
<?=(in_array($v['location_id'], $location) ? 'selected=""' : '')?>
Example:
<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>
Upvotes: 1