如何在表单生成器 symfony2 中使用数组作为 "choice" 的选择

How to use an array as choices for "choice" in form builder symfony2

嗨,我是 symfony2 的新手。我很难弄清楚如何处理我的 select 框。我需要使用数据库中的 "positions" 数组,并将其用作 select 框的选项。由于这个项目即将到期,我非常感谢你们的帮助。

Atm 我的表单设置有以下代码:

        $role = $query1->getResult(Query::HYDRATE_ARRAY);

        $roles = array();
        for($i = 0; $i <count($roles); $i++){
            $roles[] = $role[$i]['disrole'];
        }

        $form = $this->createFormBuilder($position)
            ->add('position', 'choice', array('choices'  => $roles))
            ->add('save', 'submit', array('label' => 'Search'))->setMethod('POST')
            ->getForm();

这是我在我的树枝模板中使用它的方式:

<div class="panel-body">
   {{ form(form) }}
</div>

我只是这样输出我的表格,因为我不太熟悉拼接表格部分。我真的很感谢你们的回答!提前致谢!

要在表单中使用选项,我会使用以下可能性:

/**
 * @param FormBuilderInterface $builder
 * @param array                $options
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('stuff', 'choice', ['choices' => $this->getChoices()]);
}


private function getChoices()
{
    $contents = $this->someRepoInjectedInForm->findChoices();

    $result = [];
    foreach ($contents as $content) {
        $result[$content->getId()] = $content->getLabel();
    }

    return $result;
}

您的选择标签将是数组值,通过表单发送到您的后端的值将是您数组中相应键值对的键。

您可以使用 entity field 而不是选择字段,这是一个旨在从 Doctrine 加载其选项的选择字段:

$form->add(
    'position',
    'entity',
    [
        'class' => 'YourBundle:Role',
        'query_builder' => function (RoleRepository $repository) {
            $queryBuilder = $repository->createQueryBuilder('role');
            // create your query here, or get it from your repository
            return $queryBuilder;
        },
        'choice_label' => 'disrole'
    ]
);