我有一个用于编辑News
实体的表单。在这里:
<form action="{{path('validate_news', {'id': news.id})}}" method="POST" >
<div class="form-group row">
<label for="Text" class="col-sm-4 col-form-label">Text</label>
<div class="col-sm-5">
<textarea name = "text" type="text" class="form-control" id="text" aria-describedby="textHelp" placeholder="{{news.text|e}}"></textarea>
</div>
</div>
<div class="form-group row">
<label for="startDate" class="col-sm-4 col-form-label">Start Date</label>
<div class="col-sm-5">
<input name = "startDate" type="date" class="form-control" id="startDate" aria-describedby="startDate" placeholder="{{news.startDate|date('d-m-Y')}}">
</div>
</div>
<div class="form-group row">
<label for="expireDate" class="col-sm-4 col-form-label">Expire Date</label>
<div class="col-sm-5">
<input name = "expireDate" type="date" class="form-control" id="expireDate" aria-describedby="emailHelp" placeholder="{{news.expireDate|date('d-m-Y')}}">
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
validate_news
路由有控制器,当用户单击"提交"按钮时激活:
/**
* @Route("/validateNews/{id}", name = "validate_news")
* @Method("POST")
**/
public function validateNewsAction(Request $request, $id) {
$repository = $this->getDoctrine()->getRepository('AppBundle:News');
$news = $repository->findOneById($id);
if ($request->getMethod() == 'POST') {
$text = $request->get('text');
$startDate = new DateTime();
$startDate = $request->get('startDate');
$expireDate = new DateTime();
$expireDate = $request->get('expireDate');
}
$news->setText($text);
$news->setStartDate($startDate);
$news->setexpireDate($expireDate);
$em = $this->getDoctrine()->getManager();
$em->persist($news);
$em->flush();
return $this->render("AppBundle:Default:editNewsSuccess.html.twig", array ('news' => $news));
}
startDate
和expireDate
属性定义为 datetime
。
当我尝试刷新News
对象时,出现此错误:
FatalErrorException in DateTimeType.php line 53:
Error: Call to a member function format() on a non-object
在控制器中的$startDate
上启动var_dump
,我可以看到它具有string
类型。但是在形式上,我将其定义为datetime
.
为什么POST
电话中会发生这种情况?
因为您正在从表单中获取字符串值。您需要为实体设置日期时间对象。
像那样尝试
$startDate = new DateTime($request->get('startDate'));