How to set a default value in a Symfony 2 form field?

前端 未结 2 963
-上瘾入骨i
-上瘾入骨i 2020-12-12 03:44

I\'ve been trying to set up a form with Symfony 2.

So I followed the tutorial and I\'ve created a special class for creating the form and handling the

相关标签:
2条回答
  • 2020-12-12 04:05

    What you're trying to do here is creating a security hole: anyone would be able to inject any ID in the user_product_id field and dupe you application. Not mentioning that it's useless to render a field and to not show it.

    You can set a default value to user_product_id in your entity:

    /**
     * @ORM\Annotations...
     */
    private $user_product_id = 9000;
    
    0 讨论(0)
  • 2020-12-12 04:12

    Another way is creating a Form Type Extension:

    namespace App\Form\Extension;
    
    // ...
    
    class DefaultValueTypeExtension extends AbstractTypeExtension
    {
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            if (null !== $default = $options['default']) {   
                $builder->addEventListener(
                    FormEvents::PRE_SET_DATA,
                    static function (FormEvent $event) use ($default) {
                        if (null === $event->getData()) {
                            $event->setData($default);
                        }
                    }
                );
            }
        }
    
        public function configureOptions(OptionsResolver $resolver)
        {
            $resolver->setDefault('default', null);
        }
    
        public static function getExtendedTypes(): iterable
        {
            yield FormType::class;
        }
    }
    

    Now any possible value can be passed as default to any form field:

    $form->add('user', null, ['default' => $this->getUser()]);
    $form->add('user_product_id', null, ['default' => 1]);
    

    This method is specially useful when you don't have a chance to hook into the initialization process of the bound object.

    0 讨论(0)
提交回复
热议问题