亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

傳遞給 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 后,我遇到了同樣的錯誤?,F在 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 關注
  • 154 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號