我在Symfony 4的Controller中使用Formbuilder:
$form = $this->createFormBuilder($item)
->add('id', TextType::class, array('attr' => array('class' => 'form-control')))
->add('username', TextType::class, array('attr' => array('class' => 'form-control')))
->add('email', TextType::class, array('attr' => array('class' => 'form-control')))
->add('is_active', TextType::class, array('attr' => array('class' => 'form-control')))
->add('password', TextType::class, array('attr' => array('class' => 'form-control')))
我手动创建了那些在我的实体中的字段。我现在想做的是通过循环自动创建此字段。这就是我的方法:
$form = $this->createFormBuilder($item)
foreach ($item as $field) {
->add($field, TextType::class, array('attr' => array('class' => 'form-control')))
}
但是我收到错误消息:
语法错误,意外的“ foreach”(T_FOREACH)
答案 0 :(得分:1)
您不能以这种方式链接方法,因为您在semicolon
之前错过了foreach
。
首先,您需要使用以下命令定义formBuilder
实例:
$form = $this->createFormBuilder($item); // (assuming `$item` is defined).
然后,您可以在foreach
循环中填充它:
$fields = array("id", "username", "email", "is_active", "password");
foreach ($fields as $field) {
$form->add($field, TextType::class, array('attr' => array('class' => 'form-control')));
}
然后,您的$form
将包含所有填充的字段。