Last active
August 29, 2015 14:11
-
-
Save wimvds/b105f7e7ae8b8580153b to your computer and use it in GitHub Desktop.
Validate form fields without submitting data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private function validateForm(Form $form, $entity, $groups = array('submission')) | |
{ | |
$errors = $this->get('validator')->validate($entity, $groups, true, true); | |
foreach ($errors as $error) { | |
$propertyPath = $error->getPropertyPath(); | |
if (strpos($propertyPath, '[') !== false || strpos($propertyPath, '.') !== false) { | |
/** | |
* Very dirty form field parser | |
* | |
* teamMember[0].role is converted to teamMember.0.role | |
* | |
* Then this string is exploded to get an array ['teamMember', 0, 'role'] | |
* | |
* Then we recursively iterate over the fields in the form, to get to the field where the error should | |
* be added. | |
* | |
* So for teamMember[0].role it will return : | |
* $formField = $form->get('teamMember)->get('0')->getRole(); | |
* | |
* Which would be the role property of the first team member defined ... | |
*/ | |
$propertyPath = str_replace('[', '.', $propertyPath); | |
$propertyPath = str_replace(']', '', $propertyPath); | |
$propertyPath = explode('.', $propertyPath); | |
// Get first field | |
$fieldName = array_shift($propertyPath); | |
$formField = $form->get($fieldName); | |
// Loop over rest ... | |
foreach ($propertyPath as $field) { | |
$formField = $formField->get($field); | |
} | |
$formField->addError(new FormError($error->getMessage())); | |
} else { | |
$form->get($propertyPath)->addError(new FormError($error->getMessage())); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment