Skip to content

Instantly share code, notes, and snippets.

@wimvds
Last active August 29, 2015 14:11
Show Gist options
  • Save wimvds/b105f7e7ae8b8580153b to your computer and use it in GitHub Desktop.
Save wimvds/b105f7e7ae8b8580153b to your computer and use it in GitHub Desktop.
Validate form fields without submitting data
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