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.

2 thoughts on “Form Builder with Ajax

  1. Jedrzejczyk says:

    I have bookmarked xfloyd.net it’s awesome

  2. EssayPaper says:

    EssayErudite.com is the web’s leading provider of quality and professional academic writing.
    When it comes to essay writing, an in-depth research is a big deal. Our experienced writers are professional in many fields of knowledge so that they can assist you with virtually any academic task. We deliver papers of different types: essays, theses, book reviews, case studies, etc.
    We have thousands of satisfied customers who have already recommended us to their friends. Why not follow their example and place your order today?

Please Post Your Comments & Reviews

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



CAPTCHA
Change the CAPTCHA codeSpeak the CAPTCHA code