【问题标题】:symfony forms: get a second attribute in label for a select elementsymfony forms:在标签中为选择元素获取第二个属性
【发布时间】:2018-11-15 13:24:04
【问题描述】:

我有一个实体Institution。在表单中,用户可以选择一个或多个。我使用 Select2 作为字体端。一个机构有属性internationalName,这是默认属性,因为:

Institution.php

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

机构也可以有一个缩写名称,作为属性abbreviation。我想要的是使用第二个属性在选择表单中显示(如果存在)。更好的是它没有显示,但你可以搜索它,但我真的不知道这是否可能。

我可以更改__toString(),使其包含abbreviation,但由于其他形式,这是不需要的,所以我试图通过

使其仅以这种形式显示

LocationType.php

->add('Institutions', EntityType::class, [
    'class' => Institution::class,
    'label' => 'Connected Institution(s)',
    'multiple' => true,
    'attr' => ['data-select' => 'true', 'data-placeholder' => 'start typing to find your institution...'],
    'constraints' => array(
        new Count(array(
            'min' => 1,
            'minMessage' => "Select at least one institution."))),
    'query_builder' => function (EntityRepository $er) {
        return $er->createQueryBuilder('i')
            ->orderBy('i.internationalName', 'ASC');
    },

我尝试使用'choice_label' => 'abbreviation'(仅作为测试),但这会使所有标签空白,我真的不明白为什么。我也尝试了'choice_label' => 'internationalName'.'abbreviation',但这不起作用,因为没有属性internationalNameabbreviation。我考虑过创建一个新属性,将两者结合起来,但鉴于'choice_label' => 'abbreviation' 已经导致一个空白列表,我认为这行不通。还有其他选择或解决方案吗?

编辑:根据要求相关实体类部分, Institution.php

/**
 * @Assert\NotBlank(message="Please enter the international name.")
 * @ORM\Column(type="string")
 */
private $internationalName;

/**
 * @ORM\Column(type="string", nullable=true)
 */
private $abbreviation;

【问题讨论】:

  • 您的实体有一个“缩写”属性?
  • 它有一个'abbreviation'属性,是的,它是一个字符串。
  • 你能发布你的实体类吗?
  • @ThomasLefetz,我添加了实体类的相关部分。

标签: php symfony jquery-select2 symfony4


【解决方案1】:

可能是这样的:

https://symfony.com/doc/current/reference/forms/types/choice.html#choice-value

  ->add('Institutions', EntityType::class, [
    'class'         => Institution::class,
    'label'         => 'Connected Institution(s)',
    'query_builder' => function (EntityRepository $er) {
        return $er
          ->createQueryBuilder('i')
          ->orderBy('i.internationalName', 'ASC')
        ;
    },
    'choice_value' => function (Institution $institution = null) {
        return $institution ? $institution->getInternationalName() . '(' . $institution->getAbbreviation() . ')' : '';
    },
  ])

【讨论】:

  • 使用 'choice_label' 而不是 'choice_value' 这是一个不错的选择,我可以显示缩写并搜索它。如果您对此也有建议,下一步是向用户隐藏缩写部分,但仍使其可搜索。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-02
  • 2023-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多