我正在使用Symfony2。我想将一个参数从Controller传递给FormType: 这是我的行动:
public function addAction(Request $request)
{
$employee = $this->getUser();
if (null === $employee) {
throw $this->createNotFoundException("L'employé est anonyme.");
} else {
$em = $this->getDoctrine()->getManager();
$abs = new Absence();
$form = $this->createForm(new AbsenceType($employee), $abs);
if ($form->handleRequest($request)->isValid()) {
$employee->addAbsence($abs);
$em->persist($employee);
$em->flush();
$this->addFlash('notice', 'absence bien enregistrée.');
return $this->redirect($this->generateUrl('pfe_time_absence_index'));
}
}
return $this->render('PFETimeBundle:Absence:add.html.twig', array(
'form' => $form->createView(),
));
}
这是我的FormType:
class AbsenceType extends AbstractType
{
protected $sup;
public function __construct ( Employee $profile)
{
$this->sup = $profile;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$supp=$this->sup;
$builder
->add('employee', 'entity', array(
'class' => 'PFEUserBundle:Employee',
'property'=>'matricule',
'query_builder' => function(EmployeeRepository $er) use ($supp){
return $er->createQueryBuilder('e')
->where("e.parent.matricule = :matricule")
->orderBy('e.nom', 'ASC')
->setParameter('matricule', $supp->getMatricule())
;
}
))
->add('dateDebut','date')
->add('dateFin','date')
->add('motif', 'choice', array(
'expanded' => true,
'multiple' => false,
'choices' => array('Non'=>'Non','Oui'=>'Oui'),))
->add('motif','textarea')
->add('valider','submit')
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'PFE\TimeBundle\Entity\Absence'
));
}
public function getName()
{
return 'pfetime_bundle_absence_type';
}
}
查询获取员工的所有子项并将其传递给实体列表(我使用的是doctrine扩展名)。 当我执行操作时,它给了我这个错误:
Catchable Fatal Error: Argument 1 passed to PFE\TimeBundle\Form\AbsenceType::PFE\TimeBundle\Form\{closure}() must be an instance of PFE\UserBundle\Entity\EmployeeRepository, instance of Gedmo\Tree\Entity\Repository\NestedTreeRepository given, called in C:\wamp\www\Projet\vendor\symfony\symfony\src\Symfony\Bridge\Doctrine\Form\ChoiceList\ORMQueryBuilderLoader.php on line 56 and defined
答案 0 :(得分:1)
您获得的实际错误是query_builder
关闭中的typehint存在问题。
function(EmployeeRepository $er) {}
您的关闭期望PFE\UserBundle\Entity\EmployeeRepository
的实例,但正在接收Gedmo\Tree\Entity\Repository\NestedTreeRepository
的实例
有几件事可能导致这种情况,但它可能是这两个中的一个
Employee
实体未定义repositoryClass
已定义here EmployeeRepository
课程不会继承Gedmo\Tree\Entity\Repository\NestedTreeRepository
所有这些,您应该查看Form Events这样的功能。