我想根据表单类型在Symfony2中保存表单,但找不到save()
方法。
错误消息是:
致命错误:在第44行的C:\ xampp \ htdocs \ Xq \ src \ Xq \ LogBundle \ Controller \ LogController.php中调用未定义的方法Symfony \ Component \ Form \ Form :: save()
调用save方法的控制器如下所示:
<?php
namespace Xq\LogBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\ORM\EntityRepository;
use Xq\LogBundle\Entity\Call;
use Xq\LogBundle\Form\Type\CallType;
class LogController extends Controller
{
public function callAction(Request $request)
{
#create call object
$call = new Call();
$now = new \DateTime("now");
$call->setTimestamp($now);
$call_form = $this->createForm(new CallType(), $call);
#check form input
$request = $this->get('request');
if ($request->getMethod() == 'POST')
{
$call_form->bindRequest($request);
if ($call_form->isValid())
{
**$saved_call = $call_form->save();**
}
}
return $this->render('XqLogBundle:log:call.html.twig', array('call_form'=>$call_form->createView()));
}
}
?>
CallType定义如下:
<?php
namespace Xq\LogBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
class CallType extends AbstractType
{
public function buildForm(Formbuilder $builder, array $options)
{
//here all fields are defined, and they are rendered fine
}
public function getDefaultOptions(array $options)
{
return array('data_class' => 'Xq\LogBundle\Entity\Call');
}
public function getName()
{
return 'callform';
}
}
?>
最后还有一个实体类“Call”也可以正常工作:
<?php
#ORM mapping of a call
namespace Xq\LogBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
*
* Xq\LogBundle\Entity\Call
*
* @ORM\Table(name="calls")
* @ORM\Entity
*/
class Call
{
#id of the call
/**
* @ORM\Id
* @ORM\Column(type="integer", length="7")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
#caller
/**
* @ORM\Column(name="caller", type="integer", length="3", nullable="false")
* @ORM\OneToOne(targetEntity="caller")
* @Assert\type(type="Xq\LogBundle\Entity\Caller")
*/
protected $caller;
// and so on ....
#getters and setters
/**
* Get id
*
* @return integer $id
*/
public function getId()
{
return $this->id;
}
// and so on...
}
有人知道为什么找不到保存方法吗? bind()
方法不会触发错误,因此我猜必须有一个有效的表单对象。
答案 0 :(得分:4)
表单不对持久化对象负责;他们负责输出带有来自对象的值的表单字段,并将用户输入放在表单提交上的该对象中。
使用Doctrine来保存您的对象。以下是Forms and Doctrine部分的代码段,适用于您的示例:
if ($call_form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($call);
$em->flush();
}