doqp87012
2018-09-25 04:15
浏览 43
已采纳

Symfony / Doctrine - 从实体构造函数中获取记录?

Using Symfony 4, I'm looking at the documentation for choicetype here and I see this

use App\Entity\Category;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
// ...

$builder->add('category', ChoiceType::class, [
    'choices' => [
        new Category('Cat1'),
        new Category('Cat2'),
        new Category('Cat3'),
        new Category('Cat4'),
    ],

I assume that by calling new Category('Cat1') that it would basically do a lookup in the database of that record based of something like a name field.

How do you do that in the Entity constructor? Unfortunately I don't see any documentation on how that would be done? Or is it just making a new category there (though I fail to see how this would work as it would be missing the database id without a lookup)?

Basically I have the following:

Employee Table
 - employee_id

Employee Roles Table
 - employee_id
 - role_id

Roles Table
 - role_id

So one employee can have many roles. I use a mapping table to do this. What I need is a choicetype that gives me all the roles (all records from Roles table) and then selects the ones that are found in the mapping table (Employee Roles where employee_id = x)

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douni1396 2018-09-25 05:52
    已采纳

    What you are searching might be https://symfony.com/doc/current/reference/forms/types/entity.html

    The EntityType does get records from the database (doctrine). You can use the query_builder option to modify the query to your needs: https://symfony.com/doc/current/reference/forms/types/entity.html#query-builder

    It will look like this if you want to limit the choices to active ones (example):

    use App\Entity\Category;
    use Symfony\Bridge\Doctrine\Form\Type\EntityType;
    // ...
    
    $builder->add('category', EntityType::class, array(
        'class' => Category::class,
        'choice_label' => 'displayName', // property to use as the option value
        'query_builder' => function (EntityRepository $er) {
            return $er->createQueryBuilder('c')
                ->where('c.active = 1');
        },
    ));
    
    点赞 打赏 评论

相关推荐 更多相似问题