Set Default value of choice field Symfony FormType

后端 未结 5 1884
野性不改
野性不改 2021-01-21 03:12

I want from the user to select a type of questionnaire, so I set a select that contains questionnaires types.

Types are loaded from a an entity QuestionType

5条回答
  •  余生分开走
    2021-01-21 03:38

    The accepted answer of setting in the model beforehand is a good one. However, I had a situation where I needed a default value for a certain field of each object in a collection type. The collection has the allow_add and allow_remove options enabled, so I can't pre-instantiate the values in the collection because I don't know how many objects the client will request. So I used the empty_data option with the primary key of the desired default object, like so:

    class MyChildType
    extends AbstractType 
    {
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder->add('optionalField', 'entity', array(
                'class' => 'MyBundle:MyEntity',
                // Symfony appears to convert this ID into the entity correctly!
                'empty_data' => MyEntity::DEFAULT_ID,
                'required' => false,
            ));
        }
    }
    
    class MyParentType
    extends AbstractType 
    {
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder->add('children', 'collection', array(
                'type' => new MyChildType(),
                'allow_add' => true
                'allow_delete' => true,
                'prototype' => true,  // client can add as many as it wants
            ));
        }
    }
    

提交回复
热议问题