gpt4 book ai didi

php - Symfony 错误 - EntityManager#persist() 期望参数 1 是一个实体对象,数组给定

转载 作者:行者123 更新时间:2023-12-05 08:57:43 25 4
gpt4 key购买 nike

我是 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';
}
}

默认 Controller

<?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(),
));
}
}

我已经尝试在文档中搜索这个问题,但找不到解决方案。请帮助。

谢谢!

最佳答案

您应该将您的 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 所建议的那样。

关于php - Symfony 错误 - EntityManager#persist() 期望参数 1 是一个实体对象,数组给定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29962905/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com