Sim*_*est 25 php forms ajax json symfony
我想创建一个我提交表单的web服务,如果有错误,返回一个jason编码列表,告诉我哪个字段是错误的.
目前我只获取错误消息列表,但不是html id或有错误字段的名称
这是我目前的代码
public function saveAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$form = $this->createForm(new TaskType(), new Task());
$form->handleRequest($request);
$task = $form->getData();
if ($form->isValid()) {
$em->persist($task);
$em->flush();
$array = array( 'status' => 201, 'msg' => 'Task Created');
} else {
$errors = $form->getErrors(true, true);
$errorCollection = array();
foreach($errors as $error){
$errorCollection[] = $error->getMessage();
}
$array = array( 'status' => 400, 'errorMsg' => 'Bad Request', 'errorReport' => $errorCollection); // data to return via JSON
}
$response = new Response( json_encode( $array ) );
$response->headers->set( 'Content-Type', 'application/json' );
return $response;
}
Run Code Online (Sandbox Code Playgroud)
这会给我一个回应
{
"status":400,
"errorMsg":"Bad Request",
"errorReport":{
"Task cannot be blank",
"Task date needs to be within the month"
}
}
Run Code Online (Sandbox Code Playgroud)
但我真正想要的是像
{
"status":400,
"errorMsg":"Bad Request",
"errorReport":{
"taskfield" : "Task cannot be blank",
"taskdatefield" : "Task date needs to be within the month"
}
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
COi*_*Oil 24
我正在使用它,它安静得很好:
/**
* List all errors of a given bound form.
*
* @param Form $form
*
* @return array
*/
protected function getFormErrors(Form $form)
{
$errors = array();
// Global
foreach ($form->getErrors() as $error) {
$errors[$form->getName()][] = $error->getMessage();
}
// Fields
foreach ($form as $child /** @var Form $child */) {
if (!$child->isValid()) {
foreach ($child->getErrors() as $error) {
$errors[$child->getName()][] = $error->getMessage();
}
}
}
return $errors;
}
Run Code Online (Sandbox Code Playgroud)
Sim*_*est 16
我终于在这里找到了这个问题的解决方案,它只需要一个小的修复来遵守最新的symfony更改,它就像一个魅力:
该修复包括替换第33行
if (count($child->getIterator()) > 0) {
Run Code Online (Sandbox Code Playgroud)
同
if (count($child->getIterator()) > 0 && ($child instanceof \Symfony\Component\Form\Form)) {
Run Code Online (Sandbox Code Playgroud)
因为,在Form\Button的symfony中引入,序列化函数中会出现类型不匹配,它总是期望Form\Form的一个实例.
您可以将其注册为服务:
services:
form_serializer:
class: Wooshii\SiteBundle\FormErrorsSerializer
Run Code Online (Sandbox Code Playgroud)
然后按照作者的建议使用它:
$errors = $this->get('form_serializer')->serializeFormErrors($form, true, true);
Run Code Online (Sandbox Code Playgroud)
这对我来说很有用
$errors = [];
foreach ($form->getErrors(true, true) as $formError) {
$errors[] = $formError->getMessage();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12534 次 |
| 最近记录: |