【发布时间】:2021-12-23 09:31:14
【问题描述】:
我正在寻找一种在 ajax 中发送一个以 JSON 格式返回验证错误的表单后在 jQuery 中显示验证错误的方法。
我的代码适用于简单的表单,但对于更复杂的表单会出现困难,尤其是对于包含关联数据输入的表单。
例如:
这是一个包含输入文件和用于编写字幕的相关数据的表单:
// Articles/edit.php
$this->Form->create($article);
echo $this->Form->control('title');
echo $this->Form->control('photos.0.legend');
echo $this->Form->control('photos.1.legend');
$this->Form->end();
我将 ajax 表单发布到我的 ArticlesController 的编辑方法中,如下所示:
// ArticlesController.php
public function edit($id)
{
$article = $this->Articles->findById($id)->firstOrFail();
if ($this->request->is(['post', 'put'])) {
$article = $this->Articles->patchEntity($article, $this->request->getData());
if ($this->Articles->save($article)) {
$redirection = ['action' => 'index'];
if ($this->request->is('ajax')) {
die(json_encode(['error' => false, 'redirection' => Router::url($redirection)]));
}
return $this->redirect($redirection);
}
else {
if ($this->request->is('ajax')) {
die(json_encode(['error' => true, 'validationErrors' => $article->getErrors()]));
}
}
}
$this->set(compact('article'));
}
这是 JSON 中验证错误的返回:
{
"error": true,
"validationErrors": {
"title": {
"_empty": "The title please."
},
"photos": { // validation errors are nested
"1": {
"legend": {
"_empty": "The legend please."
}
}
}
}
}
这是我试图显示验证错误的方式:
// Articles/edit.php
$('form')
.fileupload({ // It sends the form in ajax
dataType: 'json',
// [...]
done: function (e, data) {
var responseJSON = data.jqXHR.responseJSON;
if (!responseJSON.error) { // There's no error => redirect
window.location = responseJSON.redirection;
}
else { // The form contains validation errors
$.each(responseJSON.validationErrors, function (field, errors) {
displayFieldErrors(field, errors);
});
}
},
// [...]
});
// Display validation errors in a field
function displayFieldErrors(field, errors)
{
var fieldId = field.replace(/_/, '-');
var input = $("#" + fieldId);
var errorMessage = '';
$.each(errors, function (key, message) {
errorMessage = errorMessage + message + '<br>';
});
input.parents('.input').addClass('error');
input.after('<div class="error-message">' + errorMessage + '</div>');
}
问题是关联数据字段的验证错误是嵌套的(例如photos),那么如何获取输入的id呢?
谁能帮我找到我的jQuery函数displayFieldErrors()的正确实现?
【问题讨论】:
标签: php cakephp-4.x