我是symfony的新手..我在以数组的形式保存数据时遇到了一些麻烦..我每次都会收到此错误。
“EntityManager #persist()期望参数1是实体对象,给定数组。
500内部服务器错误 - ORMInvalidArgumentException“
这是我的代码..
我的表单类型
<?php
namespace Demo\FirstBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
class ShiftType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$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('save', 'submit', array(
'attr' => array(
'class' => 'btn btn-lg btn-primary'
)
));
}
public function getName()
{
return 'shifts';
}
}
默认控制器
<?php
namespace Demo\FirstBundle\Controller;
use Demo\FirstBundle\Entity\Shifts;
use Demo\FirstBundle\Form\Type\ShiftType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
class DefaultController extends Controller
{
public function indexAction()
{
return $this->render('DemoFirstBundle:Default:index.html.twig');
}
public function shiftAction(Request $request)
{
$shift = new Shifts();
$em = $this->getDoctrine()->getManager();
$form = $this->createForm(new ShiftType());
$form->handleRequest($request);
if ($form->isValid()) {
$shift = $form->getData();
$em->persist($shift);
$em->flush();
return $this->redirect($this->generateUrl('demo_first_homepage'));
}
return $this->render('DemoFirstBundle:Default:shifts.html.twig', array(
'shiftForm' => $form->createView(),
));
}
}
我尝试在文档中搜索此问题,但找不到解决方案..请帮忙。
感谢!
答案 0 :(得分:6)
您应该将Shift
实体传递到表单中,以便handleRequest
填充它。
$em = $this->getDoctrine()->getManager();
$shift = new Shifts();
// Pass the shift object into the form as the data property
$form = $this->createForm(new ShiftType(), $shift);
$form->handleRequest($request);
if ($form->isValid()) {
$em->persist($shift);
$em->flush();
...
}
...
您还可以为表单设置data_class
以匹配Janne Savolainen
建议的模型/实体的表单。
答案 1 :(得分:1)
将data_class设置为form:
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Task',
));
}
更多信息:http://symfony.com/doc/current/book/forms.html#book-forms-data-class