Symfony错误-EntityManager#persist()要求参数1为实体对象,给定数组



我是symfony的新手。。我在以数组形式持久化数据时遇到了一些问题。。我每次都会犯这个错误。

"EntityManager#persist()要求参数1是给定数组的实体对象。

500内部服务器错误-ORMInvalidArgumentException">

这是我的代码。。

我的表单类型

<?php
namespace DemoFirstBundleFormType;
use SymfonyComponentFormAbstractType;
use SymfonyComponentFormFormBuilderInterface;
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 DemoFirstBundleController;
use DemoFirstBundleEntityShifts;
use DemoFirstBundleFormTypeShiftType;
use SymfonyBundleFrameworkBundleControllerController;
use SymfonyComponentHttpFoundationRequest;
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所建议的)相匹配。

将data_class设置为表单:

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundleEntityTask',
));
}

更多信息:http://symfony.com/doc/current/book/forms.html#book-形成数据类

相关内容

  • 没有找到相关文章

最新更新