Exemplo n.º 1
0
 /**
  * @param LineItem $lineItem
  *
  * @return bool
  */
 public function process(LineItem $lineItem)
 {
     if (in_array($this->request->getMethod(), ['POST', 'PUT'], true)) {
         /** @var EntityManagerInterface $manager */
         $manager = $this->registry->getManagerForClass('OroB2BShoppingListBundle:LineItem');
         $manager->beginTransaction();
         // handle case for new shopping list creation
         $formName = $this->form->getName();
         $formData = $this->request->request->get($formName, []);
         if (empty($formData['shoppingList']) && !empty($formData['shoppingListLabel'])) {
             $shoppingList = $this->shoppingListManager->createCurrent($formData['shoppingListLabel']);
             $formData['shoppingList'] = $shoppingList->getId();
             $this->request->request->set($formName, $formData);
         }
         $this->form->submit($this->request);
         if ($this->form->isValid()) {
             /** @var LineItemRepository $lineItemRepository */
             $lineItemRepository = $manager->getRepository('OroB2BShoppingListBundle:LineItem');
             $existingLineItem = $lineItemRepository->findDuplicate($lineItem);
             if ($existingLineItem) {
                 $this->updateExistingLineItem($lineItem, $existingLineItem);
             } else {
                 $manager->persist($lineItem);
             }
             $manager->flush();
             $manager->commit();
             return true;
         } else {
             $manager->rollBack();
         }
     }
     return false;
 }
Exemplo n.º 2
0
 /**
  * {@inheritdoc}
  */
 public function buildView(FormView $view, FormInterface $form, array $options)
 {
     $name = $form->getName();
     $blockName = $options['block_name'] ?: $form->getName();
     $translationDomain = $options['translation_domain'];
     if ($view->parent) {
         if ('' !== ($parentFullName = $view->parent->vars['full_name'])) {
             $id = sprintf('%s_%s', $view->parent->vars['id'], $name);
             $fullName = sprintf('%s[%s]', $parentFullName, $name);
             $uniqueBlockPrefix = sprintf('%s_%s', $view->parent->vars['unique_block_prefix'], $blockName);
         } else {
             $id = $name;
             $fullName = $name;
             $uniqueBlockPrefix = '_' . $blockName;
         }
         if (null === $translationDomain) {
             $translationDomain = $view->parent->vars['translation_domain'];
         }
     } else {
         $id = $name;
         $fullName = $name;
         $uniqueBlockPrefix = '_' . $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');
     }
     $blockPrefixes = array();
     for ($type = $form->getConfig()->getType(); null !== $type; $type = $type->getParent()) {
         array_unshift($blockPrefixes, $type->getName());
     }
     $blockPrefixes[] = $uniqueBlockPrefix;
     $view->vars = array_replace($view->vars, array('form' => $view, 'id' => $id, 'name' => $name, 'full_name' => $fullName, 'disabled' => $form->isDisabled(), 'label' => $options['label'], 'multipart' => false, 'attr' => $options['attr'], 'block_prefixes' => $blockPrefixes, 'unique_block_prefix' => $uniqueBlockPrefix, 'translation_domain' => $translationDomain, 'cache_key' => $uniqueBlockPrefix . '_' . $form->getConfig()->getType()->getName()));
 }
Exemplo n.º 3
0
 /**
  * @throws \LogicException
  *
  * @return array
  */
 public function getFormSubmittedData()
 {
     if ('POST' !== $this->request->getMethod()) {
         throw new \LogicException('Unable to fetch submitted data, only POST request supported');
     }
     return $this->request->get($this->form->getName(), []);
 }
Exemplo n.º 4
0
 /**
  * Pass the image URL to the view.
  *
  * @param FormView      $view
  * @param FormInterface $form
  * @param array         $options
  */
 public function buildView(FormView $view, FormInterface $form, array $options)
 {
     $data = $form->getParent()->getData();
     if ($data instanceof ContentSpec) {
         $tmpName = explode('_', $form->getName());
         if (count($tmpName) === 3) {
             $currentFile = null;
             foreach ($data->getTranslations() as $tr) {
                 if ($tr->getLocale() == $tmpName[1] && ($tr->getField() == 'content' || $tr->getField() == 'data')) {
                     $contents = json_decode($tr->getContent(), true);
                     if (isset($contents[$tmpName[2]])) {
                         $currentFile = $contents[$tmpName[2]];
                     }
                 }
             }
         } else {
             $currentFile = $data->getInContent($form->getName());
             if (!$currentFile) {
                 $currentFile = $data->getInData($form->getName());
             }
         }
         if ($currentFile) {
             $currentFileWeb = $this->nyrocms->getHandler($data->getContentHandler())->getUploadDir() . '/' . $currentFile;
             $view->vars['currentFile'] = $currentFileWeb;
             $view->vars['showDelete'] = $options['showDelete'] && is_string($options['showDelete']) ? $options['showDelete'] : false;
         }
     }
 }
Exemplo n.º 5
0
 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);
 }
Exemplo n.º 6
0
 /**
  * @param FormInterface   $form    The form
  * @param FormAction|null $action  The submit action of the form
  * @param string|null     $method  The submit method of the form
  * @param string|null     $enctype The encryption type of the form
  */
 public function __construct(FormInterface $form, FormAction $action = null, $method = null, $enctype = null)
 {
     $this->form = $form;
     $this->action = $action;
     $this->method = $method;
     $this->enctype = $enctype;
     $this->hash = $this->buildHash($this->form->getName(), $action, $method, $enctype);
 }
 /**
  * @param FormView $view
  * @param FormInterface $form
  * @param array $options
  */
 protected function moveCurrentValueToDefaultLocaleValue(FormView $view, FormInterface $form, array $options)
 {
     $file = $view[$form->getName()]->vars['data'];
     $view->vars['label_attr']['data-default-locale-value'] = $this->filePathResolver->fileBasename($file);
     $view->vars['label_attr']['data-default-locale-url'] = $this->filePathResolver->fileUrl($file);
     $view[$form->getName()]->vars['value'] = null;
     $view[$form->getName()]->vars['data'] = null;
     $view[$options['remove_name']]->vars['checked'] = true;
 }
 /**
  * Test build of form with form type
  */
 public function testFormCreate()
 {
     // Assert fields
     $this->assertField('label', 'pim_translatable_field');
     $this->assertField('sort_order', 'hidden');
     // Assert option class
     $this->assertEquals('Pim\\Bundle\\CatalogBundle\\Entity\\AttributeGroup', $this->form->getConfig()->getDataClass());
     // Assert name
     $this->assertEquals('pim_enrich_attribute_group', $this->form->getName());
 }
 /**
  * Test build of form with form type
  */
 public function testFormCreate()
 {
     // Assert fields
     $this->assertField('code', 'text');
     $this->assertField('label', 'pim_translatable_field');
     // Assert option class
     $this->assertEquals('Pim\\Bundle\\CatalogBundle\\Entity\\Category', $this->form->getConfig()->getDataClass());
     // Assert name
     $this->assertEquals('pim_category', $this->form->getName());
 }
Exemplo n.º 10
0
 /**
  * @return FormInterface
  *
  * @throws ErrorMappingException
  */
 public function getTarget()
 {
     $childNames = explode('.', $this->targetPath);
     $target = $this->origin;
     foreach ($childNames as $childName) {
         if (!$target->has($childName)) {
             throw new ErrorMappingException(sprintf('The child "%s" of "%s" mapped by the rule "%s" in "%s" does not exist.', $childName, $target->getName(), $this->targetPath, $this->origin->getName()));
         }
         $target = $target->get($childName);
     }
     return $target;
 }
Exemplo n.º 11
0
 /**
  * @param FormInterface $field
  * @param FormView $view
  */
 protected function updateTooltip(FormInterface $field, FormView $view)
 {
     $parentOptions = $field->getParent()->getConfig()->getOptions();
     $parentClassName = isset($parentOptions['data_class']) ? $parentOptions['data_class'] : null;
     if (!isset($view->vars['tooltip']) && $parentClassName && $this->entityConfigProvider->hasConfig($parentClassName, $field->getName())) {
         $tooltip = $this->entityConfigProvider->getConfig($parentClassName, $field->getName())->get('description');
         //@deprecated 1.9.0:1.11.0 tooltips.*.yml will be removed. Use Resources/translations/messages.*.yml instead
         if ($this->translator->hasTrans($tooltip, self::DEFAULT_TRANSLATE_DOMAIN) || $this->translator->hasTrans($tooltip, self::TOOLTIPS_TRANSLATE_DOMAIN)) {
             $view->vars['tooltip'] = $tooltip;
         }
     }
 }
Exemplo n.º 12
0
 /**
  * {@inheritdoc}
  */
 public function buildView(FormView $view, FormInterface $form, array $options)
 {
     if (!isset($this->buttons[$form->getName()])) {
         return;
     }
     $storedButtons = $this->buttons[$form->getName()];
     if (isset($storedButtons['prepend']) && $storedButtons['prepend'] !== null) {
         $view->vars['input_group_button_prepend'] = $storedButtons['prepend']->getForm()->createView();
     }
     if (isset($storedButtons['append']) && $storedButtons['append'] !== null) {
         $view->vars['input_group_button_append'] = $storedButtons['append']->getForm()->createView();
     }
 }
Exemplo n.º 13
0
 /**
  * {@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'));
 }
Exemplo n.º 14
0
 /**
  * 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;
 }
Exemplo n.º 15
0
 /**
  * {@inheritdoc}
  */
 public function finishView(FormView $view, FormInterface $form, array $options)
 {
     $data = $view->parent->vars['value'];
     if (is_object($data)) {
         $view->vars['grid_url'] = $this->router->generate('oro_entity_relation', ['id' => $data->getId() ? $data->getId() : 0, 'entityName' => str_replace('\\', '_', get_class($data)), 'fieldName' => $form->getName()]);
     }
 }
    public function validate(FormInterface $form)
    {
        if (!$form->isSynchronized()) {
            $form->addError(new FormError(sprintf('The value for "%s" is invalid', $form->getName())));
        }

        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'));
            }
        }
    }
 /**
  * {@inheritdoc}
  */
 public function buildView(FormView $view, FormInterface $form, array $options)
 {
     if (null === ($config = $this->configManager->getEntityConfigByClass($options['class']))) {
         throw new \InvalidArgumentException(sprintf('The configuration of the "%s" entity is not available (this entity is used as the target of the "%s" autocomplete field).', $options['class'], $form->getName()));
     }
     $view->vars['autocomplete_entity_name'] = $config['name'];
 }
 /**
  * Test method related
  */
 public function testFormCreate()
 {
     // Assert default options
     $expectedOptions = array('entity_class' => false, 'field' => false, 'locales' => array('en_US', 'fr_FR'), 'required_locale' => array(), 'translation_class' => false, 'widget' => 'text');
     // Assert options
     $options = $this->form->getConfig()->getOptions();
     $expectedOptions['entity_class'] = self::OPT_ENTITY_CLASS;
     $expectedOptions['field'] = self::OPT_NAME;
     $expectedOptions['translation_class'] = self::OPT_TRANSLATION_CLASS;
     foreach ($expectedOptions as $expectedKey => $expectedValue) {
         $this->assertArrayHasKey($expectedKey, $options);
         $this->assertEquals($expectedValue, $options[$expectedKey]);
     }
     // Assert name
     $this->assertEquals('pim_translatable_field', $this->form->getName());
 }
 /**
  * Disable a field after the form has been created
  *
  * @param FormInterface $field
  */
 protected function disableField(FormInterface $field)
 {
     $config = $field->getConfig();
     $options = $config->getOptions();
     $options['disabled'] = true;
     $field->getParent()->add($field->getName(), $config->getType()->getInnerType(), $options);
 }
Exemplo n.º 20
0
 /**
  * {@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);
 }
Exemplo n.º 21
0
 /**
  * @param \Symfony\Component\Form\FormView $view
  * @param \Symfony\Component\Form\FormInterface $form
  * @param array $options
  */
 public function buildView(FormView $view, FormInterface $form, array $options)
 {
     if ($options['reload'] && !$options['as_url']) {
         throw new \InvalidArgumentException('GregwarCaptcha: The reload option cannot be set without as_url, see the README for more information');
     }
     $sessionKey = sprintf('gcb_%s', $form->getName());
     $isHuman = false;
     if ($options['humanity'] > 0) {
         $humanityKey = sprintf('%s_humanity', $sessionKey);
         if ($this->session->get($humanityKey, 0) > 0) {
             $isHuman = true;
         }
     }
     if ($options['as_url']) {
         $keys = $this->session->get($options['whitelist_key'], array());
         if (!in_array($sessionKey, $keys)) {
             $keys[] = $sessionKey;
         }
         $this->session->set($options['whitelist_key'], $keys);
         $options['session_key'] = $sessionKey;
     }
     $view->vars = array_merge($view->vars, array('captcha_width' => $options['width'], 'captcha_height' => $options['height'], 'reload' => $options['reload'], 'image_id' => uniqid('captcha_'), 'captcha_code' => $this->generator->getCaptchaCode($options), 'value' => '', 'is_human' => $isHuman));
     $persistOptions = array();
     foreach (array('phrase', 'width', 'height', 'distortion', 'length', 'quality', 'background_color', 'text_color') as $key) {
         $persistOptions[$key] = $options[$key];
     }
     $this->session->set($sessionKey, $persistOptions);
 }
Exemplo n.º 22
0
 /**
  * {@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'));
 }
Exemplo n.º 23
0
 /**
  * {@inheritdoc}
  */
 public function buildView(FormView $view, FormInterface $form, array $options)
 {
     $vars = ['configs' => $options['configs']];
     if ($form->getData()) {
         $data = $form->getParent()->getData();
         $fieldConfig = $this->cm->getProvider('extend')->getConfig($data, $form->getName());
         if ($form->getData()) {
             /** @var ConverterInterface|EntitySelectHandler $converter */
             $converter = $options['converter'];
             $result = [];
             if ($converter instanceof EntitySelectHandler) {
                 $converter->initForEntity($fieldConfig->getId()->getClassName(), $fieldConfig->get('target_field'));
             }
             if (isset($options['configs']['multiple']) && $options['configs']['multiple']) {
                 foreach ($form->getData() as $item) {
                     $result[] = $converter->convertItem($item);
                 }
             } else {
                 $result[] = $converter->convertItem($form->getData());
             }
             $vars['attr'] = ['data-selected-data' => json_encode($result)];
         }
     }
     $view->vars = array_replace_recursive($view->vars, $vars);
 }
Exemplo n.º 24
0
 /**
  * {@inheritdoc}
  */
 public function buildView(FormView $view, FormInterface $form, array $options)
 {
     $view->vars['object'] = $form->getParent()->getData();
     if ($options['download_link'] && $view->vars['object']) {
         $view->vars['download_uri'] = $this->storage->resolveUri($form->getParent()->getData(), $form->getName());
     }
 }
Exemplo n.º 25
0
 public function buildView(FormView $view, FormInterface $form, array $options)
 {
     $knockout['enabled'] = $form->getAttribute('knockout');
     if ($knockout['enabled'] === true) {
         $knockout['viewModel'] = array('name' => $form->getName(), 'fields' => $this->buildViewModelFields($form->getChildren()), 'bindings' => $this->buildViewModelBindings($form->getChildren()), 'collections' => $this->getCollections($form->getChildren(), $view));
     }
     $view->set('knockout', $knockout);
 }
 /**
  * @param FormInterface $form
  *
  * @return string
  */
 public static function label(FormInterface $form)
 {
     $label = $form->getConfig()->getOption('label');
     if (!$label) {
         $label = self::humanize($form->getName());
     }
     return $label;
 }
Exemplo n.º 27
0
 public function buildView(FormView $view, FormInterface $form, array $options)
 {
     if (empty($options['render_controller'])) {
         throw new InvalidArgumentException('Ervenytelen controller');
     }
     $view->vars['url'] = $this->router->generate($options['route'], array_merge($options['route_params'], array('name' => $form->getName(), 'formType' => $options['upload_form_type'], 'controller' => empty($options['render_controller']) ? 'null' : $options['render_controller'])));
     $view->vars['size'] = $options['size'];
     $view->vars['has_callback'] = !empty($options['js_upload_complete_callback']) ? 1 : 0;
     $view->vars['js_upload_callback'] = $options['js_upload_complete_callback'];
     $view->vars['types'] = $options['file_types'];
     $view->vars['label'] = $options['btn_label'];
     $view->vars['param_name'] = $this->paramName;
     $view->vars['debug'] = true === $options['debug'] ? 'true' : 'false';
     $view->vars['widget_name'] = $form->getName();
     $view->vars['session_id'] = session_id();
     $view->vars['form_type'] = $options['upload_form_type'];
 }
Exemplo n.º 28
0
 /**
  * {@inheritdoc}
  */
 public function buildView(FormView $view, FormInterface $form, array $options)
 {
     $name = $form->getName();
     $blockName = $options['block_name'] ?: $form->getName();
     $translationDomain = $options['translation_domain'];
     $labelFormat = $options['label_format'];
     if ($view->parent) {
         if ('' !== ($parentFullName = $view->parent->vars['full_name'])) {
             $id = sprintf('%s_%s', $view->parent->vars['id'], $name);
             $fullName = sprintf('%s[%s]', $parentFullName, $name);
             $uniqueBlockPrefix = sprintf('%s_%s', $view->parent->vars['unique_block_prefix'], $blockName);
         } else {
             $id = $name;
             $fullName = $name;
             $uniqueBlockPrefix = '_' . $blockName;
         }
         if (null === $translationDomain) {
             $translationDomain = $view->parent->vars['translation_domain'];
         }
         if (!$labelFormat) {
             $labelFormat = $view->parent->vars['label_format'];
         }
     } else {
         $id = $name;
         $fullName = $name;
         $uniqueBlockPrefix = '_' . $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');
     }
     $blockPrefixes = array();
     for ($type = $form->getConfig()->getType(); null !== $type; $type = $type->getParent()) {
         if (method_exists($type, 'getBlockPrefix')) {
             array_unshift($blockPrefixes, $type->getBlockPrefix());
         } else {
             @trigger_error(get_class($type) . ': The ResolvedFormTypeInterface::getBlockPrefix() method will be added in version 3.0. You should add it to your implementation.', E_USER_DEPRECATED);
             $fqcn = get_class($type->getInnerType());
             $name = $type->getName();
             $hasCustomName = $name !== $fqcn;
             array_unshift($blockPrefixes, $hasCustomName ? $name : StringUtil::fqcnToBlockPrefix($fqcn));
         }
     }
     $blockPrefixes[] = $uniqueBlockPrefix;
     $view->vars = array_replace($view->vars, array('form' => $view, 'id' => $id, 'name' => $name, 'full_name' => $fullName, 'disabled' => $form->isDisabled(), 'label' => $options['label'], 'label_format' => $labelFormat, 'multipart' => false, 'attr' => $options['attr'], 'block_prefixes' => $blockPrefixes, 'unique_block_prefix' => $uniqueBlockPrefix, 'translation_domain' => $translationDomain, 'cache_key' => $uniqueBlockPrefix . '_' . $form->getConfig()->getType()->getName()));
 }
 /**
  * {@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);
 }
Exemplo n.º 30
0
 /**
  * {@inheritdoc}
  */
 public function buildView(FormView $view, FormInterface $form, array $options)
 {
     $name = $form->getName();
     $blockName = $options['block_name'] ?: $form->getName();
     $readOnly = $options['read_only'];
     $translationDomain = $options['translation_domain'];
     if ($view->parent) {
         if ('' === $name) {
             throw new Exception('Form node with empty name can be used only as root form node.');
         }
         if ('' !== ($parentFullName = $view->parent->vars['full_name'])) {
             $id = sprintf('%s_%s', $view->parent->vars['id'], $name);
             $fullName = sprintf('%s[%s]', $parentFullName, $name);
             $uniqueBlockPrefix = sprintf('%s_%s', $view->parent->vars['unique_block_prefix'], $blockName);
         } else {
             $id = $name;
             $fullName = $name;
             $uniqueBlockPrefix = '_' . $blockName;
         }
         // Complex fields are read-only if they themselves or their parents are.
         if (!$readOnly) {
             $readOnly = $view->parent->vars['read_only'];
         }
         if (!$translationDomain) {
             $translationDomain = $view->parent->vars['translation_domain'];
         }
     } else {
         $id = $name;
         $fullName = $name;
         $uniqueBlockPrefix = '_' . $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');
     }
     $blockPrefixes = array();
     for ($type = $form->getConfig()->getType(); null !== $type; $type = $type->getParent()) {
         array_unshift($blockPrefixes, $type->getName());
     }
     $blockPrefixes[] = $uniqueBlockPrefix;
     if (!$translationDomain) {
         $translationDomain = 'messages';
     }
     $view->vars = array_replace($view->vars, array('form' => $view, 'id' => $id, 'name' => $name, 'full_name' => $fullName, 'read_only' => $readOnly, 'errors' => $form->getErrors(), 'valid' => $form->isBound() ? $form->isValid() : true, 'value' => $form->getViewData(), 'data' => $form->getNormData(), '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(), 'block_prefixes' => $blockPrefixes, 'unique_block_prefix' => $uniqueBlockPrefix, 'translation_domain' => $translationDomain, 'cache_key' => $uniqueBlockPrefix . '_' . $form->getConfig()->getType()->getName()));
 }