I want to create a webservice to which I submit a form, and in case of errors, returns a jason encoded list that tells me which field is wrong.
我想创建一个webservice,我向它提交一个表单,如果出现错误,返回一个jason编码的列表,该列表告诉我哪个字段是错误的。
currently I only get a list of error messages but not an html id or a name of the fields with errors
目前,我只得到一个错误消息列表,但没有一个html id或带有错误的字段名
here's my current code
这是我当前的代码
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;
}
this will give me a response like
这会给我一个类似的回答
{
"status":400,
"errorMsg":"Bad Request",
"errorReport":{
"Task cannot be blank",
"Task date needs to be within the month"
}
}
but what I really want is something like
但我真正想要的是
{
"status":400,
"errorMsg":"Bad Request",
"errorReport":{
"taskfield" : "Task cannot be blank",
"taskdatefield" : "Task date needs to be within the month"
}
}
How can I achieve that?
我怎么才能做到呢?
4 个解决方案
#1
16
I am using this, it works quiet well:
我正在使用这个,它运行得很好:
/**
* 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;
}
#2
15
I've finally found the solution to this problem here, it only needed a small fix to comply to latest symfony changes and it worked like a charm:
我终于在这里找到了这个问题的解决方案,它只需要一个小的修正就可以满足最新的symfony变化,它像一个魅力:
The fix consists in replacing line 33
修复在于替换第33行
if (count($child->getIterator()) > 0) {
with
与
if (count($child->getIterator()) > 0 && ($child instanceof \Symfony\Component\Form\Form)) {
because, with the introduction in symfony of Form\Button, a type mismatch will occur in serialize function which is expecting always an instance of Form\Form.
因为,随着表单\按钮的symfony的引入,串行化函数将出现类型不匹配,而串行化函数总是期望表单\表单的实例。
You can register it as a service:
你可将其注册为服务:
services:
form_serializer:
class: Wooshii\SiteBundle\FormErrorsSerializer
and then use it as the author suggest:
然后按照作者的建议使用它:
$errors = $this->get('form_serializer')->serializeFormErrors($form, true, true);
#3
4
This does the trick for me
这对我有好处。
$errors = [];
foreach ($form->getErrors(true, true) as $formError) {
$errors[] = $formError->getMessage();
}
#4
1
PHP has associative arrays, meanwhile JS has 2 different data structures : object and arrays.
PHP有关联数组,而JS有两个不同的数据结构:对象和数组。
The JSON you want to obtain is not legal and should be :
您想要获得的JSON是不合法的,应该是:
{
"status":400,
"errorMsg":"Bad Request",
"errorReport": {
"taskfield" : "Task cannot be blank",
"taskdatefield" : "Task date needs to be within the month"
}
}
So you may want to do something like this to build your collection :
所以你可能想做这样的事情来建立你的收藏:
$errorCollection = array();
foreach($errors as $error){
$errorCollection[$error->getId()] = $error->getMessage();
}
(assuming the getId() method exist on $error objects)
(假设getId()方法存在于$error对象上)
#1
16
I am using this, it works quiet well:
我正在使用这个,它运行得很好:
/**
* 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;
}
#2
15
I've finally found the solution to this problem here, it only needed a small fix to comply to latest symfony changes and it worked like a charm:
我终于在这里找到了这个问题的解决方案,它只需要一个小的修正就可以满足最新的symfony变化,它像一个魅力:
The fix consists in replacing line 33
修复在于替换第33行
if (count($child->getIterator()) > 0) {
with
与
if (count($child->getIterator()) > 0 && ($child instanceof \Symfony\Component\Form\Form)) {
because, with the introduction in symfony of Form\Button, a type mismatch will occur in serialize function which is expecting always an instance of Form\Form.
因为,随着表单\按钮的symfony的引入,串行化函数将出现类型不匹配,而串行化函数总是期望表单\表单的实例。
You can register it as a service:
你可将其注册为服务:
services:
form_serializer:
class: Wooshii\SiteBundle\FormErrorsSerializer
and then use it as the author suggest:
然后按照作者的建议使用它:
$errors = $this->get('form_serializer')->serializeFormErrors($form, true, true);
#3
4
This does the trick for me
这对我有好处。
$errors = [];
foreach ($form->getErrors(true, true) as $formError) {
$errors[] = $formError->getMessage();
}
#4
1
PHP has associative arrays, meanwhile JS has 2 different data structures : object and arrays.
PHP有关联数组,而JS有两个不同的数据结构:对象和数组。
The JSON you want to obtain is not legal and should be :
您想要获得的JSON是不合法的,应该是:
{
"status":400,
"errorMsg":"Bad Request",
"errorReport": {
"taskfield" : "Task cannot be blank",
"taskdatefield" : "Task date needs to be within the month"
}
}
So you may want to do something like this to build your collection :
所以你可能想做这样的事情来建立你的收藏:
$errorCollection = array();
foreach($errors as $error){
$errorCollection[$error->getId()] = $error->getMessage();
}
(assuming the getId() method exist on $error objects)
(假设getId()方法存在于$error对象上)