fips123
fips123

Reputation: 281

Option selected with codeigniter and data from DB

I use codeigniter to create a dropdownlist with customers.
If I enter selected, than the last customer in the dropdown is automatically choosen.

Is it possible to select a customer inside that foreach?

My code snippet:

<?php foreach ($customers as $c): ?>
<option value="<?php echo $c->customer_id;?>"><?php echo $c->customer_name; ?></option>
<?php endforeach; ?>

Upvotes: 0

Views: 2524

Answers (4)

Ghanshyam Nakiya
Ghanshyam Nakiya

Reputation: 1712

Compare variable with attribute in option tag

 <?php  $chosenCustomer_id = 5;?>   
 <select name="customer"  required>
   <?php foreach ($customers as $c){?>

    <option <?=($chosenCustomer_id==$c['customer_id']?'selected="selected"':'')?> value="<?=$c['customer_id']?>"><?=$c['customer_name']?></option>

     <?php } 
    ?>

    </select> 

Upvotes: 0

Vishu238
Vishu238

Reputation: 673

Use selected attribute in Option Tag
Selected needs to be set based on condition

$selected=(condition): "selected",""; 
<option <?php echo $selected; ?>> Option Inner Html </option>

Upvotes: 0

Michael Kunst
Michael Kunst

Reputation: 2988

Yes it is. However you have to know which customer is chosen at the moment, and then inside the loop check if the chosen customer_id is the same as the current one:

<?php 
$chosenCustomer_id = 5; //of course don't hardcode it
foreach ($customers as $c): 
$selected = $c->customer_id == $chosenCustomer_id ? 'selected' : '';
?>
<option value="<?php echo $c->customer_id;?>" <?php echo $selected; ?>> <?php echo ><?php echo $c->customer_name; ?></option>
<?php endforeach; ?>

Upvotes: 1

Disha V.
Disha V.

Reputation: 1864

Just add ternary condition in <option> inside for loop where $selectedOption is your value to be selected.

<?php $selectedOption = "yourvalue";
foreach ($customers as $c): ?>
    <option value="<?php echo $c->customer_id;?>" <?= ($c->customer_id == $selectedOption ? "selected" : "")><?php echo $c->customer_name; ?></option>
<?php endforeach; ?>

Upvotes: 1

Related Questions