Simple code examples on how to use Symfony form builder with Ajax and jquery validators
Symfoyny part:
...
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormInterface;
...
$form->handleRequest($request);
if ($form->isSubmitted()) {
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($empl_pay);
$em->flush();
}
$errors = $this->getErrorsFromForm($form);
return new JsonResponse($errors);
}
...
private function getErrorsFromForm(FormInterface $form)
{
$errors = array();
foreach ($form->getErrors() as $error) {
$errors[] = $error->getMessage();
}
foreach ($form->all() as $childForm) {
if ($childForm instanceof FormInterface) {
if ($childErrors = $this->getErrorsFromForm($childForm)) {
$errors[$childForm->getName()] = $childErrors;
}
}
}
return $errors;
}
Recommended front end using JavaScript parsley:
var $form = $("form[name='form']");
$form.submit(function(e) {
e.preventDefault();
$form.parsley().reset();
var $action = window.location.pathname;
$.post($action, $(this).serialize(), function(data) {
$.each( data, function( key, value ) {
console.log( 'ERROR ' + key + ': ' + value );
$('#form_' + key).parsley().addError('forcederror', {message: value, updateClass: true});
});
});
});
For jQuery validator use this:
errors = { personalid: "Please enter an ID to check" };
$validator.showErrors(errors);
This entry was posted in PHP, Symfony3. Bookmark the permalink.