Symfony - 表单上的数据参数错误

问题描述 投票:0回答:2

问题的背景:

我创建了一个 symfony 表单。

每个工具都有一组模块。

用户拥有任何工具的模块集合。

我想要什么:

我希望每个工具都有与该工具的模块相对应的复选框。用户拥有的模块复选框被选中。

([] = 复选框)

工具1:[]模块1 [x]模块2 [x]模块3

工具2:[]模块4 [x]模块5

工具3:[x]模块6 []模块7

我目前拥有的:

对于每个工具,都有与该工具的模块相对应的复选框。但我在勾选用户模块的复选框时遇到问题。我收到数据参数错误。

表单字段:

 $user = $options['user'];
 $tools = $options['tools'];

        foreach ($tools as $tool) {
            $name = 'profile_'.str_replace(array('-', ' ', '.'), '', $tool->getLibelle());
            $builder
                ->add($name, ChoiceType::class, [
                    'label' => $tool->getLibelle(),
                    'choices' => $tool->getModules(),
                    'choice_value' => 'id',
                    'choice_label' => function (?Module $module) {
                        return $module ? $module->getName() : '';
                    },
                    'data'=> $user->getModules(), // ERROR HERE
                    'expanded' => true,
                    'multiple' => true,
                    'mapped'=>false
                ])
            ;
        }

[...]

public function configureOptions(OptionsResolver $resolver): void
{
    $resolver->setDefaults([
        'data_class' => User::class,
        'user'=> null,
        'category'=> null,
        'tools'=> null,
    ]);
}

错误:

我的问题:

为什么我会出现这个错误?如何正确使用data参数才能达到预期的效果?

symfony symfony-forms
2个回答
0
投票

你做得很好,尝试转储 $user->getModules() 返回的内容,它必须是一个数组。可能没有返回数组,请检查关系。

我做了一个小测试,效果很好。

$name = 'name_field';
$builder->add($name,ChoiceType::class, array(
    'choices' => array('Yes', 'No'),
    'data' => array('Yes', false),
    'mapped' => false,
    'expanded' => true,
    'multiple' => true
));

0
投票

在我看来 $user->getModules() 返回一个集合。我设法找到了另一个解决方案并且有效(我将字段的类型更改为 EntityType)

foreach ($tools as $tool) {
            $name = 'acces_'.str_replace(array('-', ' ', '.'), '', $tool->getLibelle());
            $builder
                ->add($name, EntityType::class, [
                    'class'=> Module::class,
                    'label' => $tool->getLibelle(),
                    'data' => $user->getModules(),
                    'choices'=> $tool->getModules(),
                    'choice_value' => 'id',
                    'choice_label' => 'name',
                    'expanded' => true,
                    'multiple' => true,
                    'required' => true,
                    'mapped'=>false,
                ])
            ;
        }

ChoiceType:数据参数需要数组

EntityType:需要采集的数据参数

© www.soinside.com 2019 - 2024. All rights reserved.