【问题标题】:Wrong expected argument of type错误的预期参数类型
【发布时间】:2019-08-28 06:33:23
【问题描述】:

我的模型中有一个名称为 rank 且类型为整数的字段。

在我的formType 中,它是一个EntityType,因为我需要这个下拉菜单来选择新条目的顺序(排名)。

现在表单的验证当然会带来错误:

“整数”、“App\Entity\ProductType”类型的预期参数在 属性路径“rank”。

我该如何处理这种情况? 这是 Symfony 4

在模型中,我有字段

/**
 * @ORM\Column(type="integer")
 */
 private $rank;

在我的 formType 中我添加了这个实体

->add('rank', EntityType::class, [
    'class' => ProductType::class,
    'query_builder' => function (EntityRepository $er) {
        return $er->createQueryBuilder('p')->orderBy('p.rank', 'ASC');
    },
    'choice_label' => function($productType) {
        return 'nach ' . $productType->getNameDe();
    },
    'choice_value' => function ($productType) {
        return $productType ? $productType->getRank() : '';
    },
    'placeholder' => 'am Anfang',
])

在控制器中

$productType = new ProductType();
$form = $this->createForm(ProductTypeType::class, $productType);

if ($request->isMethod('POST')) {
            
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) { /*here it breakes of course*/
        $entityManager = $this->getDoctrine()->getManager();
        
        /*Here I will set the new order (rank) to all my entries later then
          but the Form validation gives me the error*/


        $entityManager->persist($productType);
        $entityManager->flush();

        return $this->redirectToRoute('admin_product_type_index');
    }
}

【问题讨论】:

    标签: php symfony entity symfony-forms


    【解决方案1】:

    EntityType 从实体(对象)中选择类型并返回一个实体(对象)并期望一个实体(对象)。

    但是,rank 似乎是一个 int。因此与EntityType 期望和返回的内容不兼容。要更改EntityType 的功能,您可能必须进行一些肮脏的黑客攻击,这至少涉及data transformer - 您可以将一个附加到表单字段,它会在表单和它获取/返回的值之间转换数据.

    您可能需要向数据转换器提供EntityRepositoryManager/EntityRepository 才能正常工作。

    使用ChoiceType更容易,只需从EntityRepository 生成choices 即可生成您期望的排名值。

    【讨论】:

    • 谢谢Jakumi,我想我试试ChoiceType,非常好的主意
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-21
    • 1970-01-01
    • 1970-01-01
    • 2020-03-05
    • 2021-08-10
    • 2021-04-30
    相关资源
    最近更新 更多