We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Opt Group

Hi,

I was wondering if it's actually possible to handle opt groups within a volt select form, or if I'd be required to create a select field through the backend and configure it to my liking.

Would be quite useful for my project.

Thanks in advance.



13.8k

Can you write down the output (html) that you desire to generate?



3.7k
edited Jul '18

<select> <optgroup label="Swedish Cars"> <option value="volvo">Volvo</option> <option value="saab">Saab</option> </optgroup> <optgroup label="German Cars"> <option value="mercedes">Mercedes</option> <option value="audi">Audi</option> </optgroup> </select>

something similar to that would be nice.

Can you write down the output (html) that you desire to generate?



3.7k

I was ideally looking for something that could be done more directly through volt rather than back-end, but if that's what needs to be done for the intended result to work, then I guess I can settle with that.

This doesnt work for you: https://forum.phalcon.io/discussion/3316/optgroup-in-forms-element-select ?



13.8k
Accepted
answer
edited Jul '18

If you pass all the information to the view you could also do it in volt. I dont think its an easier approach though.

Are you generating all fields manually? If you pass it as an array/object you can loop through it in volt en just build the selectbox completly from the ground up. You would still get the correct post/get values from the form.

What kind of approach are you using all together? I take it you are not working with models/form objects then?

To build the selectbox manually in volt it could look similar to this.

<select>
{% for optgroup in yourPassedObject %}
    <optgroup label="{{ optgroup.name }}">
        {% for option in optgroup.options %}
            <option value="{{ option.name }}">{{ ucfirst(option.name) }}</option> # to use ucfirst, see below
        {% endfor %}
    </optgroup>
{% endfor %}
</select>

# in your service definition for the view add after; $volt = new VoltEngine($view, $this);
$compiler = $volt->getCompiler();
$compiler->addFunction('ucfirst', 'ucfirst');