Berdasarkan jawaban @Jay Seth, saya membuat versi class FormErrors khusus untuk Ajax Forms:
// src/AppBundle/Form/FormErrors.php
namespace AppBundle\Form;
class FormErrors
{
/**
* @param \Symfony\Component\Form\Form $form
*
* @return array $errors
*/
public function getArray(\Symfony\Component\Form\Form $form)
{
return $this->getErrors($form, $form->getName());
}
/**
* @param \Symfony\Component\Form\Form $baseForm
* @param \Symfony\Component\Form\Form $baseFormName
*
* @return array $errors
*/
private function getErrors($baseForm, $baseFormName) {
$errors = array();
if ($baseForm instanceof \Symfony\Component\Form\Form) {
foreach($baseForm->getErrors() as $error) {
$errors[] = array(
"mess" => $error->getMessage(),
"key" => $baseFormName
);
}
foreach ($baseForm->all() as $key => $child) {
if(($child instanceof \Symfony\Component\Form\Form)) {
$cErrors = $this->getErrors($child, $baseFormName . "_" . $child->getName());
$errors = array_merge($errors, $cErrors);
}
}
}
return $errors;
}
}
Penggunaan (misalnya dalam tindakan Anda):
$errors = $this->get('form_errors')->getArray($form);
Versi Symfony: 2.8.4
Contoh respon JSON:
{
"success": false,
"errors": [{
"mess": "error_message",
"key": "RegistrationForm_user_firstname"
}, {
"mess": "error_message",
"key": "RegistrationForm_user_lastname"
}, {
"mess": "error_message",
"key": "RegistrationForm_user_email"
}, {
"mess": "error_message",
"key": "RegistrationForm_user_zipCode"
}, {
"mess": "error_message",
"key": "RegistrationForm_user_password_password"
}, {
"mess": "error_message",
"key": "RegistrationForm_terms"
}, {
"mess": "error_message2",
"key": "RegistrationForm_terms"
}, {
"mess": "error_message",
"key": "RegistrationForm_marketing"
}, {
"mess": "error_message2",
"key": "RegistrationForm_marketing"
}]
}
Objek kesalahan berisi bidang "kunci", yang merupakan id dari elemen DOM masukan, sehingga Anda dapat dengan mudah mengisi pesan kesalahan.
Jika Anda memiliki formulir anak di dalam formulir induk, jangan lupa untuk menambahkan cascade_validation
opsi di dalam formulir induk setDefaults
.