Showing posts with label symfony2 forms. Show all posts
Showing posts with label symfony2 forms. Show all posts

Thursday, March 14, 2013

Symfony2: How to find out the form errors

How to find out the form errors in Symfony2. Just add that code to your Controller:
if ($form->isValid()) {
...

} else {
    foreach($form->getChildren() as $child) {
        foreach( $child->getErrors() as $error) {
            print($error->getMessageTemplate()); 
        }
    }
}
It takes into consideration only the errors of the form fields. If you want to check errors of the form too, add that:
foreach ($form->getErrors() as $error) {
    print($error->getMessageTemplate());
}

Monday, December 10, 2012

How to found out extra fields in Symfony2 form?


If you encounter this error message while working with Symfony2 forms, follow my advice.
This form should not contain extra fields.
This way to find out the fields that are considered "extra" is very simple. I use the code quite frequently. Here it is:
$data = $request->request->all();

print("REQUEST DATA<br/>");
foreach ($data as $k => $d) {
    print("$k: <pre>"); print_r($d); print("</pre>");
}

$children = $form->all();

print("<br/>FORM CHILDREN<br/>");
foreach ($children as $ch) {
    print($ch->getName() . "<br/>");
}

$data = array_diff_key($data, $children);
//$data contains now extra fields

print("<br/>DIFF DATA<br/>");
foreach ($data as $k => $d) {
    print("$k: <pre>"); print_r($d); print("</pre>");
}
...
$form->bind($data);
Have a nice day!