Twig Setting Select Option on a dropdown
28,616
May be you can try something like this:
Replace supervisor
variable name by oneSupervisor
in the loop and test oneSupervisor
with user.supervisor
.
<select class="form-control" id="supervisor">
{% for oneSupervisor in supervisor %}
{% set selected = '' %}
{% if (oneSupervisor.fname ~ ' ' ~ oneSupervisor.lname) == user.supervisor %}
{% set selected = 'selected' %}
{% endif %}
<option value="{{oneSupervisor.fname}} {{oneSupervisor.lname}}" {{ selected }}>{{oneSupervisor.fname}} {{oneSupervisor.lname}}</option>
{% endfor %}
</select>
Author by
darkdelusions
Updated on July 09, 2022Comments
-
darkdelusions almost 2 years
I am currently writing a php mvc from scratch and using twig as my template engine and need some assistance setting the selected option on a drop down list. Currently in my model I have an sql query that pull all list of supervisors and drops them in my drop down list using the twig for loop but I need to some how select a user’s supervisor if it matches up.
I apologize now as I am new to twig
View:
<select class="form-control" id="supervisor"> {% for supervisor in supervisor %} <option value="{{supervisor.fname}} {{supervisor.lname}}" >{{supervisor.fname}} {{supervisor.lname}}</option> {% endfor %} </select>
Tried:
<select class="form-control" id="supervisor"> {% for supervisor in supervisor %} {% if {{supervisor.fname}} {{supervisor.lname}} == {{ user.supervisor }} %} <option value=”{{supervisor.fname}} {{supervisor.lname}}” selected>{{supervisor.fname}} {{supervisor.lname}}</option> {% else %} <option value=”{{supervisor.fname}} {{supervisor.lname}}”>{{supervisor.fname}} {{supervisor.lname}}</option> {% endif %} {% endfor %} </select>
-
darkdelusions about 7 yearsThis is still not setting the select value but I am pretty sure I know why... the table the query is pulling from has a first and last name column and the oneSupervisor var that is being set is not returning the name frist and last name. i attempted to set a var of supervisr like {% set moose = 'oneSupervisor.fname oneSupervisor.lname' %} an using that in the if statement but it still not setting selected
-
doydoy44 about 7 yearsWhat do you have in
supervisor
and inuser.supervisor
? -
darkdelusions about 7 yearsUser.supervisor returns it as one string Bob Smith onesupervisor is an array (fname Bob lname Smith) of it would be easier I could create a new table that just houses all the supervisors
-
doydoy44 about 7 years@darkdelusions: I change my if test with concatenation
-
darkdelusions about 7 yearsThank you @doydoy44 that corrected the issue I didn't even think about concatenating the the 2 together.
-
doydoy44 about 7 years@darkdelusions: You're welcome and thank's for your return :)