How to set default value for form field in Symfony2?

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

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

相关标签:
22条回答
  • 2020-11-27 13:41

    Often, for init default values of form i use fixtures. Of cause this way is not easiest, but very comfortable.

    Example:

    class LoadSurgeonPlanData implements FixtureInterface
    {
        public function load(ObjectManager $manager)
        {
            $surgeonPlan = new SurgeonPlan();
    
            $surgeonPlan->setName('Free trial');
            $surgeonPlan->setPrice(0);
            $surgeonPlan->setDelayWorkHours(0);
            $surgeonPlan->setSlug('free');
    
            $manager->persist($surgeonPlan);
            $manager->flush();        
        }   
    }
    

    Yet, symfony type field have the option data.

    Example

    $builder->add('token', 'hidden', array(
        'data' => 'abcdef',
    ));
    
    0 讨论(0)
  • 2020-11-27 13:41

    If that field is bound to an entity (is a property of that entity) you can just set a default value for it.

    An example:

    public function getMyField() {
        if (is_null($this->MyField)) {
            $this->setMyField('my default value');
        }
        return $this->MyField;
    }
    
    0 讨论(0)
  • 2020-11-27 13:41

    As Brian asked:

    empty_data appears to only set the field to 1 when it is submitted with no value. What about when you want the form to default to displaying 1 in the input when no value is present?

    you can set the default value with empty_value

    $builder->add('myField', 'number', ['empty_value' => 'Default value'])
    
    0 讨论(0)
  • 2020-11-27 13:43
    ->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
         $form = $event->getForm(); 
         $data = $event->getData(); 
    
         if ($data == null) {
             $form->add('position', IntegerType::class, array('data' => 0));
         }
    
    });
    
    0 讨论(0)
  • 2020-11-27 13:43

    I solved this problem, by adding value in attr:

    ->add('projectDeliveringInDays', null, [
        'attr' => [
              'min'=>'1',
              'value'=>'1'
              ]
         ])
    
    0 讨论(0)
  • 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.

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