【发布时间】:2017-12-11 17:56:28
【问题描述】:
我试图弄清楚为什么当我创建一个带有来自 json 请求的值的预填充实体的表单时表单没有验证。
这是 Symfony 中已经配置了 FosRestBundle 的控制器:
public function createAction(Request $request)
{
$house = new House();
$house->setTitle($request->get('title'));
$house->setDescription($request->get('description'));
$house->setPostcode($request->get('postCode'));
$house->setPhoneNumber((int) $request->get('phoneNumber'));
$availability = $request->get('available') ? true : false;
$house->setAvailability($availability);
$form = $this->createCreateForm($house);
$form->handleRequest($request);
$response = new JsonResponse();
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($house);
$em->flush();
return $response->setData(array(
'success' => true
));
}
return $response->setData(array(
'success' => false,
'errors' => $this->getFormErrors($form)
));
}
private function createCreateForm(House $entity)
{
$form = $this->createForm(new HouseType(), $entity, array(
'action' => $this->generateUrl('houses_create'),
'method' => 'POST',
'csrf_protection' => false
));
return $form;
}
yaml 配置文件:
# app/config/config.yml
fos_rest:
param_fetcher_listener: true
body_listener: true
routing_loader:
default_format: json
exception:
enabled: true
# configure the view handler
view:
force_redirects:
html: true
formats:
json: true
xml: true
templating_formats:
html: true
# add a content negotiation rule, enabling support for json/xml for the entire website
format_listener:
enabled: true
rules:
- { path: ^/, priorities: [ json, xml, html ], fallback_format: html, prefer_extension: false }
例如,如果我执行$form->get('title')->getData(),我可以看到表单已正确填写但仍未通过验证,当我执行$this->getFormErrors($form) 时,我只会得到一个空数组。
知道如何调试这个问题吗?
【问题讨论】:
标签: php json symfony fosrestbundle