ferdinandfly
ferdinandfly

Reputation: 371

Symfony2 verify a form checkbox is checked in twig template

I have a problem of verify a check box in twig template. In twig, i wanna to do this:

{% for activity in form.activity %}
    {% if (activity.isChecked) %}
    <div>
        {{ form_widget(activity) }}
        {{ form_label(activity) }}
    </div>
    {% endif  %}
{% endfor %}

The activity is a entity field in form builder:

->add('activity', 'entity', array(
            'class'         => 'AcmeProspectionBundle:Activity',        
            'expanded'      => true,
            'multiple'      => true,
            'property'      => 'name',
/*
            'query_builder' => function(EntityRepository $er) use($options) {
                return $er->createQueryBuilder('ac')
                ->leftJoin('ac.company','c')
                ->where('c = :id')
                ->orderBy('ac.name', 'ASC')
                ->setParameter('id', $options['company_id']);
            }
*/
))

In fact, if I do not comment the query_builder part, it will only generate the checked part, but if I do this Symfony will check the integrity of the original array and the submit array. I can not add any new activity. In fact I generate the choice by javascript like this:

 <div class="activity_checkbox" data-prototype='<div>
 <input type="checkbox" checked="checked" value="100" placeholder="" name="acme_prospection_company[activity][]">
 <label></label></div>'>

Cause I have more than 3000 choice and I can not use the original checkbox or select to let user do that. So now all the work is done, only need to render the checked activities. And I do not know how.

Upvotes: 4

Views: 12662

Answers (3)

tlarson
tlarson

Reputation: 473

This is a very late response, but others may be having this problem and this is the only entry I see relative to boolean data in forms in collections. This worked for me in Symfony 4 using a boolean property called "isRole" of "organization" which is an element of an collection. The form type used is CollectionType (not EntityType). However, I think it should work in both cases:

{% for organization in form.organizations %}
   {% if (organization.isRole.vars.data) %}
       ...
   {% endif %}
{% endfor %}

No need to use == since the data result is already a boolean result.

Upvotes: 0

Alain
Alain

Reputation: 36954

For a checkbox, you should use:

{% if form.activity.vars.data %}

Upvotes: 5

Marc Juchli
Marc Juchli

Reputation: 2278

To access a value within your form object(s) the general solution is:

{{ form.vars.value.NAME }}

Using the dump method you can output all available form objects:

{{ dump(form.vars.value) }}

It's also documented in the book: http://symfony.com/doc/current/book/forms.html

Upvotes: 0

Related Questions