/** * @dataProvider getValidInputs */ public function testSubmit($submitted, $expected) { $this->sut->submit($submitted); $msg = ''; if (!$this->sut->isValid()) { $msg = print_r($this->sut->getErrors(), true); foreach ($this->sut->all() as $child) { $msg .= "\n" . print_r($child->getErrors(), true); } } $this->assertTrue($this->sut->isValid(), $msg); $this->assertEquals($expected, $this->sut->getData()); }
/** * Returns an array with form fields errors * * @param FormInterface $form * @param bool|false $useLabels * @param array $errors * @return array */ public function getErrorMessages(FormInterface $form, $useLabels = false, $errors = array()) { if ($form->count() > 0) { foreach ($form->all() as $child) { if (!$child->isValid()) { $errors = $this->getErrorMessages($child, $useLabels, $errors); } } } foreach ($form->getErrors() as $error) { if ($useLabels) { $fieldNameData = $this->getErrorFormLabel($form); } else { $fieldNameData = $this->getErrorFormId($form); } $fieldName = $fieldNameData; if ($useLabels) { /** * @ignore */ $fieldName = $this->translator->trans($fieldNameData['label'], array(), $fieldNameData['domain']); } $errors[$fieldName] = $error->getMessage(); } return $errors; }
/** * @param FormInterface $form * @return int|false ID of inserted data OR success */ public function registerUser(FormInterface $form) { if ($this->encoder == null) { throw new \Exception("Encoder can not be NULL! Do you added the Encoder by using add_encoder() ??"); } if ($form->isValid()) { $data = $form->getData(); $entity = new GBUserEntry(); $entity->setNick($data['nick']); $entity->setPass($this->encodePassword($entity, $data['password'])); try { $this->emanager->persist($entity); $this->emanager->flush(); return $entity->getUid(); } catch (\Exception $ex) { $this->errormessage = $ex->getMessage(); if (strstr($this->errormessage, "Duplicate")) { $this->errormessage = "Dieser Nick wird bereits verwendet!"; } return false; } } elseif ($form->isSubmitted()) { $this->errormessage = (string) $form->getErrors(true); } return false; }
public function buildView(FormView $view, FormInterface $form) { if ($view->hasParent()) { $parentId = $view->getParent()->get('id'); $parentName = $view->getParent()->get('name'); $id = sprintf('%s_%s', $parentId, $form->getName()); $name = sprintf('%s[%s]', $parentName, $form->getName()); } else { $id = $form->getName(); $name = $form->getName(); } $view->set('form', $view); $view->set('id', $id); $view->set('name', $name); $view->set('errors', $form->getErrors()); $view->set('value', $form->getClientData()); $view->set('read_only', $form->isReadOnly()); $view->set('required', $form->isRequired()); $view->set('max_length', $form->getAttribute('max_length')); $view->set('size', null); $view->set('label', $form->getAttribute('label')); $view->set('multipart', false); $view->set('attr', array()); $types = array(); foreach (array_reverse((array) $form->getTypes()) as $type) { $types[] = $type->getName(); } $view->set('types', $types); }
/** * {@inheritdoc} */ public function buildView(FormView $view, FormInterface $form) { $name = $form->getName(); if ($view->hasParent()) { if ('' === $name) { throw new FormException('Form node with empty name can be used only as root form node.'); } if ('' !== ($parentFullName = $view->getParent()->get('full_name'))) { $id = sprintf('%s_%s', $view->getParent()->get('id'), $name); $fullName = sprintf('%s[%s]', $parentFullName, $name); } else { $id = $name; $fullName = $name; } } else { // If this form node have empty name, set id to `form` // to avoid rendering `id=""` in html structure $id = $name ?: 'form'; $fullName = $name; } $types = array(); foreach ($form->getTypes() as $type) { $types[] = $type->getName(); } $view->set('form', $view)->set('id', $id)->set('name', $name)->set('full_name', $fullName)->set('errors', $form->getErrors())->set('value', $form->getClientData())->set('read_only', $form->isReadOnly())->set('required', $form->isRequired())->set('max_length', $form->getAttribute('max_length'))->set('pattern', $form->getAttribute('pattern'))->set('size', null)->set('label', $form->getAttribute('label'))->set('multipart', false)->set('attr', $form->getAttribute('attr'))->set('types', $types)->set('translation_domain', $form->getAttribute('translation_domain')); }
/** * @param FormInterface $form * @param array $results * * @return array */ private function formatFormErrors(FormInterface $form, &$results = array()) { /* * first check if there are any errors bound for this element */ $errors = $form->getErrors(); if (count($errors)) { $messages = []; foreach ($errors as $error) { if ($error instanceof FormError) { $messages[] = $this->translator->trans($error->getMessage(), $error->getMessageParameters(), 'validators'); } $results[] = ['property_path' => $this->formatPropertyPath($error), 'message' => join(', ', $messages)]; } } /* * Then, check if there are any children. If yes, then parse them */ $children = $form->all(); if (count($children)) { foreach ($children as $child) { if ($child instanceof FormInterface) { $this->formatFormErrors($child, $results); } } } return $results; }
/** * {@inheritdoc} */ public function buildView(FormView $view, FormInterface $form) { $name = $form->getName(); $readOnly = $form->getAttribute('read_only'); if ($view->hasParent()) { if ('' === $name) { throw new FormException('Form node with empty name can be used only as root form node.'); } if ('' !== ($parentFullName = $view->getParent()->get('full_name'))) { $id = sprintf('%s_%s', $view->getParent()->get('id'), $name); $fullName = sprintf('%s[%s]', $parentFullName, $name); } else { $id = $name; $fullName = $name; } // Complex fields are read-only if themselves or their parent is. $readOnly = $readOnly || $view->getParent()->get('read_only'); } else { $id = $name; $fullName = $name; // Strip leading underscores and digits. These are allowed in // form names, but not in HTML4 ID attributes. // http://www.w3.org/TR/html401/struct/global.html#adef-id $id = ltrim($id, '_0123456789'); } $types = array(); foreach ($form->getTypes() as $type) { $types[] = $type->getName(); } $view->set('form', $view)->set('id', $id)->set('name', $name)->set('full_name', $fullName)->set('read_only', $readOnly)->set('errors', $form->getErrors())->set('value', $form->getClientData())->set('disabled', $form->isDisabled())->set('required', $form->isRequired())->set('max_length', $form->getAttribute('max_length'))->set('pattern', $form->getAttribute('pattern'))->set('size', null)->set('label', $form->getAttribute('label'))->set('multipart', false)->set('attr', $form->getAttribute('attr'))->set('types', $types)->set('translation_domain', $form->getAttribute('translation_domain')); }
/** * {@inheritdoc} */ public function extractSubmittedData(FormInterface $form) { $data = array('submitted_data' => array('norm' => $this->valueExporter->exportValue($form->getNormData())), 'errors' => array()); if ($form->getViewData() !== $form->getNormData()) { $data['submitted_data']['view'] = $this->valueExporter->exportValue($form->getViewData()); } if ($form->getData() !== $form->getNormData()) { $data['submitted_data']['model'] = $this->valueExporter->exportValue($form->getData()); } foreach ($form->getErrors() as $error) { $errorData = array('message' => $error->getMessage(), 'origin' => is_object($error->getOrigin()) ? spl_object_hash($error->getOrigin()) : null, 'trace' => array()); $cause = $error->getCause(); while (null !== $cause) { if ($cause instanceof ConstraintViolationInterface) { $errorData['trace'][] = array('class' => $this->valueExporter->exportValue(get_class($cause)), 'root' => $this->valueExporter->exportValue($cause->getRoot()), 'path' => $this->valueExporter->exportValue($cause->getPropertyPath()), 'value' => $this->valueExporter->exportValue($cause->getInvalidValue())); $cause = method_exists($cause, 'getCause') ? $cause->getCause() : null; continue; } if ($cause instanceof \Exception) { $errorData['trace'][] = array('class' => $this->valueExporter->exportValue(get_class($cause)), 'message' => $this->valueExporter->exportValue($cause->getMessage())); $cause = $cause->getPrevious(); continue; } $errorData['trace'][] = $cause; break; } $data['errors'][] = $errorData; } $data['synchronized'] = $this->valueExporter->exportValue($form->isSynchronized()); return $data; }
/** * This does the actual job. Method travels through all levels of form recursively and gathers errors. * @param FormInterface $form * @param array &$results * * @return FormError[] */ private function realParseErrors(FormInterface $form, array &$results) { /* * first check if there are any errors bound for this element */ $errors = $form->getErrors(); if (count($errors)) { $config = $form->getConfig(); $name = $form->getName(); $label = $config->getOption('label'); $translation = $this->getTranslationDomain($form); /* * If a label isn't explicitly set, use humanized field name */ if (empty($label)) { $label = ucfirst(trim(strtolower(preg_replace(['/([A-Z])/', '/[_\\s]+/'], ['_$1', ' '], $name)))); } $results[] = array('name' => $name, 'label' => $label, 'errors' => $errors); } /* * Then, check if there are any children. If yes, then parse them */ $children = $form->all(); if (count($children)) { foreach ($children as $child) { if ($child instanceof FormInterface) { $this->realParseErrors($child, $results); } } } return $results; }
protected function getErrors(FormInterface $form) { $messages = []; foreach ($form->getErrors() as $message) { $messages[] = $message->getMessage(); } return $messages; }
public function __construct(FormInterface $form) { $message = []; foreach ($form->getErrors(true, true) as $error) { $message[] = sprintf('[%s] %s (%s)', $error->getOrigin() ? $error->getOrigin()->getPropertyPath() : '-', $error->getMessage(), json_encode($error->getMessageParameters())); } parent::__construct(implode("\n", $message)); }
/** * Gets an associative array with all the errors in a form and it's children. * * @param FormInterface $form * * @return array */ public static function getFormErrors(FormInterface $form) { $errors = array(); foreach ($form->getErrors() as $error) { $errors['_form_'][] = $error->getMessage(); } self::addChildErrors($form, $errors); return $errors; }
public function __construct(FormInterface $form) { $this->name = $form->getName(); foreach ($form->getErrors() as $error) { $this->errors[] = $error; } foreach ($form->all() as $child) { $this->children[] = new static($child); } }
/** * Returns the form error mapping for easier marking of form errors in * javascript handler code. * * @param FormInterface $form * * @return array */ protected function getFormErrorMapping(FormInterface $form) { $allErrors = array(); $formName = $form->getName(); $fieldPrefix = !empty($formName) ? "{$formName}_" : ""; foreach ($form->all() as $children) { $errors = $children->getErrors(); if (!empty($errors)) { $allErrors["{$fieldPrefix}{$children->getName()}"] = array_map(function (FormError $error) { return $error->getMessage(); }, is_array($errors) ? $errors : iterator_to_array($errors)); } } if ($form->getErrors()->count() > 0) { foreach ($form->getErrors() as $topLevelError) { $allErrors["__global"][] = $topLevelError->getMessage(); } } return $allErrors; }
/** * @param FormView $view * @param FormInterface $form * @param array $options */ public function buildView(FormView $view, FormInterface $form, array $options) { $errors = array(); $fieldErrors = $form->getErrors(); foreach ($fieldErrors as $fieldError) { $errors[] = $this->translator->trans($fieldError->getMessageTemplate(), $fieldError->getMessageParameters(), 'validators'); } if ($errors) { $view->vars['attr']['data-error'] = implode("<br>", $errors); } }
/** * Validates the provided information against a form. * * @param FormInterface $form form to check * @param DocumentModel $model Model to determine entity to be used * @param FormDataMapperInterface $formDataMapper Mapps the entity to form fields * @param string $jsonContent json data * * @throws ValidationException * @return mixed */ public function checkForm(FormInterface $form, DocumentModel $model, FormDataMapperInterface $formDataMapper, $jsonContent) { $document = $formDataMapper->convertToFormData($jsonContent, $model->getEntityClass()); $form->submit($document, true); if (!$form->isValid()) { throw new ValidationException($form->getErrors(true)); } else { $record = $form->getData(); } return $record; }
/** * @param FormInterface $form * @return array */ protected function getFormErrorMessages(FormInterface $form) { $errors = []; foreach ($form->getErrors() as $error) { if ($form->isRoot()) { $errors[] = $this->toErrorArray($error); } else { $errors[] = $this->toErrorArray($error, $form); } } return $errors; }
/** * @param FormInterface $form * @return string All form's error messages concatenated into one string */ protected function getFormErrors(FormInterface $form) { $errors = ''; /** @var FormError $error */ foreach ($form->getErrors() as $error) { $errors .= $error->getMessage() . "\n"; } foreach ($form->all() as $key => $child) { if ($err = $this->getFormErrors($child)) { $errors .= sprintf("%s: %s\n", $key, $err); } } return $errors; }
/** * @param FormInterface $form * @return \Symfony\Component\Form\FormError[] */ protected function getAllErrors(FormInterface $form) { $errors = $form->getErrors(); $children = $form->all(); if (!count($errors) && !count($children)) { return null; } $section = ['field' => $form->getName()]; if (count($errors)) { $section['errors'] = array_map(function (FormError $error) { return ['message' => $error->getMessage(), 'parameters' => $error->getMessageParameters()]; }, iterator_to_array($form->getErrors())); } if (count($children)) { $section['children'] = array_values(array_filter(array_map(function (FormInterface $field) { return $this->getAllErrors($field); }, $form->all()))); if (!count($errors) && !count($section['children'])) { return null; } } return $section; }
public function formErrorsToArray(FormInterface $form) { $errors = array(); foreach ($form->getErrors() as $error) { $errors[] = $error->getMessage(); } /* @var $child \Symfony\Component\Form\Form */ foreach ($form->all() as $child) { if (!$child->isValid()) { $errors[$child->getName()] = $this->formErrorsToArray($child); } } return $errors; }
/** * Helper for extracting errors from form child elements */ public function getFormErrors(FormInterface $form) { $errors = array(); foreach ($form->all() as $field) { $childErrors = $this->getFormErrors($field); if ($childErrors) { $errors[$field->getName()] = $childErrors; } } foreach ($form->getErrors() as $error) { $errors['errors'] = $error->getMessage(); } return $errors; }
/** * {@inheritdoc} */ public function extractSubmittedData(FormInterface $form) { $data = array('submitted_data' => array('norm' => $this->valueExporter->exportValue($form->getNormData())), 'errors' => array()); if ($form->getViewData() !== $form->getNormData()) { $data['submitted_data']['view'] = $this->valueExporter->exportValue($form->getViewData()); } if ($form->getData() !== $form->getNormData()) { $data['submitted_data']['model'] = $this->valueExporter->exportValue($form->getData()); } foreach ($form->getErrors() as $error) { $data['errors'][] = array('message' => $error->getMessage()); } $data['synchronized'] = $this->valueExporter->exportValue($form->isSynchronized()); return $data; }
/** * Collects errors from form * * @param FormInterface $form * @return array */ public 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; }
public static function errors(FormInterface $form) : array { $errors = []; foreach ($form->getErrors() as $error) { $errors[$form->getName()][] = $error->getMessage(); } foreach ($form as $child) { if (!$child->isValid()) { foreach ($child->getErrors() as $error) { $errors[$child->getName()][] = $error->getMessage(); } } } return $errors; }
function it_does_not_handle_form_when_the_form_is_invalid(Request $request, FormFactoryInterface $formFactory, FormBuilderInterface $formBuilder, FormInterface $form, FormError $formError, FormInterface $child) { $formFactory->createNamedBuilder('', 'kreta_dummy_type', null, [])->shouldBeCalled()->willReturn($formBuilder); $formBuilder->getForm()->shouldBeCalled()->willReturn($form); $request->isMethod('POST')->shouldBeCalled()->willReturn(true); $form->handleRequest($request)->shouldBeCalled()->willReturn($form); $form->isValid()->shouldBeCalled()->willReturn(false); $form->getErrors()->shouldBeCalled()->willReturn([$formError]); $formError->getMessage()->shouldBeCalled()->willReturn('Form error'); $form->all()->shouldBeCalled()->willReturn([$child]); $child->isValid()->shouldBeCalled()->willReturn(false); $child->getName()->shouldBeCalled()->willReturn('Child form error'); $child->getErrors()->shouldBeCalled()->willReturn([]); $child->all()->shouldBeCalled()->willReturn([]); $this->shouldThrow(new InvalidFormException(['Form error', 'Child form error' => []]))->during('handleForm', [$request]); }
/** * @param FormInterface $form * @return array */ protected function getErrorMessages(FormInterface $form) { $errors = array(); foreach ($form->getErrors() as $key => $error) { $errors[] = $this->translator->trans($error->getMessage()); } foreach ($form->all() as $child) { if (!$child->isValid()) { $childErrors = $this->getErrorMessages($child); foreach ($childErrors as $childError) { $errors[] = $childError; } } } return $errors; }
/** * Collect form errors. * * @param FormInterface $form * * @return array */ protected function getFormErrors(FormInterface $form) { $errors = []; foreach ($form->getErrors() as $error) { $errors[] = $error->getMessage(); } foreach ($form->all() as $childForm) { if ($childForm instanceof FormInterface) { $childErrors = $this->getFormErrors($childForm); if ($childErrors) { $errors[$childForm->getName()] = $childErrors; } } } return $errors; }
/** * Gets all the errors in the current $field and adds them to $_errors, to * get all errors in the form and its children recursively. * Also adds display name to error-message. * * @param FormInterface $field Field to get Errors from */ protected function _getErrors(FormInterface $field) { if ($field->getConfig()->getOption('label')) { $label = $this->_translator->trans($field->getConfig()->getOption('label')); } else { $label = ucfirst(trim(strtolower(preg_replace(array('/([A-Z])/', '/[_\\s]+/'), array('_$1', ' '), $field->getName())))); } $fieldErrors = array(); foreach ($field->getErrors() as $error) { // don't show label if error is on the whole form $fieldErrors[] = $field->isRoot() ? $error->getMessage() : $label . ': ' . $error->getMessage(); } $this->_errors[] = $fieldErrors; foreach ($field->all() as $child) { $this->_getErrors($child); } }
/** * {@inheritdoc} */ public function buildView(FormViewInterface $view, FormInterface $form, array $options) { $name = $form->getName(); $blockName = $options['block_name'] ?: $form->getName(); $readOnly = $options['read_only']; $translationDomain = $options['translation_domain']; if ($view->hasParent()) { if ('' === $name) { throw new FormException('Form node with empty name can be used only as root form node.'); } $parentView = $view->getParent(); if ('' !== ($parentFullName = $parentView->getVar('full_name'))) { $id = sprintf('%s_%s', $parentView->getVar('id'), $name); $fullName = sprintf('%s[%s]', $parentFullName, $name); $fullBlockName = sprintf('%s_%s', $parentView->getVar('full_block_name'), $blockName); } else { $id = $name; $fullName = $name; $fullBlockName = '_' . $blockName; } // Complex fields are read-only if they themselves or their parents are. if (!$readOnly) { $readOnly = $parentView->getVar('read_only'); } if (!$translationDomain) { $translationDomain = $parentView->getVar('translation_domain'); } } else { $id = $name; $fullName = $name; $fullBlockName = '_' . $blockName; // Strip leading underscores and digits. These are allowed in // form names, but not in HTML4 ID attributes. // http://www.w3.org/TR/html401/struct/global.html#adef-id $id = ltrim($id, '_0123456789'); } $types = array(); for ($type = $form->getConfig()->getType(); null !== $type; $type = $type->getParent()) { array_unshift($types, $type->getName()); } if (!$translationDomain) { $translationDomain = 'messages'; } $view->addVars(array('form' => $view, 'id' => $id, 'name' => $name, 'full_name' => $fullName, 'full_block_name' => $fullBlockName, 'read_only' => $readOnly, 'errors' => $form->getErrors(), 'valid' => $form->isBound() ? $form->isValid() : true, 'value' => $form->getViewData(), 'disabled' => $form->isDisabled(), 'required' => $form->isRequired(), 'max_length' => $options['max_length'], 'pattern' => $options['pattern'], 'size' => null, 'label' => $options['label'], 'multipart' => false, 'attr' => $options['attr'], 'label_attr' => $options['label_attr'], 'compound' => $form->getConfig()->getCompound(), 'types' => $types, 'translation_domain' => $translationDomain)); }
/** * @param \Symfony\Component\Form\FormInterface $form * * @return \Symfony\Component\HttpFoundation\RedirectResponse */ protected function submitCommentForm(Request $request, FormInterface $form) { $formData = $form->getData(); $idSalesOrder = $formData[CommentTransfer::FK_SALES_ORDER]; if ($form->isValid()) { $commentTransfer = new CommentTransfer(); $commentTransfer->setMessage($formData[CommentTransfer::MESSAGE]); $commentTransfer->setFkSalesOrder($idSalesOrder); $currentUserTransfer = $this->getFactory()->getUserFacade()->getCurrentUser(); $commentTransfer->setUsername($currentUserTransfer->getFirstName() . ' ' . $currentUserTransfer->getLastName()); $this->getFacade()->saveComment($commentTransfer); $this->addSuccessMessage('Comment successfully added'); return $this->redirectResponse($request->headers->get('referer')); } else { foreach ($form->getErrors(true) as $error) { $this->addErrorMessage($error->getMessage()); } } }