将数据数组传递给表单

时间:2019-11-08 18:53:29

标签: symfony

我正在使用symfony,我需要传递两个数组,以便可以选择列表。

现在在表单生成器中我有这个:

    ->add('city', EntityType::class, [
        'label' => 'Select city',
        'class' => Cities::class,
        'choice_label' => 'title',
        'choice_value' => 'title'
    ])

它把列表中的所有cities丢给了我。我想过滤它们。我已经在控制器上进行了如下过滤:

    $capitals = $cityRepository->findBy(['cityType' => CityType::capital()->id()]);
    $villages = $cityRepository->findBy(['villageType' => CityType::village()->id()]);

这将返回两个数组:capitalsvillages

如何将它们传递给表单?

2 个答案:

答案 0 :(得分:-1)

在您的控制器中:

$form=$this->createForm(YourFormType::class, $yourEntity, array(
    'capitals'=>$capitals,
    'villages'=>$villages
));

以您的形式:

public function buildForm(FormBuilderInterface $builder, array $options) {
    /** @var array $capitals */
    $capitals=$options['capitals'];
    /** @var array $villages */
    $villages=$options['villages'];

    $builder->add('city', EntityType::class, array(...)
            ->add('vallacap', ChoiceType::class, array(
                'mapped'=>false, //Make sure it's not mapped to any entity
                'choices'=>array(
                    'Capitals'=>$capitals,
                    'Villages'=>$villages
                ),
                'required'=>false,
            ));
}

public function configureOptions(OptionsResolver $resolver) {
    $resolver->setDefaults(array(
        'data_class'=>Personnalisation::class,
        'capitals'=>null, // Set default to null in case argument is not passed
        'villages'=>null,
    ));
}

答案 1 :(得分:-1)

您需要将数组传递给choices选项。

https://symfony.com/doc/current/reference/forms/types/entity.html#using-choices

    ->add('city', EntityType::class, [
        'label' => 'Select city',
        'class' => Cities::class,
        'choice_label' => 'title',
        'choice_value' => 'title',
        'choices' => $choices // ------------> This line
    ])

$choices = array_merge($capitals, $villages);