首页 > 解决方案 > SELECT 的 Symfony 值

问题描述

我有一个 Select 获取字符串列表,但我需要在数据库中插入他们的 ID,而不是他们的名字。我在 symfony 4.2 下工作 在我的表单中,我使用这个(有效):

    $builder
        ->add('cours', EntityType::class, array(
          'class' => Cours::class,
          'label' => false,
          'placeholder' => 'Cours',
          'required' => true,
          'choice_label' => 'nomUe',
          'choices' => $formation->getCours(),
          'attr' => array('class' => 'custom-select')
        ))
我查看了文档,我想插入类似的内容

          'choice_value' =>  $formation->getId(),
但这给了我一个错误,例如: 在此处输入图像描述

和想法?谢谢!

标签: symfony

解决方案


实际上,您可能已经在 Class 实体中重新定义了 __toString 方法……这就是为什么您在表单中具有可视名称的原因……但是在数据库中它将记录您的实体的 ID。

所以你必须删除表单中的行选择......所以最后你的表单应该是这样的:

    $builder
        ->add('cours', EntityType::class, array(
          'class' => Cours::class,
          'label' => false,
          'placeholder' => 'Cours',
          'required' => true,
          'choice_label' => 'nomUe',
          'attr' => array('class' => 'custom-select')
        ))

但是...我想您在 Class 实体中的 __toString 方法如下所示:

public function __toString()
    {
      return $this -> getName() ;
    }

因此,如果您更喜欢在表单中使用 Id 而不是实体的名称,则必须显示它:

public function __toString()
    {
      return  (String) $this -> getId() ;
    }


推荐阅读