public function isValid(\Symfony\Component\Form\Form &$form) { $viewData = $form->getViewData(); //pour le champ hidden allFieldsAreThere de Revision if (!is_object($viewData) && 'allFieldsAreThere' == $form->getName()) { return true; } if ($viewData instanceof Revision) { /** @var DataField $dataField */ $dataField = $viewData->getDatafield(); } elseif ($viewData instanceof DataField) { /** @var DataField $dataField */ $dataField = $viewData; } else { throw new \Exception("Unforeseen type of viewData"); } if ($dataField->getFieldType() !== null && $dataField->getFieldType()->getType() !== null) { $dataFieldTypeClassName = $dataField->getFieldType()->getType(); /** @var DataFieldType $dataFieldType */ $dataFieldType = new $dataFieldTypeClassName(); } $isValid = true; if (isset($dataFieldType) && $dataFieldType->isContainer()) { //If datafield is container or type is null => Container => Recursive $formChildren = $form->all(); foreach ($formChildren as $child) { if ($child instanceof \Symfony\Component\Form\Form) { $tempIsValid = $this->isValid($child); //Recursive $isValid = $isValid && $tempIsValid; } } if (!$isValid) { $form->addError(new FormError("At least one child is not valid!")); } } // $isValid = $isValid && $dataFieldType->isValid($dataField); if (isset($dataFieldType) && !$dataFieldType->isValid($dataField)) { $isValid = false; $form->addError(new FormError("This Field is not valid! " . $dataField->getMessages()[0])); } return $isValid; }
/** * Validate the given request with the given rules. * * @param \Symfony\Component\Form\Form $form * @param \Illuminate\Http\Request $request * @param array $rules * @param array $messages * @return void */ public function validateForm(Form $form, Request $request, array $rules, array $messages = array()) { $data = $form->getName() ? $request->get($form->getName()) : $request->all(); $validator = $this->getValidationFactory()->make($data, $rules, $messages); if ($validator->fails()) { $this->throwValidationException($request, $validator); } }
/** * @param Form $form The form * @param string $namePrefix The field name prefix (concatenation of parents names). * @return array The form errors, as an array */ private function getErrorsArray(Form $form, $namePrefix = '') { $formName = $namePrefix ? sprintf('%s[%s]', $namePrefix, $form->getName()) : $form->getName(); $errors = array(); foreach ($form->getErrors() as $error) { if (!isset($errors[$formName])) { $errors[$formName] = array(); } $errors[$formName][] = $error->getMessage(); } return $errors; }
public function serializeFormToXml(XmlSerializationVisitor $visitor, Form $form, array $type) { if (null === $visitor->document) { $visitor->document = $visitor->createDocument(null, null, false); $visitor->document->appendChild($formNode = $visitor->document->createElement('form')); $visitor->setCurrentNode($formNode); } else { $visitor->getCurrentNode()->appendChild($formNode = $visitor->document->createElement('form')); } $formNode->setAttribute('name', $form->getName()); $formNode->appendChild($errorsNode = $visitor->document->createElement('errors')); foreach ($form->getErrors() as $error) { $errorNode = $visitor->document->createElement('entry'); $errorNode->appendChild($this->serializeFormErrorToXml($visitor, $error, array())); $errorsNode->appendChild($errorNode); } foreach ($form->all() as $child) { if ($child instanceof Form) { if (null !== ($node = $this->serializeFormToXml($visitor, $child, array()))) { $formNode->appendChild($node); } } } return $formNode; }
/** * @param Form $form * @param string $path * * @return Form */ public static function &getForm(Form &$form, $path) { $keys = array_filter(preg_split('#[\\.\\[\\]]+#', $path), function ($val) { return $val; }); $prefix = substr($path, 0, strlen($form->getName()) + 1); if ($form->getName() . '[' === $prefix || $form->getName() . '.' === $prefix) { array_shift($keys); } $val = $form; foreach ($keys as $k) { $val = static::_get($val, $k); } /* @var $val Form */ return $val; }
/** * @param Form $form * @param Request $request * @param callable $preValidation callback to be called before the form is validated * @throws \Mcfedr\JsonFormBundle\Exception\InvalidFormHttpException * @throws \Mcfedr\JsonFormBundle\Exception\MissingFormHttpException * @throws \Mcfedr\JsonFormBundle\Exception\InvalidJsonHttpException */ protected function handleJsonForm(Form $form, Request $request, callable $preValidation = null) { $bodyJson = $request->getContent(); if (!($body = json_decode($bodyJson, true))) { throw new InvalidJsonHttpException(); } if (!isset($body[$form->getName()])) { throw new MissingFormHttpException($form); } $form->submit($body[$form->getName()]); if ($preValidation) { $preValidation(); } if (!$form->isValid()) { throw new InvalidFormHttpException($form); } }
/** * Resolve input and get files from request * @return array */ private function resolveInput() { if ($this->secure_upload === false) { return $this->rq->files->all(); } $parts = $this->rq->files->get($this->form->getName()); return $parts[$this->input_name]; }
/** * @param Form $form * @param Request $request * @param array $options * * @return bool */ public function handle(Form $form, Request $request, array $options = null) { if (!$request->isMethod('POST')) { return false; } $form->bind($request->request->get($form->getName())); if (!$form->isBound() || !$form->isValid()) { return false; } $this->usermanager->createUser($form->getData()->getUser()); return true; }
protected function getErrorMessages(Form $form) { $errors = array(); foreach ($form->getErrors() as $key => $error) { $errors[$key] = $error->getMessage(); } foreach ($form->all() as $child) { if (!$child->isValid()) { $key = sprintf('%s[%s]', $form->getName(), $child->getName()); $errors[$key] = $this->getErrorMessages($child); } } return $errors; }
/** * @param Request $request * @param Form $articleForm * @return mixed * @throws \Exception */ protected function upload(Request $request, Form $form, $width, $height) { $files = $request->files->get($form->getName()); if (!empty($files['image'])) { $path = __DIR__ . self::UPLOAD_DIR; $filename = $files['image']->getClientOriginalName(); $filepath = $path . $filename; $files['image']->move($path, $filename); chmod($filepath, 0755); //ToDo: renommer les images en ajoutant uniqid() Image::open($filepath)->zoomCrop($width, $height, "#346A85", "center", "center")->save($filepath); return $filename; } else { return false; } }
/** * @param Form $form * @return array */ protected function getFormErrors(Form $form) { $errors = array(); // Global foreach ($form->getErrors() as $error) { $errors[$form->getName()][] = $error->getMessage(); } // Fields foreach ($form as $child) { if (!$child->isValid()) { foreach ($child->getErrors() as $error) { $errors[$child->getName()][] = $error->getMessage(); } } } return $errors; }
public static function getAllErrors(Form $form, $parent_prefix = '') { $id = $parent_prefix . ($parent_prefix ? '_' : '') . $form->getName(); $errors = array($id . '_errors' => array()); foreach ($form->getErrors() as $error) { $errors[$id . '_errors'][] = array('error' => self::formatErrors($error)); } if (!count($errors[$id . '_errors'])) { unset($errors[$id . '_errors']); } foreach ($form->getChildren() as $child) { if ($_errors = self::getAllErrors($child, $id)) { $errors = array_merge($errors, $_errors); } } if (count($errors)) { return $errors; } else { return false; } }
/** * Removes submitted errant form fields * @param Symfony\Component\Form\Form $form * @param Symfony\Component\HttpFoundation\Request $request * @param Array $collections */ public function sanitizeCollections(Form &$form, Request &$request, Array $collections) { $formName = $form->getName(); $submission = $request->request->get($formName); foreach ($collections as $collection => $fields) { $total = count($submission[$collection])+1; for ($i = 0; $i < $total; $i++) { foreach ($fields as $field) { if (empty($submission[$collection][$i][$field])) { unset($submission[$collection][$i]); break; } } } } $request->request->set($formName, $submission); }
/** * Handle a POST from user edit or first user creation. * * @param Request $request * @param Form $form A Symfony form * @param boolean $firstuser If this is a first user set up * * @return Entity\Users|false */ private function validateUserForm(Request $request, Form $form, $firstuser = false) { $form->submit($request->get($form->getName())); if (!$form->isValid()) { return false; } $userEntity = new Entity\Users($form->getData()); $userEntity->setUsername($this->app['slugify']->slugify($userEntity->getUsername())); if (!$firstuser) { $userEntity->setRoles($this->users()->filterManipulatableRoles($userEntity->getId(), $userEntity->getRoles())); } if ($this->getRepository('Bolt\\Storage\\Entity\\Users')->save($userEntity)) { $this->flashes()->success(Trans::__('page.edit-users.message.user-saved', ['%user%' => $userEntity->getDisplayname()])); $this->notifyUserSave($request, $userEntity->getDisplayname(), $userEntity->getEmail(), $firstuser); } else { $this->flashes()->error(Trans::__('page.edit-users.message.saving-user', ['%user%' => $userEntity->getDisplayname()])); } return $userEntity; }
/** * Handle a POST from user edit or first user creation. * * @param \Silex\Application $app * @param Symfony\Component\Form\Form $form A Symfony form * @param boolean $firstuser If this is a first user set up * * @return array|boolean An array of user elements, otherwise false */ private function validateUserForm(Application $app, Form $form, $firstuser = false) { $form->submit($app['request']->get($form->getName())); if ($form->isValid()) { $user = $form->getData(); if ($firstuser) { $user['roles'] = array(Permissions::ROLE_ROOT); } else { $id = isset($user['id']) ? $user['id'] : null; $user['roles'] = $app['users']->filterManipulatableRoles($id, $user['roles']); } $res = $app['users']->saveUser($user); if ($user['id']) { $app['logger.system']->info(Trans::__('page.edit-users.log.user-updated', array('%user%' => $user['displayname'])), array('event' => 'security')); } else { $app['logger.system']->info(Trans::__('page.edit-users.log.user-added', array('%user%' => $user['displayname'])), array('event' => 'security')); if ($firstuser) { // Create a welcome email $mailhtml = $app['render']->render('email/firstuser.twig', array('sitename' => $app['config']->get('general/sitename')))->getContent(); try { // Send a welcome email $message = $app['mailer']->createMessage('message')->setSubject(Trans::__('New Bolt site has been set up'))->setFrom(array($app['config']->get('general/mailoptions/senderMail', $user['email']) => $app['config']->get('general/mailoptions/senderName', $app['config']->get('general/sitename'))))->setTo(array($user['email'] => $user['displayname']))->setBody(strip_tags($mailhtml))->addPart($mailhtml, 'text/html'); $app['mailer']->send($message); } catch (\Exception $e) { // Sending message failed. What else can we do, sending with snailmail? $app['logger.system']->error("The 'mailoptions' need to be set in app/config/config.yml", array('event' => 'config')); } } } if ($res) { $app['session']->getFlashBag()->add('success', Trans::__('page.edit-users.message.user-saved', array('%user%' => $user['displayname']))); } else { $app['session']->getFlashBag()->add('error', Trans::__('page.edit-users.message.saving-user', array('%user%' => $user['displayname']))); } return $user; } return false; }
/** * Get all form errors * @param Form $form * @return array */ private function getErrors(Form $form) { $errors = array(); $children = $form->getIterator(); /** @var Form $child */ foreach ($children as $child) { if (!$child->isValid()) { $errors[$form->getName() . '[' . $child->getName() . ']'] = $this->getErrors($child); } } foreach ($form->getErrors() as $key => $error) { $errors[] = $error->getMessage(); } return $errors; }
/** * Generate first form item from request. * * @param Request $request * @param Form $form * @param string $field * @param mixed $data * * @return array */ public function firstItem(Request $request, Form $form, $field, $data) { $item = []; $content = json_decode($request->getContent()); if (is_object($content) && isset($content->{$form->getName()}) && isset($content->{$form->getName()}->{$field})) { $key = key($content->{$form->getName()}->{$field}); if (!is_null($key)) { $item[$field][$key] = $data; } } return $item; }
/** * Checks if the form child given is an instance of SymfonyForm, and returns name if so. Otherwise it casts the * param to a string and returns that * * @param string | SymfonyForm $child Name of child, or instance of child field * * @return string */ protected function _getChildName($child) { if ($child instanceof SymfonyForm) { return $child->getName(); } return (string) $child; }
public function __construct(Form $form) { parent::__construct(400, 'Missing ' . $form->getName()); }
/** * @param string $form_name the name of the form * @param \Symfony\Component\Validator\Constraints\Collection $validationCollection the collection of validators * @return mixed array of rules to be used by jquery validation */ public function getRules(Form $form, Collection $validationCollection) { $rules = array(); foreach ($validationCollection->fields as $field_key => $field_validators) { foreach ($field_validators as $field_validator) { if ($field_validator instanceof \Symfony\Component\Validator\Constraints\Email) { $rules = $this->addRule($form->getName(), $rules, $field_key, 'email'); } if ($field_validator instanceof \Symfony\Component\Validator\Constraints\NotBlank) { $rules = $this->addRule($form->getName(), $rules, $field_key, 'required'); } } } return $rules; }
/** * @param Form $form * @param array $metadata * @param string $prefix * * @return array|string */ protected function modelizeForm(Form $form, &$metadata, $prefix = null) { if ($form->getConfig()->getCompound()) { $all = $form->all(); $model = []; foreach ($all as $formField) { /** @var Form $formField */ $model[$formField->getName()] = $this->modelizeForm($formField, $metadata, null === $prefix ? '' : $prefix . ($prefix ? '.' : '') . $form->getName()); } ksort($model); return $model; } else { $value = 'string'; if ($form->getConfig()->getOption('choices')) { $value = array_keys($form->getConfig()->getOption('choices')); $metadata[$prefix . ($prefix ? '.' : '') . $form->getName()] = ['type' => lcfirst(preg_replace('/^api/', '', $form->getConfig()->getType()->getName())), 'constraints' => $this->buildConstraints($form) + [['type' => 'choices', 'vars' => ['values' => $value]]], 'default' => !is_object($form->getConfig()->getOption('empty_data')) ? $form->getConfig()->getOption('empty_data') : null]; } elseif ($form->getConfig()->getOption('type')) { /** @var AbstractType $type */ $type = $this->modelizeForm($form->getConfig()->getOption('type'), $metadata, ($prefix ? '.' : '') . $prefix); unset($type); $metadata[$prefix . ($prefix ? '.' : '') . $form->getName()] = ['type' => lcfirst(preg_replace('/^api/', '', $form->getConfig()->getType()->getName())), 'constraints' => $this->buildConstraints($form), 'default' => !is_object($form->getConfig()->getOption('empty_data')) ? $form->getConfig()->getOption('empty_data') : null]; $value = []; } else { $metadata[$prefix . ($prefix ? '.' : '') . $form->getName()] = ['type' => lcfirst(preg_replace('/^api/', '', $form->getConfig()->getType()->getName())), 'constraints' => $this->buildConstraints($form), 'default' => !is_object($form->getConfig()->getOption('empty_data')) ? $form->getConfig()->getOption('empty_data') : null]; } return $value; } }
/** * @param Request $request * @param Form $form * @return $this */ public function load(Request $request, Form $form) { $this->_load($request, $form->getConfig()->getMethod(), $form->getName()); $form->handleRequest($request); return $this; }
/** * @param Form $form * * @return array */ protected function getValidationData(Form $form) { // If parent has metadata $parent = $form->getParent(); if ($parent && null !== $parent->getConfig()->getDataClass()) { $classMetadata = $metadata = $this->getMetadataFor($parent->getConfig()->getDataClass()); if ($classMetadata->hasMemberMetadatas($form->getName())) { $metadata = $classMetadata->getMemberMetadatas($form->getName()); /** @var PropertyMetadata $item */ foreach ($metadata as $item) { $this->composeValidationData($parentData, $item->getConstraints(), $getters = !empty($item->getters) ? (array) $item->getters : array()); } } } // If has own metadata if (null !== $form->getConfig()->getDataClass()) { $metadata = $this->getMetadataFor($form->getConfig()->getDataClass()); $this->composeValidationData($ownData, $metadata->getConstraints(), $getters = !empty($metadata->getters) ? (array) $metadata->getters : array()); } // If has constraints in a form element $this->composeValidationData($formData, (array) $form->getConfig()->getOption('constraints'), array()); $result = array(); $groups = $this->getValidationGroups($form); if (!empty($parentData)) { $parentData['groups'] = $this->getValidationGroups($parent); $result['parent'] = $parentData; } if (!empty($ownData)) { $ownData['groups'] = $groups; $result['entity'] = $ownData; } if (!empty($formData)) { $formData['groups'] = $groups; $result['form'] = $formData; } return $result; }
/** * Handle the upload POST. * * @param Request $request The Symfony Request * @param Form $form * @param string $namespace The filesystem namespace * @param string $path The path prefix */ private function handleUpload(Request $request, Form $form, $namespace, $path) { $form->submit($request); if (!$form->isValid()) { $this->flashes()->error(Trans::__('general.phrase.file-upload-failed')); return; } $files = $request->files->get($form->getName()); $files = $files['FileUpload']; foreach ($files as $fileToProcess) { $fileToProcess = ['name' => $fileToProcess->getClientOriginalName(), 'tmp_name' => $fileToProcess->getPathName()]; $originalFilename = $fileToProcess['name']; $filename = preg_replace('/[^a-zA-Z0-9_\\.]/', '_', basename($originalFilename)); if ($this->app['filepermissions']->allowedUpload($filename)) { $this->processUpload($namespace, $path, $filename, $fileToProcess); } else { $extensionList = []; foreach ($this->app['filepermissions']->getAllowedUploadExtensions() as $extension) { $extensionList[] = '<code>.' . htmlspecialchars($extension, ENT_QUOTES) . '</code>'; } $extensionList = implode(' ', $extensionList); $this->flashes()->error(Trans::__("File '%file%' could not be uploaded (wrong/disallowed file type). Make sure the file extension is one of the following:", ['%file%' => $filename]) . $extensionList); } } }
/** * Checks to see if the form was cancelled * * @param Form $form * * @return int */ protected function isFormCancelled(Form &$form) { $name = $form->getName(); return $this->request->request->get($name . '[buttons][cancel]', false, true) !== false; }