How to set default value for form field in Symfony2?

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

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

22条回答
  •  难免孤独
    2020-11-27 13:44

    If you need to set default value and your form relates to the entity, then you should use following approach:

    // buildForm() method
    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder
        ...
        ->add(
            'myField',
            'text',
            array(
                'data' => isset($options['data']) ? $options['data']->getMyField() : 'my default value'
            )
        );
    }
    

    Otherwise, myField always will be set to default value, instead of getting value from entity.

提交回复
热议问题