如何将 ChoiceType 框标记为默认值

how to check a choicetype box as default

提问人:Kartik 提问时间:9/5/2023 最后编辑:Miss SkooterKartik 更新时间:9/12/2023 访问量:25

问:

如何默认选中 PMTool 复选框?此外,当我修改现有用户时,我不希望它覆盖数据。

-> add('raw_roles', ChoiceType:: class, [
    'label' => 'User access',
    'multiple' => true,
    'expanded' => true,
    'choices' => [
        'PMTool' => 'ROLE_USER',
        'SPOC' => 'ROLE_SPOC_USER',
        'Debug' => 'ROLE_SOAP_USER',
    ],
    data => ['ROLE_USER'],
])

我尝试使用上面的代码实现所需的结果,但是当我修改现有用户时,PMTool复选框会自动选中,并且在未取消选中的情况下不会保存。

php 表单 symfony-forms symfony5

评论


答:

0赞 Mohammed Jhosawa 9/6/2023 #1

回调返回以默认选中“PMTool”复选框。否则,我们返回一个空数组以取消选中该复选框。(文档['ROLE_USER'][])

->add('raw_roles', ChoiceType::class, [
    'label' => 'User access',
    'multiple' => true,
    'expanded' => true,
    'choices' => [
        'PMTool' => 'ROLE_USER',
        'SPOC' => 'ROLE_SPOC_USER',
        'Debug' => 'ROLE_SOAP_USER',
    ],
    'data' => function ($value, $user) {
        // Check if the user already has the 'ROLE_USER' (PMTool) role
        if (in_array('ROLE_USER', $user->getRoles())) {
            return ['ROLE_USER'];
        } else {
            return [];
        }
    },
])