Symfony表单中的自定义查询

时间:2017-02-16 09:31:27

标签: php symfony doctrine-orm

createQueryBuilder查询工作正常表单,当我尝试使用EntityManager编写自定义查询时显示警告。 EntityManager不可用。

控制器:

$form = $this->createForm(new ContractsType($user, $isAdmin, $securityContext), $contract, array('em' => $em, 'referring_student' => $contract->getReferringStudent()));

ContractsType

class ContractsType extends AbstractType {

$queryBuilder = function($repo) use ($user) {

return $repo->createQueryBuilder('p')
    ->leftJoin('p.employees', 'e')
    ->where('e.id = :employee_id')
    ->setParameter('employee_id', $user->getId())
    ->orderBy('p.name', 'ASC');
}
  $builder->add('store', 'entity', array(
        'class' => 'C2EducateToolsBundle:Stores',
        'label' => 'Center',
        'query_builder' => $queryBuilder,
        'property' => 'name',
        'empty_value' => 'Select')
    );
    }

createQueryBuilder工作正常,但我想使用EntityManager编写自定义查询,如何在此处使实体Equery可用。这样我就可以运行下面的查询。

$storesQuery = "select store_id as id,ts.name as name from tbl_employees e LEFT JOIN tbl_stores ts ON e.store_id=ts.id where e.id=:employeesId  AND ts.center_type_id!=:centerTypeId AND ts.select_option = :selectOption";
            $em = $this->getDoctrine()->getEntityManager();
            $stmt = $em->getConnection()->prepare($storesQuery);
            $stmt->bindValue('employeesId', $user->getId());
            $stmt->execute();
            $listLocations = $stmt->fetchAll(\PDO::FETCH_ASSOC);

2 个答案:

答案 0 :(得分:1)

您可以使用"选择" EntityType表单的选项,因此您只需在查询构建器中执行查询,但在表单类型和结果集中执行查询,如

$query = ....;
$result = $query->execute();
$builder->add('store', 'entity', array(
    'class' => 'C2EducateToolsBundle:Stores',
    'label' => 'Center',
    'choices' => $result,
    'property' => 'name',
    'empty_value' => 'Select')
);

答案 1 :(得分:1)

您可以通过form type a service注入$em

# myBundle\config\services.yml
services:
    form.type.address:
        class: myBundle\Form\AddressType
        arguments: ['@doctrine.orm.entity_manager'] # We inject our familiar $em.

同时,在我们的表单中输入:

// myBundle\Form\AddressType.php
// ...
Class AddressType
{
    protected $em;

    public function __construct(\Doctrine\ORM\EntityManager $em) // Type-hint so nothing funny gets in.
    {
        $this->em = $em; // And store it on our form type during instantiation.
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // ... Then use it in here!
    }
}