首页 > 解决方案 > 在创建表单之前添加选项以选择 EntityType 字段的标签

问题描述

我有一个包含两个 EntityType 字段的表单,第一个是类别,第二个是子类别,类别字段将包含我在数据库中拥有的所有类别,但我想再添加一个,即“所有类别” ,我希望它是默认选择的,我该如何实现这一点..

$builder
            ->add(
                'category',
                EntityType::class,
                [
                    'label' => 'Catégorie',
                    'class' => Category::class,
                    'choice_label' => 'title',
                    'mapped' => false
                ]
            )

            ->add(
                'subCategory',
                EntityType::class,
                [
                    'label' => 'Sous-catégorie',
                    'class' => SubCategory::class,
                    'choice_label' => 'title',
                    'mapped' => false
                ]
            );

标签: phpformssymfony

解决方案


您可以手动构建您的选择数组并使用ChoiceType,例如:

// retrieve list of your categories in your controller or somewhere else
// and pass it using the options. Add it also before the default option "All categories".
$categories = $options['categories'];

$builder->add('category', ChoiceType::class, [
    'choices' => $categories,
    ...

推荐阅读