vendor/symfony/form/Extension/Core/Type/FormType.php line 171

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <fabien@symfony.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace Symfony\Component\Form\Extension\Core\Type;
  11. use Symfony\Component\Form\Exception\LogicException;
  12. use Symfony\Component\Form\Extension\Core\DataAccessor\CallbackAccessor;
  13. use Symfony\Component\Form\Extension\Core\DataAccessor\ChainAccessor;
  14. use Symfony\Component\Form\Extension\Core\DataAccessor\PropertyPathAccessor;
  15. use Symfony\Component\Form\Extension\Core\DataMapper\DataMapper;
  16. use Symfony\Component\Form\Extension\Core\EventListener\TrimListener;
  17. use Symfony\Component\Form\FormBuilderInterface;
  18. use Symfony\Component\Form\FormInterface;
  19. use Symfony\Component\Form\FormView;
  20. use Symfony\Component\OptionsResolver\Options;
  21. use Symfony\Component\OptionsResolver\OptionsResolver;
  22. use Symfony\Component\PropertyAccess\PropertyAccess;
  23. use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
  24. use Symfony\Component\Translation\TranslatableMessage;
  25. class FormType extends BaseType
  26. {
  27.     private $dataMapper;
  28.     public function __construct(PropertyAccessorInterface $propertyAccessor null)
  29.     {
  30.         $this->dataMapper = new DataMapper(new ChainAccessor([
  31.             new CallbackAccessor(),
  32.             new PropertyPathAccessor($propertyAccessor ?? PropertyAccess::createPropertyAccessor()),
  33.         ]));
  34.     }
  35.     /**
  36.      * {@inheritdoc}
  37.      */
  38.     public function buildForm(FormBuilderInterface $builder, array $options)
  39.     {
  40.         parent::buildForm($builder$options);
  41.         $isDataOptionSet \array_key_exists('data'$options);
  42.         $builder
  43.             ->setRequired($options['required'])
  44.             ->setErrorBubbling($options['error_bubbling'])
  45.             ->setEmptyData($options['empty_data'])
  46.             ->setPropertyPath($options['property_path'])
  47.             ->setMapped($options['mapped'])
  48.             ->setByReference($options['by_reference'])
  49.             ->setInheritData($options['inherit_data'])
  50.             ->setCompound($options['compound'])
  51.             ->setData($isDataOptionSet $options['data'] : null)
  52.             ->setDataLocked($isDataOptionSet)
  53.             ->setDataMapper($options['compound'] ? $this->dataMapper null)
  54.             ->setMethod($options['method'])
  55.             ->setAction($options['action']);
  56.         if ($options['trim']) {
  57.             $builder->addEventSubscriber(new TrimListener());
  58.         }
  59.         $builder->setIsEmptyCallback($options['is_empty_callback']);
  60.     }
  61.     /**
  62.      * {@inheritdoc}
  63.      */
  64.     public function buildView(FormView $viewFormInterface $form, array $options)
  65.     {
  66.         parent::buildView($view$form$options);
  67.         $name $form->getName();
  68.         $helpTranslationParameters $options['help_translation_parameters'];
  69.         if ($view->parent) {
  70.             if ('' === $name) {
  71.                 throw new LogicException('Form node with empty name can be used only as root form node.');
  72.             }
  73.             // Complex fields are read-only if they themselves or their parents are.
  74.             if (!isset($view->vars['attr']['readonly']) && isset($view->parent->vars['attr']['readonly']) && false !== $view->parent->vars['attr']['readonly']) {
  75.                 $view->vars['attr']['readonly'] = true;
  76.             }
  77.             $helpTranslationParameters array_merge($view->parent->vars['help_translation_parameters'], $helpTranslationParameters);
  78.             $rootFormAttrOption $form->getRoot()->getConfig()->getOption('form_attr');
  79.             if ($options['form_attr'] || $rootFormAttrOption) {
  80.                 $view->vars['attr']['form'] = \is_string($rootFormAttrOption) ? $rootFormAttrOption $form->getRoot()->getName();
  81.                 if (empty($view->vars['attr']['form'])) {
  82.                     throw new LogicException('"form_attr" option must be a string identifier on root form when it has no id.');
  83.                 }
  84.             }
  85.         } elseif (\is_string($options['form_attr'])) {
  86.             $view->vars['id'] = $options['form_attr'];
  87.         }
  88.         $formConfig $form->getConfig();
  89.         $view->vars array_replace($view->vars, [
  90.             'errors' => $form->getErrors(),
  91.             'valid' => $form->isSubmitted() ? $form->isValid() : true,
  92.             'value' => $form->getViewData(),
  93.             'data' => $form->getNormData(),
  94.             'required' => $form->isRequired(),
  95.             'size' => null,
  96.             'label_attr' => $options['label_attr'],
  97.             'help' => $options['help'],
  98.             'help_attr' => $options['help_attr'],
  99.             'help_html' => $options['help_html'],
  100.             'help_translation_parameters' => $helpTranslationParameters,
  101.             'compound' => $formConfig->getCompound(),
  102.             'method' => $formConfig->getMethod(),
  103.             'action' => $formConfig->getAction(),
  104.             'submitted' => $form->isSubmitted(),
  105.         ]);
  106.     }
  107.     /**
  108.      * {@inheritdoc}
  109.      */
  110.     public function finishView(FormView $viewFormInterface $form, array $options)
  111.     {
  112.         $multipart false;
  113.         foreach ($view->children as $child) {
  114.             if ($child->vars['multipart']) {
  115.                 $multipart true;
  116.                 break;
  117.             }
  118.         }
  119.         $view->vars['multipart'] = $multipart;
  120.     }
  121.     /**
  122.      * {@inheritdoc}
  123.      */
  124.     public function configureOptions(OptionsResolver $resolver)
  125.     {
  126.         parent::configureOptions($resolver);
  127.         // Derive "data_class" option from passed "data" object
  128.         $dataClass = function (Options $options) {
  129.             return isset($options['data']) && \is_object($options['data']) ? \get_class($options['data']) : null;
  130.         };
  131.         // Derive "empty_data" closure from "data_class" option
  132.         $emptyData = function (Options $options) {
  133.             $class $options['data_class'];
  134.             if (null !== $class) {
  135.                 return function (FormInterface $form) use ($class) {
  136.                     return $form->isEmpty() && !$form->isRequired() ? null : new $class();
  137.                 };
  138.             }
  139.             return function (FormInterface $form) {
  140.                 return $form->getConfig()->getCompound() ? [] : '';
  141.             };
  142.         };
  143.         // Wrap "post_max_size_message" in a closure to translate it lazily
  144.         $uploadMaxSizeMessage = function (Options $options) {
  145.             return function () use ($options) {
  146.                 return $options['post_max_size_message'];
  147.             };
  148.         };
  149.         // For any form that is not represented by a single HTML control,
  150.         // errors should bubble up by default
  151.         $errorBubbling = function (Options $options) {
  152.             return $options['compound'] && !$options['inherit_data'];
  153.         };
  154.         // If data is given, the form is locked to that data
  155.         // (independent of its value)
  156.         $resolver->setDefined([
  157.             'data',
  158.         ]);
  159.         $resolver->setDefaults([
  160.             'data_class' => $dataClass,
  161.             'empty_data' => $emptyData,
  162.             'trim' => true,
  163.             'required' => true,
  164.             'property_path' => null,
  165.             'mapped' => true,
  166.             'by_reference' => true,
  167.             'error_bubbling' => $errorBubbling,
  168.             'label_attr' => [],
  169.             'inherit_data' => false,
  170.             'compound' => true,
  171.             'method' => 'POST',
  172.             // According to RFC 2396 (http://www.ietf.org/rfc/rfc2396.txt)
  173.             // section 4.2., empty URIs are considered same-document references
  174.             'action' => '',
  175.             'attr' => [],
  176.             'post_max_size_message' => 'The uploaded file was too large. Please try to upload a smaller file.',
  177.             'upload_max_size_message' => $uploadMaxSizeMessage// internal
  178.             'allow_file_upload' => false,
  179.             'help' => null,
  180.             'help_attr' => [],
  181.             'help_html' => false,
  182.             'help_translation_parameters' => [],
  183.             'invalid_message' => 'This value is not valid.',
  184.             'invalid_message_parameters' => [],
  185.             'is_empty_callback' => null,
  186.             'getter' => null,
  187.             'setter' => null,
  188.             'form_attr' => false,
  189.         ]);
  190.         $resolver->setAllowedTypes('label_attr''array');
  191.         $resolver->setAllowedTypes('action''string');
  192.         $resolver->setAllowedTypes('upload_max_size_message', ['callable']);
  193.         $resolver->setAllowedTypes('help', ['string''null'TranslatableMessage::class]);
  194.         $resolver->setAllowedTypes('help_attr''array');
  195.         $resolver->setAllowedTypes('help_html''bool');
  196.         $resolver->setAllowedTypes('is_empty_callback', ['null''callable']);
  197.         $resolver->setAllowedTypes('getter', ['null''callable']);
  198.         $resolver->setAllowedTypes('setter', ['null''callable']);
  199.         $resolver->setAllowedTypes('form_attr', ['bool''string']);
  200.         $resolver->setInfo('getter''A callable that accepts two arguments (the view data and the current form field) and must return a value.');
  201.         $resolver->setInfo('setter''A callable that accepts three arguments (a reference to the view data, the submitted value and the current form field).');
  202.     }
  203.     /**
  204.      * {@inheritdoc}
  205.      */
  206.     public function getParent(): ?string
  207.     {
  208.         return null;
  209.     }
  210.     /**
  211.      * {@inheritdoc}
  212.      */
  213.     public function getBlockPrefix(): string
  214.     {
  215.         return 'form';
  216.     }
  217. }