如何自定义 EntityType 选项文本?

How to customize EntityType option text?

我想显示带有 DB 选项的选择。在这种情况下,我使用 EntityTypequery_builder:

$builder
    ->add('internships', EntityType::class, array(
        'class' => 'IndexBundle\Entity\Internship',
        'property' => 'id',
        'empty_value' => 'Choose',
        'query_builder' => function (EntityRepository $er) use ($trainee) {
            return $er->createQueryBuilder('i')
                ->where('i.trainee = :trainee')
                ->andWhere('i.state = :state')
                ->setParameter('trainee', $trainee)
                ->setParameter('state', 'unverified');
        },
        'constraints' => array(
            new NotBlank(array(
                'message' => 'choice.not.blank'
            ))
        )
    ))

现在一切都很好。我得到 select 元素,其中包含必要的选项以及 id 值的文本。

<select>
    <option value="id">id</option>
    ...
</select>

如何自定义它?

例如,我希望它是 idtype table 列的组合:

<select>
    <option value="id">#id (type)</option>
    ...
</select>

您可以使用 choice_label 选项自定义您的选项。
你可以传递一个函数来检索你想要的文本,或者如果你在另一个地方重用它,你可以添加一个 getter 到你的实体。

有函数:

$builder
    ->add('internships', EntityType::class, array(
        'class' => 'IndexBundle\Entity\Internship',
        'property' => 'id',
        'empty_value' => 'Choose',
        'query_builder' => function (EntityRepository $er) use ($trainee) {
            return $er->createQueryBuilder('i')
                ->where('i.trainee = :trainee')
                ->andWhere('i.state = :state')
                ->setParameter('trainee', $trainee)
                ->setParameter('state', 'unverified');
        },
        'choice_label' => function ($internship) {
            return '#'.$internship->getId().' ('.$internship->getType().')';
        },
        'constraints' => array(
            new NotBlank(array(
                'message' => 'choice.not.blank'
            ))
        )
    ))

同一个getter:

$builder
    ->add('internships', EntityType::class, array(
        'class' => 'IndexBundle\Entity\Internship',
        'property' => 'id',
        'empty_value' => 'Choose',
        'query_builder' => function (EntityRepository $er) use ($trainee) {
            return $er->createQueryBuilder('i')
                ->where('i.trainee = :trainee')
                ->andWhere('i.state = :state')
                ->setParameter('trainee', $trainee)
                ->setParameter('state', 'unverified');
        },
        'choice_label' => 'idAndType',
        'constraints' => array(
            new NotBlank(array(
                'message' => 'choice.not.blank'
            ))
        )
    ))

Internship.php:

Class Internship
{
    //...
    public function getIdAndType()
    {
        return '#'.$this->id.' ('.$this->type.')';
    }
}

注:
对于旧的 Symfony 版本(<= 2.6),这个选项被命名为 property and use something supported by the PropertyAccessor component,所以你不能使用一个函数,只能使用一个 getter。