How to set default value for form field in Symfony2?

后端 未结 22 1653
暖寄归人
暖寄归人 2020-11-27 13:23

Is there an easy way to set a default value for text form field?

22条回答
  •  一生所求
    2020-11-27 13:59

    Approach 1 (from http://www.cranespud.com/blog/dead-simple-default-values-on-symfony2-forms/)

    Simply set the default value in your entity, either in the variable declaration or the constructor:

    class Entity {
        private $color = '#0000FF';
        ...
    }
    

    or

    class Entity {
        private $color;
    
        public function __construct(){
             $this->color = '#0000FF';
             ...
        }
        ...
    }
    

    Approach 2 from a comment in the above link, and also Dmitriy's answer (not the accepted one) from How to set default value for form field in Symfony2?

    Add the default value to the data attribute when adding the field with the FormBuilder, adapted from Dmitriy's answer.

    Note that this assumes that the property will and will only have the value null when it's a new, and not an existing, entity.

    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder->add('color', 'text', array(
                'label' => 'Color:',
                'data' => (isset($options['data']) && $options['data']->getColor() !== null) ? $options['data']->getColor() : '#0000FF'
            )
        );
    }
    

提交回复
热议问题