在 Twig 和 Symfony 中多次渲染一个字段

Render a field multiple times in Twig and Symfony

我需要两个输入以便用户可以选择

控制器

$etud = new Etudiant();
$form=$this->createFormBuilder($etud)
    ->add('filierechoisit',EntityType::class,array('class'=>'inscriptionBundle\Entity\filieres', 'choice_label'=>'libelle_filiere'))
    ->add('filierechoisit',EntityType::class,array('class'=>'inscriptionBundle\Entity\filieres', 'choice_label'=>'libelle_filiere'))->getForm();
if ($form->isValid()) {
    // ... maybe do some form processing, like saving the Task and Tag objects
}

return $this->render('inscriptionBundle:Default:authentification.html.twig', array(
    'modif' => $form->createView(),
));

我该怎么做?

我几乎可以肯定您想要一个 ChoiceType/EntityType field with multiple and expanded 选项作为 true。 它应该是这样的:

$form->add('filierechoisit', EntityType::class, array(
    # query choices from this entity
    'class' => 'inscriptionBundle\Entity\filieres',
    # use the filieres.libelle_filiere property as the visible option string
    'choice_label' => 'libelle_filiere',
    # used to render a select box, check boxes or radios
    'multiple' => true,
    'expanded' => true,
));

您正在混合处理表单和呈现表单。如果您希望用户选择他输入数据的方式 - 您不希望以两种不同的方式处理此数据,直到它们成为两个独立的字段。

你应该只有一个

->add('filierechoisit',EntityType::class,array('class'=>'inscriptionBundle\Entity\filieres', 'choice_label'=>'libelle_filiere'))

调用添加字段处理并将所有渲染留给前端。您可以在那里使用一些 JS 或 API,或者在简单的情况下,只需覆盖该字段的 Twig 模板

http://symfony.com/doc/current/cookbook/form/form_customization.html

您可以在此处为您的表单呈现您自己的小部件,允许用户执行一些 html 操作来更改输入。

目前,调用两个具有相同名称的 add 只会让第二个覆盖第一个。