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

check_field checked vs unchecked

Is there a way to output a variable in a check_field? I'd like to use one line of code to display a checkbox, and have it be checked or unchecked as determined by a variable:

{% set chk = value == 1 ? 'checked' : '' %}
{{ check_field('name', 'value':1, chk) }}

Right now, this doesn't work, so I end up doing it this way:

{% if value == 1 %}
    {{ check_field('name', 'value':1, 'checked':'checked' }}
{% else %}
    {{ check_field('name', 'value':1 }}
{% endif %

Not a huge deal, but it's twice as many lines of code.

Thanks.



10.9k
edited May '15

Hi,

Maybe not quite the amount of grace you want but you can do:

    {% set value = 0 %}

    {{ value == 1 ? check_field('name', 'value':1, 'checked':'checked') : check_field('name', 'value':1) }}

Otherwise you'll have to make your own method I think. I don't see a way around it.

edited Jun '15

This is a bit late, but I figured I'd post in case someone else encounters this thread. This still isn't excelent, but its cleaner.

check_field('name', 'value':1, value == 1 ? 'checked' : '')
edited Aug '17

Does it work? I tried, but 'check' attribute does not appear. :(

This is a bit late, but I figured I'd post in case someone else encounters this thread. This still isn't excelent, but its cleaner.

check_field('name', 'value':1, value == 1 ? 'checked' : '')