我正在学习symfony,我现在几个小时都遇到这个问题了。我试图从FOSuserbundle获取用户ID到我自己的表单的Dropdown。但是无法成功..我想__construct函数做错了我猜...这是代码
ShiftType.php :
class ShiftType extends AbstractType
{
protected $users;
public function __construct (User $users)
{
$this->users = $users;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$user = $this->user;
$builder
->add('date', 'date', array(
'label' => 'Shift Date',
'attr' => array(
'class' => 'form-control'
)
))
->add('site_name', 'text', array(
'label' => 'Site Name',
'attr' => array(
'class' => 'form-control'
)
))
->add('location', 'text', array(
'label' => 'Site Location',
'attr' => array(
'class' => 'form-control'
)
))
->add('startTime', 'time', array(
'label' => 'Start time',
'attr' => array(
'class' => 'form-control'
)
))
->add('endTime', 'time', array(
'label' => 'End time',
'attr' => array(
'class' => 'form-control'
)
))
->add('employee', 'button', array(
'class' => 'UserBundle:user',
'label' => 'Select Employee',
'attr' => array(
'data-toggle' => 'dropdown',
'class' => 'form-control btn btn-default dropdown-toggle',
'query_builder' => function(EntityRepository $er) use ($users) {
return $er->createQueryBuilder('pp')
->where("pp.username = :username")
->orderBy('pp.index', 'ASC')
->setParameter('users', $users)
;
},
)
))
->add('save', 'submit', array(
'attr' => array(
'class' => 'btn btn-lg btn-primary'
)
));
}
public function getName()
{
return 'shifts';
}
}
我对QueryBuilder功能也有疑问。如果我以正确的方式做到这一点。
这是我的控制器:
public function shiftAction(Request $request)
{
$shift = new Shifts();
$em = $this->getDoctrine()->getManager();
$users = new User;
$users = $em->getRepository('UserBundle:User')
->findAll();
//var_dump($users);
$form = $this->createForm(new ShiftType($users), $shift);
$form->handleRequest($request);
if ($form->isValid()) {
$em->persist($shift);
$em->flush();
return $this->redirect($this->generateUrl('allshifts'));
}
return $this->render('XYZFirstBundle:Default:shifts.html.twig', array(
'shiftForm' => $form->createView(),
));
}
我一直收到此错误
ContextErrorException:Catchable Fatal Error:传递给的参数1 XYZ \ FirstBundle \ Form \ Type \ ShiftType :: __ construct()必须是。的实例 XYZ \ FirstBundle \ Form \ Type \ User,给定的数组,调用 第33行/var/www/html/learnsymfony/src/XYZ/FirstBundle/Controller/DefaultController.php 并定义于 /var/www/html/learnsymfony/src/XYZ/FirstBundle/Form/Type/ShiftType.php第12行
答案 0 :(得分:1)
public function __construct (User $users)
该行声明函数__construct
期望将User
对象传递给它,但在您的控制器中,您传递一个数组
$users = $em->getRepository('UserBundle:User')->findAll(); // array of User objects
$form = $this->createForm(new ShiftType($users), $shift);
功能API:http://www.doctrine-project.org/api/orm/2.2/class-Doctrine.ORM.EntityRepository.html#_findAll