【问题标题】:get error on symfony : "Expected argument of type "AppBundle\Entity\Magasin\Caracteristique\ChoixCaracteristique", "string" given"在 symfony 上出现错误:“类型为“AppBundle\Entity\Magasin\Caracteristique\ChoixCaracteristique”的预期参数,给定“字符串”
【发布时间】:2018-03-01 10:08:42
【问题描述】:

我对表单中ChoiceType 的返回码有疑问:

$form->add('choix',ChoiceType::class, array(
           'choices' => $voila ,
           'multiple'=>false,'label'=>$nom,'expanded'=>true));  

此代码调用实体中的 setChoix() 函数:

public function 
setChoix(\AppBundle\Entity\Magasin\Caracteristique\ChoixCaracteristique 
$choix = null)
{
   $this->choix = $choix;
   return $this;
}

之前,我没有使用 ChoiceType 而是使用 EntityType,所以,它起作用了:

$form->add('choix', EntityType::class, array(
           'class' => 'AppBundle:Magasin\Caracteristique\ChoixCaracteristique',
           'choices' => $choix,
           'placeholder' => 'Choix',
           'label' => $label,
           'required' => false
        )); 

我的问题是“

如何 CAST ChoiceType 避免类型问题 (EntityType使用AppBundle:Magasin\Caracteristique\ChoixCaracteristique类型,所以可以)

感谢您的帮助!

【问题讨论】:

    标签: symfony


    【解决方案1】:

    为什么你使用 ChoiceType 作为 entity ?真奇怪。 :)

    如果你想使用 ChoiceType,你可以在提交后使用 DataTransformer 在ChoixCaracteristique 实体中进行转换选择:https://symfony.com/doc/current/form/data_transformers.html

    【讨论】:

    • 是的,我明白 :) 在实体的表单中使用 ChoiceType 很奇怪。但是你可以使用 DataTransformer 来解决它:)
    • 好的,非常感谢,但是为什么使用EntityType,没有问题,使用ChoiceType,有问题..?
    • EntityType : " 一个特殊的 ChoiceType 字段,旨在从 Doctrine 实体中加载选项。例如,如果您有一个 Category 实体,您可以使用此字段来显示全部或部分的选择字段, 来自数据库的 Category 对象。" : symfony.com/doc/current/reference/forms/types/entity.html 对于 ChoiceType,它只是列表或复选框:返回字符串或布尔值(并且您的实体正在等待 ChoixCaracteristique 类)。但是您可以使用 DataTransformer 更改 ChoiceType 返回:symfony.com/doc/current/form/data_transformers.html
    • 这意味着将 ChoiceType 转换为 Integer,而不是 boolean 或 string ?
    • 我也是法国人,我的英语很糟糕:1/ Tu as une entite "ChoixCaracteristique"。 Dans ton formulaire, pour gérer cette entité, il est recommandé d'utiliser EntityType qui s'occupe de Charger Doctrine。 ChoiceType ne permet que de gérer des textes (string) ou des booléen。 2/ En liant ChoiceType à ton entité ChoixCaracteristique,celle-ci retourne une erreur car elle 参加 un objet ChoixCaracteristique 3/ Donc sois tu 使用 EntityType,sois tu 使用效率 ChoiceType mais il faudra utiliser un DataTransformer, qui transformera le booléen en entité :)
    【解决方案2】:

    在我的 EntityType 中,我只是添加了这些选项:

    'multiple' => false,
    'expanded' => true,
    

    让它发挥作用

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-30
      • 1970-01-01
      • 1970-01-01
      • 2019-11-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多