代码之家  ›  专栏  ›  技术社区  ›  Dirk J. Faber

symfony forms:在select元素的label中获取第二个属性

  •  0
  • Dirk J. Faber  · 技术社区  · 6 年前

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

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

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

    我可以改变 __toString() 缩写 ,但这是不需要的,因为其他形式,所以我试图使它只显示在这个形式通过

    ->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 '选择标签'=>'缩写' 已经在一个空白列表的结果,我不认为这将工作。还有其他选择或解决方案吗?

    编辑:根据相关实体类零件的要求, 机构.php

    /**
     * @Assert\NotBlank(message="Please enter the international name.")
     * @ORM\Column(type="string")
     */
    private $internationalName;
    
    /**
     * @ORM\Column(type="string", nullable=true)
     */
    private $abbreviation;
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Alex.Barylski    6 年前

    可能是这样的:

    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() . ')' : '';
        },
      ])
    
    推荐文章