如果通过循环添加表单字段,则自定义 symfony 表单
Customize symfony form if the form fields are added through a loop
我正在创建这样的表单:
foreach ($users as $user) {
$builder->add('user_' . $user->getId(), NumberType::class, [
'label' => $user->__toString(),
'required' => false,
'mapped' => false,
'constraints' => [...],
]);
}
在 twig 中,我想以 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>
但我收到错误:
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".
我该如何着手解决这个问题?
我使用了attribute函数来解决我的问题:
<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>
只需在树枝中循环表单就可以了。
我认为这可能对您有所帮助(但未经测试)
<tbody>
{% for user in form %}
<tr>
<td>{{ form_label(user) }}</td>
<td>{{ form_widget(user) }}</td>
</tr>
{% endfor %}
我正在创建这样的表单:
foreach ($users as $user) {
$builder->add('user_' . $user->getId(), NumberType::class, [
'label' => $user->__toString(),
'required' => false,
'mapped' => false,
'constraints' => [...],
]);
}
在 twig 中,我想以 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>
但我收到错误:
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".
我该如何着手解决这个问题?
我使用了attribute函数来解决我的问题:
<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>
只需在树枝中循环表单就可以了。
我认为这可能对您有所帮助(但未经测试)
<tbody>
{% for user in form %}
<tr>
<td>{{ form_label(user) }}</td>
<td>{{ form_widget(user) }}</td>
</tr>
{% endfor %}