自定义查询形式



createquerybuilder查询工作良好的表单时,我尝试使用EntityManager编写自定义查询时显示警告。EntityManager不可用。

控制器:

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

ContractStepe

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编写自定义查询,我如何在此处使Entity 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);

您可以通过制作表单类型A服务来注入$em

# myBundleconfigservices.yml
services:
    form.type.address:
        class: myBundleFormAddressType
        arguments: ['@doctrine.orm.entity_manager'] # We inject our familiar $em.

同时,以我们的形式类型:

// myBundleFormAddressType.php
// ...
Class AddressType
{
    protected $em;
    public function __construct(DoctrineORMEntityManager $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!
    }
}

您可以使用"选择"选项为EntityType表单,因此您只能在查询构建器中执行查询,而是在您的form类型中,而结果设置为

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

相关内容

  • 没有找到相关文章

最新更新