如何自定义EntityType选项文本?

时间:2016-12-20 13:27:05

标签: forms symfony query-builder

我想用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表列的组合:

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

1 个答案:

答案 0 :(得分:5)

您可以使用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版本(&lt; = 2.6),此选项名为property并使用PropertyAccessor component支持的内容,因此您不能使用函数,只能使用getter。