talhaamir
talhaamir

Reputation: 129

Customize symfony form if the form fields are added through a loop

I am creating a form like this:

foreach ($users as $user) {
    $builder->add('user_' . $user->getId(), NumberType::class, [
       'label' => $user->__toString(),
       'required' => false,
       'mapped' => false,
       'constraints' => [...],
    ]);
}

In twig I want to display the form in a table:

<tbody>
    {% for user in users %}
    {% set userId = 'user_' ~ user.getID() %}
        <tr>
            <td>{{ form_label(form.userId) }}</td>
            <td>
                {{ form_widget(form.userId) }}
            </td>
        </tr>
    {% endfor %}
 </tbody>

but I get error:

Neither the property "userId" nor one of the methods "userId()", "getuserId()"/"isuserId()" or "__call()" exist and have public access in class "Symfony\Component\Form\FormView".

How can I go about to solve this problem ?

Upvotes: 1

Views: 623

Answers (2)

Theva
Theva

Reputation: 948

just loop the form in twig should be ok .

I think this might help you (but not tested)

<tbody>
{% for user in form %}
    <tr>
        <td>{{ form_label(user) }}</td>
        <td>{{ form_widget(user) }}</td>
    </tr>
{% endfor %}

Upvotes: 1

talhaamir
talhaamir

Reputation: 129

I used attribute function to solve my problem:

<tbody>
    {% for user in users %}
    {% set userId = 'user_' ~ user.getID() %}
        <tr>
            <td>{{ form_label(attribute(form, (userId) )) }}</td>
            <td>
                {{ form_widget(attribute(form, (userId) )) }}
            </td>
        </tr>
    {% endfor %}
</tbody>

Upvotes: 2

Related Questions