为了账号安全,请及时绑定邮箱和手机立即绑定

传递给 Symfony\Bridge\Doctrine\Form\ChoiceList\

传递给 Symfony\Bridge\Doctrine\Form\ChoiceList\

PHP
慕莱坞森 2023-07-08 16:36:34
我是 Symfony 的新手。我使用 DestinationFormType和DestinationController 来保存 Destination。JS 部分运行良好,但现在当我尝试保存实体时会抛出下一个异常:传递给 Symfony\Bridge\Doctrine\Form\ChoiceList\IdReader::getIdValue() 的参数 1 必须是一个对象或 null,给定 int,在第 200 行的 \vendor\symfony\form\ChoiceList\ArrayChoiceList.php 中调用奇怪的是,它似乎试图转换一个不需要转换的值(191)(堆栈调用顶部):对于国家/地区实体会引发错误。这是我的 DestinationFormType
查看完整描述

3 回答

?
潇潇雨雨

TA贡献1833条经验 获得超4个赞

好吧,通过观看我的代码,答案并不明显,因为当你看到


$countries = $countryRepository->findByRegionId($region->getId());

你可能认为返回的是国家数组,但实际上它是 JS 的助手,只返回 id 和 name


/**

 * @param int $regionId

 * @return array

 */

public function findByRegionId(int $regionId)

{

    return $this->createQueryBuilder('c')

        ->select(['c.id', 'c.name'])

        ->where('c.region = :id')

        ->orderBy('c.name')

        ->setParameter('id', $regionId)

        ->getQuery()

        ->execute();

}

所以以防万一其他人遇到这个问题: $choices 需要一个对象数组,而不是一个带有 id 和 name 的数组,所以我修改了我的 addCountryDropDown 方法,如下所示


private function addCountryDropdown(FormInterface $form, ?Region $region, ?Country $country)

{

    $countries = array();


    if ($region) {

        $countryRepository = $this->em->getRepository(Country::class);

        $countries = $countryRepository->findBy([

            'region' => $region->getId()

        ]);

    }


    $form->add('country', EntityType::class, [

        'required' => true,

        'data' => $country,

        'placeholder' => 'Select a Region first ...',

        'class' => Country::class,

        'choices' => $countries

    ]);

}


查看完整回答
反对 回复 2023-07-08
?
UYOU

TA贡献1878条经验 获得超4个赞

使用 User 实体迁移到 Symfony 5.4 后,我遇到了同样的错误。现在 getRoles() 函数必须以字符串形式返回角色列表。就我而言,我有一个实体角色。


我通过在 User 实体中添加 getRolesObjects() 解决了这个问题:


public function getRolesObjects(): array

{

    if(is_array($this->roles)) {

        return $this->roles;

    } else if($this->roles && ($this->roles instanceof Collection)) {

        return $this->roles->toArray();

    } else {

        return [];

    }

}

并在 FormType 中添加自定义 getter:


$builder

            ->add('firstName', TextType::class)

            ->add('lastName', TextType::class)

            ->add('email',  TextType::class)

            ->add('roles', EntityType::class, [

                'class' => Role::class,

                'multiple' => true,


                'getter' => function (User $user, FormInterface $form): array {

                    return $user->getRolesObjects();

                }


            ]);


查看完整回答
反对 回复 2023-07-08
?
慕工程0101907

TA贡献1887条经验 获得超5个赞

事实证明,我试图将一个数组传递给一个ChoiceType未设置为接受多项选择的数组。

我希望它可以挽救某人几分钟的生命!


查看完整回答
反对 回复 2023-07-08
  • 3 回答
  • 0 关注
  • 96 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信