Reputation: 13
I have this simple code in my product_form.tpl php file of opencart 2.3:
<select name="type" id="type" class="form-control">
<?php if ($type) { ?>
<option value="1" selected="selected">Flower</option>
<option value="0">Plant</option>
<?php } else { ?>
<option value="1">Flower</option>
<option value="0" selected="selected">Plant</option>
<?php } ?>
</select>
Everything fine and simple, but i need at least 1 more option for this select to add:
<option value="2">Bouquet</option>
Could you please tell me how this should look like in case of 3 options... Thanks in advance!
Upvotes: 1
Views: 199
Reputation: 83
If you really want to go this way, then:
<select name="type" id="type" class="form-control">
<?php if ((int)$type === 0) { ?>
<option value="2">Bouquet</option>
<option value="1">Flower</option>
<option value="0" selected="selected">Plant</option>
<?php } elseif ((int)$type === 1) { ?>
<option value="2">Bouquet</option>
<option value="1" selected="selected">Flower</option>
<option value="0">Plant</option>
<?php } elseif ((int)$type === 2) { ?>
<option value="2" selected="selected">Bouquet</option>
<option value="1">Flower</option>
<option value="0">Plant</option>
<?php } ?>
</select>
But I would suggest using the way Jelmer Jellema suggested.
Upvotes: -1
Reputation: 1116
Sometimes it's easier to just write some structured code..
<?php
$options = array(
"1" => "flower",
"0" => "Plant",
"2" => "Bouquet",
"3" => "Rock"
);
$currentval = 2;
?>
<select name="type" id="type" class="form-control">
<?php
foreach($options as $val => $label):
?>
<option value="<?=$val;?>" <?=$currentval == $val ? 'selected' : ''?>><?=$label;?></option>
<?php
endforeach;
?>
Upvotes: 1
Reputation: 27082
You chose a bad approach as I wrote in comment under question.
<select name="type" id="type" class="form-control">
<option value="1" <?php echo isset($type) && $type == 1 ? 'selected' : '' ?>>Flower</option>
<option value="0" <?php echo isset($type) && $type == 0 ? 'selected' : '' ?>>Plant</option>
<option value="2" <?php echo isset($type) && $type == 2 ? 'selected' : '' ?>>Bouquet</option>
</select>
Another way is using array and write the dropdown using foreach loop.
isset($type)
can be taken above the code, you need to check if variable exists to prevent notice of undefined variable.
There can be something like
$type = isset($type) ? $type : NULL; // or any default value like 0
In options
then will be just <?php echo $type == 1 ? 'selected' : ''; ?>
.
Upvotes: 2
Reputation: 299
You can use a siwtch case block instead of bunch of if's you can check the documentation here https://www.w3schools.com/PhP/php_switch.asp and you can compare the value of $type more organized ! Good Luck !
Upvotes: -1