The Blog

Form Builder with Ajax Posted on

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, Symfony2. Bookmark the permalink.

One thought on “Form Builder with Ajax

  1. Jedrzejczyk says:

    I have bookmarked xfloyd.net it’s awesome

Please Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *



CAPTCHA
Change the CAPTCHA code Speak the CAPTCHA code