Reputation: 1972
createQueryBuilder Query Working fine Form, when i try to write custom Query using EntityManager its showing warning. EntityManager not available.
Controller :
$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 working Fine, but I want to write custom Query using EntityManager, How can I make the entity Equery available here. so that I can Run the below Query.
$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);
Upvotes: 0
Views: 1651
Reputation: 1345
You can inject $em
by making the form type a service.
# myBundle\config\services.yml
services:
form.type.address:
class: myBundle\Form\AddressType
arguments: ['@doctrine.orm.entity_manager'] # We inject our familiar $em.
Meanwhile, in our form type:
// 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!
}
}
Upvotes: 1
Reputation: 36
You can use "choices" option for EntityType form, so you just execute query not in query builder but in your form type and result set to choices like
$query = ....;
$result = $query->execute();
$builder->add('store', 'entity', array(
'class' => 'C2EducateToolsBundle:Stores',
'label' => 'Center',
'choices' => $result,
'property' => 'name',
'empty_value' => 'Select')
);
Upvotes: 1