public function handle(FormInterface $form, Request $request) { $form->handleRequest($request); if (!$form->isValid()) { return false; } $data = $form->getData(); if ($form->isSubmitted()) { $user = $this->userManager->findUserByEmail($data['email']); if (is_null($user)) { $form->addError(new FormError($this->translator->trans('security.resetting.request.errors.email_not_found'))); return false; } if ($user->isPasswordRequestNonExpired($this->tokenTll)) { $form->addError(new FormError($this->translator->trans('security.resetting.request.errors.password_already_requested'))); return false; } if ($user->getConfirmationToken() === null) { $user->setConfirmationToken($this->tokenGenerator->generateToken()); } $user->setPasswordRequestedAt(new \DateTime()); $this->userManager->resettingRequest($user); } return true; }
public function validate(FormInterface $form) { if (!$form->isSynchronized()) { $form->addError(new FormError('The value is invalid')); } if (count($form->getExtraData()) > 0) { $form->addError(new FormError('This form should not contain extra fields')); } if ($form->isRoot() && isset($_SERVER['CONTENT_LENGTH'])) { $length = (int) $_SERVER['CONTENT_LENGTH']; $max = trim(ini_get('post_max_size')); switch (strtolower(substr($max, -1))) { // The 'G' modifier is available since PHP 5.1.0 case 'g': $max *= 1024; case 'm': $max *= 1024; case 'k': $max *= 1024; } if ($length > $max) { $form->addError(new FormError('The uploaded file was too large. Please try to upload a smaller file')); } } }
/** * Process form * * @param EmailTemplate $entity * * @return bool True on successful processing, false otherwise */ public function process(EmailTemplate $entity) { // always use default locale during template edit in order to allow update of default locale $entity->setLocale($this->defaultLocale); if ($entity->getId()) { // refresh translations $this->manager->refresh($entity); } $this->form->setData($entity); if (in_array($this->request->getMethod(), array('POST', 'PUT'))) { // deny to modify system templates if ($entity->getIsSystem() && !$entity->getIsEditable()) { $this->form->addError(new FormError($this->translator->trans('oro.email.handler.attempt_save_system_template'))); return false; } $this->form->submit($this->request); if ($this->form->isValid()) { // mark an email template creating by an user as editable if (!$entity->getId()) { $entity->setIsEditable(true); } $this->manager->persist($entity); $this->manager->flush(); return true; } } return false; }
/** * Prepare & process form * * @author Jeremie Samson <*****@*****.**> * * @return bool */ public function process() { if ($this->request->isMethod('POST')) { $this->form->handleRequest($this->request); if ($this->form->isValid()) { /** @var ModelUserRole $model */ $model = $this->form->getData(); if (!$model->getUser() || !$model->getRole()) { $this->form->addError(new FormError('Missing parameter(s)')); } /** @var User $user */ $user = $this->em->getRepository('UserBundle:User')->find($model->getUser()); /** @var Post $role */ $role = $this->em->getRepository('FaucondorBundle:Post')->find($model->getRole()); if (!$user) { $this->form->get('user')->addError(new FormError('User with id ' . $model->getUser() . ' not found ')); } if (!$role) { $this->form->get('role')->addError(new FormError('Role with id ' . $model->getRole() . ' not found ')); } $this->onSuccess($user, $role); return true; } } return false; }
/** * Prepare & process form * * @author Jeremie Samson <*****@*****.**> * * @return bool */ public function process() { if ($this->request->isMethod('POST')) { $this->form->handleRequest($this->request); if ($this->form->isValid()) { /** @var ModelUser $user */ $user = $this->form->getData(); if (!$user->getFirstname() || !$user->getLastname() || !$user->getEmailGalaxy() || !$user->getSection()) { $this->form->addError(new FormError('Missing parameter(s)')); } else { if (!filter_var($user->getEmail(), FILTER_VALIDATE_EMAIL) || !filter_var($user->getEmailGalaxy(), FILTER_VALIDATE_EMAIL)) { $error = new FormError('email invalid'); if (!filter_var($user->getEmail(), FILTER_VALIDATE_EMAIL)) { $this->form->get('email')->addError($error); } if (!filter_var($user->getEmailGalaxy(), FILTER_VALIDATE_EMAIL)) { $this->form->get('emailGalaxy')->addError($error); } } else { $section_id = $this->em->getRepository('FaucondorBundle:Section')->find($user->getSection()); $section_code = $this->em->getRepository('FaucondorBundle:Section')->findOneBy(array("code" => $user->getSection())); if (!$section_id && !$section_code) { $this->form->get('section')->addError(new FormError('Section with id ' . $user->getSection() . ' not found')); } else { /** @var Section $section */ $section = $section_id ? $section_id : $section_code; $this->onSuccess($user, $section); return true; } } } } } return false; }
public function validate(Form\FormInterface $form) { $discountAmounts = false; foreach ($form->get('discountAmounts')->getData() as $currency => $amount) { if ($amount) { $discountAmounts = true; break; } } if ($form->get('percentage')->getData() && $discountAmounts) { $form->addError(new Form\FormError('Please only fill in either a percentage OR a fixed discount.')); } elseif (!$form->get('percentage')->getData() && !$discountAmounts && false === $form->get('freeShipping')->getData()) { $form->addError(new Form\FormError('Neither a percentage discount, nor a fixed discount amount, nor free shipping have been added to this discount.')); } }
/** * {@inheritdoc} */ public function handleRequest(FormInterface $form, $request = null) { if (null !== $request) { throw new UnexpectedTypeException($request, 'null'); } $name = $form->getName(); $method = $form->getConfig()->getMethod(); if ($method !== self::getRequestMethod()) { return; } // For request methods that must not have a request body we fetch data // from the query string. Otherwise we look for data in the request body. if ('GET' === $method || 'HEAD' === $method || 'TRACE' === $method) { if ('' === $name) { $data = $_GET; } else { // Don't submit GET requests if the form's name does not exist // in the request if (!isset($_GET[$name])) { return; } $data = $_GET[$name]; } } else { // Mark the form with an error if the uploaded size was too large // This is done here and not in FormValidator because $_POST is // empty when that error occurs. Hence the form is never submitted. if ($this->serverParams->hasPostMaxSizeBeenExceeded()) { // Submit the form, but don't clear the default values $form->submit(null, false); $form->addError(new FormError($form->getConfig()->getOption('post_max_size_message'), null, array('{{ max }}' => $this->serverParams->getNormalizedIniPostMaxSize()))); return; } $fixedFiles = array(); foreach ($_FILES as $fileKey => $file) { $fixedFiles[$fileKey] = self::stripEmptyFiles(self::fixPhpFilesArray($file)); } if ('' === $name) { $params = $_POST; $files = $fixedFiles; } elseif (array_key_exists($name, $_POST) || array_key_exists($name, $fixedFiles)) { $default = $form->getConfig()->getCompound() ? array() : null; $params = array_key_exists($name, $_POST) ? $_POST[$name] : $default; $files = array_key_exists($name, $fixedFiles) ? $fixedFiles[$name] : $default; } else { // Don't submit the form if it is not present in the request return; } if (is_array($params) && is_array($files)) { $data = array_replace_recursive($params, $files); } else { $data = $params ?: $files; } } // Don't auto-submit the form unless at least one field is present. if ('' === $name && count(array_intersect_key($data, $form->all())) <= 0) { return; } $form->submit($data, 'PATCH' !== $method); }
/** * Bind all errors from ApiClientException $e to $form. * * You can override mapping between parameters in ApiClientException::getError * and parameters in FormInterface by giving a $map. * If string association is not enough, you can use a callable to * return a sub-form: * * ->translate($form, $e, array( * 'password' => function($form) { return $form->get('rawPassword')->get('first'); }, * 'foo' => 'bar', * )) * * @param FormInterface $form The form * @param ApiClientException $e The exception * @param string[]|callable[] $map The mapping between api parameters and form parameters * * @return FormInterface The form */ public function translate(FormInterface $form, ApiClientException $e, array $map = array()) { if (!$e->getError()) { $form->addError(new FormError($e->getMessage())); return $form; } foreach ($e->getError()->getEntityBodyParameters() as $parameterName => $messages) { $widget = $form; if (array_key_exists($parameterName, $map)) { if (is_callable($map[$parameterName])) { $widget = $map[$parameterName]($form); if (!$widget instanceof FormInterface) { throw new \LogicException(sprintf('The callable ("$map[%s]") should return a FormInterface', $parameterName)); } } else { $widget = $form->get($map[$parameterName]); } } elseif ($form->has($parameterName)) { $widget = $form->get($parameterName); } foreach ($messages as $message) { if (null === $widget->getParent()) { $widget->addError(new FormError(sprintf('%s: %s', $parameterName, $message))); } else { $widget->addError(new FormError($message)); } } } return $form; }
/** * Adds an error to the field. * * @see FormInterface */ public function addError(FormError $error) { if ($this->parent && $this->errorBubbling) { $this->parent->addError($error); } else { $this->errors[] = $error; } }
/** * Process form * * @param Email $model * @return bool True on successful processing, false otherwise */ public function process(Email $model) { $this->form->setData($model); if (in_array($this->request->getMethod(), ['POST', 'PUT'])) { $this->form->submit($this->request); if ($this->form->isValid()) { try { $this->emailProcessor->process($model); return true; } catch (\Exception $ex) { $this->logger->error('Email sending failed.', ['exception' => $ex]); $this->form->addError(new FormError($ex->getMessage())); } } } return false; }
/** * {@inheritdoc} */ public function handleRequest(FormInterface $form, $request = null) { if (!$request instanceof Request) { throw new UnexpectedTypeException($request, 'Symfony\\Component\\HttpFoundation\\Request'); } $name = $form->getName(); $method = $form->getConfig()->getMethod(); if ($method !== $request->getMethod()) { return; } // For request methods that must not have a request body we fetch data // from the query string. Otherwise we look for data in the request body. if ('GET' === $method || 'HEAD' === $method || 'TRACE' === $method) { if ('' === $name) { $data = $request->query->all(); } else { // Don't submit GET requests if the form's name does not exist // in the request if (!$request->query->has($name)) { return; } $data = $request->query->get($name); } } else { // Mark the form with an error if the uploaded size was too large // This is done here and not in FormValidator because $_POST is // empty when that error occurs. Hence the form is never submitted. $contentLength = $this->serverParams->getContentLength(); $maxContentLength = $this->serverParams->getPostMaxSize(); if (!empty($maxContentLength) && $contentLength > $maxContentLength) { // Submit the form, but don't clear the default values $form->submit(null, false); $form->addError(new FormError($form->getConfig()->getOption('post_max_size_message'), null, array('{{ max }}' => $this->serverParams->getNormalizedIniPostMaxSize()))); return; } if ('' === $name) { $params = $request->request->all(); $files = $request->files->all(); } elseif ($request->request->has($name) || $request->files->has($name)) { $default = $form->getConfig()->getCompound() ? array() : null; $params = $request->request->get($name, $default); $files = $request->files->get($name, $default); } else { // Don't submit the form if it is not present in the request return; } if (is_array($params) && is_array($files)) { $data = array_replace_recursive($params, $files); } else { $data = $params ?: $files; } } // Don't auto-submit the form unless at least one field is present. if ('' === $name && count(array_intersect_key($data, $form->all())) <= 0) { return; } $form->submit($data, 'PATCH' !== $method); }
/** * {@inheritdoc} */ public function addError(FormError $error) { if ($this->parent && $this->config->getErrorBubbling()) { $this->parent->addError($error); } else { $this->errors[] = $error; } return $this; }
/** * @param $form * @param $message * @return JsonResponse */ private function errorResponse(Request $request, FormInterface $form, $message) { $form->addError(new FormError($message)); if ($request->isXmlHttpRequest()) { return new JsonResponse(['message' => $message, 'form' => $this->renderView('VivaitTaskstackCommunicatorBundle:HelpPanel:form.html.twig', ['form' => $form->createView()])], 400); } else { return $this->pageResponse($form); } }
private function updateUserAndForm(User &$user, FormInterface &$form, UserService $userService) { $cyrillicName = $userService->transliterate($user->getLiteralUsername()); if ($this->isAllreadyExists($cyrillicName)) { $errorMessage = $this->get('translator')->trans('fos_user.username.already_used', [], 'validators'); $form->addError(new FormError($errorMessage)); } else { $user->setName($cyrillicName); } }
/** * Process form * * @param User $entity * * @return bool True on successful processing, false otherwise */ public function process(User $entity) { if (in_array($this->request->getMethod(), ['POST', 'PUT'])) { $this->form->submit($this->request); if ($this->form->isValid()) { $entity->setPlainPassword($this->form->get('password')->getData()); $entity->setPasswordChangedAt(new \DateTime()); try { $this->mailerProcessor->sendChangePasswordEmail($entity); } catch (\Exception $e) { $this->form->addError(new FormError($this->translator->trans('oro.email.handler.unable_to_send_email'))); $this->logger->error('Email sending failed.', ['exception' => $e]); return false; } $this->userManager->updateUser($entity); return true; } } return false; }
/** * Validate Marketing List. * * @param MarketingList $marketingList * @return bool */ protected function isValid(MarketingList $marketingList) { $errors = $this->validator->validate($marketingList->getSegment(), array('marketing_list')); if (count($errors) > 0) { /** @var ConstraintViolationInterface $error */ foreach ($errors as $error) { $this->form->addError(new FormError($error->getMessage(), $error->getMessageTemplate(), $error->getMessageParameters(), $error->getMessagePluralization())); } } return $this->form->isValid(); }
public function validate(FormInterface $form) { $code = $form->getData(); $excepted_code = $this->getExceptedCode(); if (!($code && $excepted_code && is_string($code) && is_string($excepted_code) && $this->niceize($code) == $this->niceize($excepted_code))) { $form->addError(new FormError('Bad code value')); } $this->session->remove($this->key); if ($this->session->has($this->key . '_fingerprint')) { $this->session->remove($this->key . '_fingerprint'); } }
public function validate(FormInterface $form) { $code = $form->getData(); $expectedCode = $this->getExpectedCode(); if (!($code && is_string($code) && ($this->compare($code, $expectedCode) || $this->compare($code, $this->bypassCode)))) { $form->addError(new FormError($this->invalidMessage)); } $this->session->remove($this->key); if ($this->session->has($this->key . '_fingerprint')) { $this->session->remove($this->key . '_fingerprint'); } }
/** * {@inheritdoc} */ public function validate(FormInterface $form) { $error = ''; $request = $this->request->request; $server = $this->request->server; $datas = array('privatekey' => $this->privateKey, 'challenge' => $request->get('recaptcha_challenge_field'), 'response' => $request->get('recaptcha_response_field'), 'remoteip' => $server->get('REMOTE_ADDR')); if (empty($datas['challenge']) || empty($datas['response'])) { $error = 'The captcha is not valid.'; } if (true !== ($answer = $this->check($datas, $form->getAttribute('option_validator')))) { $error = sprintf('Unable to check the captcha from the server. (%s)', $answer); } if (!empty($error)) { $form->addError(new FormError($error)); } }
public function create(FormInterface $form, Request $request) { $form->handleRequest($request); if (!$form->isValid()) { return false; } $entity = $form->getData(); if ($form->isSubmitted()) { if (!is_null($this->manager->checkUniqueEmail($entity->getUser()->getEmail()))) { $form->addError(new FormError('Email ja cadastrado!')); return false; } } $this->manager->create($entity); return true; }
/** * Process form * * @param Email $model * @return bool True on successful processing, false otherwise */ public function process(Email $model) { if ($this->request->getMethod() === 'GET') { $this->initModel($model); } $this->form->setData($model); if (in_array($this->request->getMethod(), array('POST', 'PUT'))) { $this->form->submit($this->request); if ($this->form->isValid()) { try { $this->emailProcessor->process($model); return true; } catch (\Exception $ex) { $this->logger->error('Email sending failed.', array('exception' => $ex)); $this->form->addError(new FormError($this->translator->trans('oro.email.handler.unable_to_send_email'))); } } } return false; }
/** * Process form * * @param Email $model * @return bool True on successful processing, false otherwise */ public function process(Email $model) { $result = false; if ($this->request->getMethod() === 'GET') { $this->initModel($model); } $this->form->setData($model); if (in_array($this->request->getMethod(), array('POST', 'PUT'))) { $this->form->submit($this->request); if ($this->form->isValid()) { try { $messageDate = new \DateTime('now', new \DateTimeZone('UTC')); $message = $this->mailer->createMessage(); $message->setDate($messageDate->getTimestamp()); $message->setFrom($this->getAddresses($model->getFrom())); $message->setTo($this->getAddresses($model->getTo())); $message->setSubject($model->getSubject()); $message->setBody($model->getBody(), 'text/plain'); $sent = $this->mailer->send($message); if (!$sent) { throw new \Swift_SwiftException('An email was not delivered.'); } $origin = $this->em->getRepository('OroEmailBundle:InternalEmailOrigin')->findOneBy(array('name' => InternalEmailOrigin::BAP)); $this->emailEntityBuilder->setOrigin($origin); $email = $this->emailEntityBuilder->email($model->getSubject(), $model->getFrom(), $model->getTo(), $messageDate, $messageDate, $messageDate); $email->setFolder($origin->getFolder(EmailFolder::SENT)); $emailBody = $this->emailEntityBuilder->body($model->getBody(), false, true); $email->setEmailBody($emailBody); $this->emailEntityBuilder->getBatch()->persist($this->em); $this->em->flush(); $result = true; } catch (\Exception $ex) { $this->logger->error('Email sending failed.', array('exception' => $ex)); $this->form->addError(new FormError($this->translator->trans('oro.email.handler.unable_to_send_email'))); } } } return $result; }
/** * @param FormInterface $form * @param string $message * @param array $messageParameters */ protected function addFormError(FormInterface $form, $message, array $messageParameters = []) { $message = $this->translator->trans($message, $messageParameters); $form->addError(new FormError($message)); }
/** * Convert a comma-separated string into an array of models * @param string $string * @param FormInterface $form A form to write errors into * @return Player[] */ private function stringToModels($string, $form) { // Convert the comma-separated list of players the user gave us into an // array $players = explode(',', $string); // Remove all the whitespace and duplicate entries $players = array_map('trim', $players); $players = array_unique($players); $models = array(); foreach ($players as $player) { try { $model = $this->listUsernames ? $this->usernameToModel($player) : $this->idToModel($player); if ($model) { if (!$this->multiple) { return $model; } if ($this->include && $model->getId() == $this->include->getId()) { // The caller has explicitly asked to include this player, // so we just ignore any entries the user gave us to prevent // duplications continue; } $models[] = $model; } } catch (InvalidNameException $e) { $form->addError(new FormError($e->getMessage())); } } if ($this->include) { $models[] = $this->include; } return $models; }
private function applyErrorsToForm(FormInterface $form, Result $result) { $ex = $result->getPluginException(); $globalErrors = $ex->getGlobalErrors(); $dataErrors = $ex->getDataErrors(); // add a generic error message if (!$dataErrors && !$globalErrors) { $form->addError(new FormError('form.error.invalid_payment_instruction')); return; } foreach ($globalErrors as $error) { $form->addError(new FormError($error)); } foreach ($dataErrors as $field => $error) { $form->get($field)->addError(new FormError($error)); } }
private function applyErrorsToForm(FormInterface $form, Result $result) { $ex = $result->getPluginException(); $globalErrors = $ex->getGlobalErrors(); $dataErrors = $ex->getDataErrors(); // add a generic error message if (!$dataErrors && !$globalErrors) { $form->addError(new FormError('form.error.invalid_payment_instruction')); return; } foreach ($globalErrors as $error) { $form->addError(new FormError($error)); } foreach ($dataErrors as $path => $error) { $path = explode('.', $path); $field = $form; do { $field = $field->get(array_shift($path)); } while ($path); $field->addError(new FormError($error)); } }
/** * {@inheritdoc} */ public function mapViolation(ConstraintViolation $violation, FormInterface $form, $allowNonSynchronized = false) { $this->allowNonSynchronized = $allowNonSynchronized; $violationPath = null; $relativePath = null; $match = false; // Don't create a ViolationPath instance for empty property paths if (strlen($violation->getPropertyPath()) > 0) { $violationPath = new ViolationPath($violation->getPropertyPath()); $relativePath = $this->reconstructPath($violationPath, $form); } // This case happens if the violation path is empty and thus // the violation should be mapped to the root form if (null === $violationPath) { $this->scope = $form; } // In general, mapping happens from the root form to the leaf forms // First, the rules of the root form are applied to determine // the subsequent descendant. The rules of this descendant are then // applied to find the next and so on, until we have found the // most specific form that matches the violation. // If any of the forms found in this process is not synchronized, // mapping is aborted. Non-synchronized forms could not reverse // transform the value entered by the user, thus any further violations // caused by the (invalid) reverse transformed value should be // ignored. if (null !== $relativePath) { // Set the scope to the root of the relative path // This root will usually be $form. If the path contains // an unmapped form though, the last unmapped form found // will be the root of the path. $this->setScope($relativePath->getRoot()); $it = new PropertyPathIterator($relativePath); while ($this->isValidScope() && null !== ($child = $this->matchChild($it))) { $this->setScope($child); $it->next(); $match = true; } } // This case happens if an error happened in the data under a // virtual form that does not match any of the children of // the virtual form. if (null !== $violationPath && !$match) { // If we could not map the error to anything more specific // than the root element, map it to the innermost directly // mapped form of the violation path // e.g. "children[foo].children[bar].data.baz" // Here the innermost directly mapped child is "bar" $it = new ViolationPathIterator($violationPath); // The overhead of setScope() is not needed anymore here $this->scope = $form; while ($this->isValidScope() && $it->valid() && $it->mapsForm()) { if (!$this->scope->has($it->current())) { // Break if we find a reference to a non-existing child break; } $this->scope = $this->scope->get($it->current()); $it->next(); } } // Follow dot rules until we have the final target $mapping = $this->scope->getConfig()->getOption('error_mapping'); while ($this->isValidScope() && isset($mapping['.'])) { $dotRule = new MappingRule($this->scope, '.', $mapping['.']); $this->scope = $dotRule->getTarget(); $mapping = $this->scope->getConfig()->getOption('error_mapping'); } // Only add the error if the form is synchronized if ($this->isValidScope()) { $this->scope->addError(new FormError($violation->getMessageTemplate(), $violation->getMessageParameters(), $violation->getMessagePluralization())); } }
/** * Mark the form with an error if the uploaded size was too large * * This is done here and not in FormValidator because $_POST is * empty when that error occurs. Hence the form is never submitted. * * @param FormInterface $form * @return boolean */ private function isUploadedSizeValid(FormInterface $form) { $contentLength = $this->serverParams->getContentLength(); $maxContentLength = $this->serverParams->getPostMaxSize(); if (!empty($maxContentLength) && $contentLength > $maxContentLength) { // Submit the form, but don't clear the default values $form->submit(null, false); $form->addError(new FormError($form->getConfig()->getOption('post_max_size_message'), null, array('{{ max }}' => $this->serverParams->getNormalizedIniPostMaxSize()))); return false; } return true; }