-2

I create a form and add EntityType field:

        ->add('name', EntityType::class, [
            'class' => MyTest::class,
            'choice_label' => function($name){
                return $name->getName();
            },
            'mapped' => false
        ])

I want show the Name that Category is car.

My database table is:

id | name | category

2 Answers2

0

Simply do this, in callback function on choice_label you are free to do anything to modify the label, in case category is a string skip the getName(), if you want to display the category not some string based on the category name skip the switch as well

->add('name', EntityType::class, [
            'class' => MyTest::class,
            'choice_label' => function(MyTest $entity){
                switch($entity->getCategory()->getName()) {
                    case 'car':
                        return 'It\'s a car!';
                }
                return $entity->getCategory()->getName();
            },
            'mapped' => false
        ])
B0re
  • 239
  • 1
  • 8
0

Add query_builder to your code.

    ->add('name', EntityType::class, [
        'class' => MyTest::class,
        'query_builder' => function(EntityRepository $er){
            return $er->createQueryBuilder('u')
                ->where('u.category = :category')
                ->setParameter('category', 'car');
        },
        'choice_label' => function($name){
            return $name->getName();
        },
        'mapped' => false
    ])