Domanda

I have 3 entities: Company, Department, and User User has a one to many relationship to company. Department has separate many to one relationships with both Company and User

The goal is for each department to have different departments configured, and the user to be able to select (in their profile) from the departments belonging to their company.

I am trying to accomplish this with the build in entity field type. My issue is that when Symfony renders the field, the user is allowed to choose ANY department, not just departments belonging to that users company.

I tried using a custom query, but I am getting an error that $company doesn't exist (even though I have it in my function). I think this is because the custom query is in a closure, which has its own scope.

È stato utile?

Soluzione

Your suggestion to use a custom query was totally right. To use an object in the scope of the custom query you have to use the use statement. E.g.:

    $company = $user->getCompany();

    $builder->add('department', 'entity', array(
        'class' => 'YourSpecialBundle:Department',
        'property' => 'name',
        'query_builder' => function(EntityRepository $er) use($company) {
             return $er->createQueryBuilder('r')
                     ->where('r.company = :company')
                     ->setParameter("company", $company);
         }
    ));

If you need to define multiple filters:

    $company = $user->getCompany();

    $builder->add('department', 'entity', array(
        'class' => 'YourSpecialBundle:Department',
        'property' => 'name',
        'query_builder' => function(EntityRepository $er) use($company) {
             return $er->createQueryBuilder('r')
                     ->where('r.company = :company AND r.active = :active')
                     ->setParameter(array(
                            "company" => $company,
                            "active" => true
                     ));
         }
    ));
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top