Search code examples
phphtmlphalcon

Based on a condition, how to make a dropdown list single select or multiselect?


I had a requirement where in an employee list dropdown given, if selectMultiple is set, the dropdown should allow multiple selects, and if selectMultiple is not set, it shouldn't.

<select name="employeeList[]" id="employeeList" class="form-
control" multiple="<?=$selectMultiple?>">
    <?php
    foreach($employeeList as $employee) {

        echo "<option value='" . $employee->$employeeId . "'>" . 
        $employee->employeeName . "</option>";

    }    
    ?>
</select>

It's a phtml file, and $selectMultiple is passed from a controller(as in Phalcon). I have tried something like passing, $selectMultiple ="multiple", so the code will look like

<select name="employeeList[]" id="employeeList" class="form-control" multiple="multiple">

and $selectMultiple="" for the single select case.

<select name="employeeList[]" id="employeeList" class="form-control" multiple="">

But the very presence of multiple attribute itself makes the dropdown list elligible for multiselect.

In short, in either cases, it triggers multiselect regardless of the condition. Please help.


Solution

  • You can simply write your code like

    You need to pass $selectMultiple = "multiple" or $selectMultiple = ''

    <select name="employeeList[]" id="employeeList" class="form-control" <? echo !empty($selectMultiple) ? $selectMultiple : '' ?>>
    <?php
    foreach($employeeList as $employee) {
    
        echo "<option value='" . $employee->$employeeId . "'>" . 
        $employee->employeeName . "</option>";
    
    }    
    ?>