如何使用foreach循环从我的实体中提取数据以在formBuilder中使用它?

时间:2018-08-24 13:13:45

标签: forms symfony foreach controller

我在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)

1 个答案:

答案 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将包含所有填充的字段。