Inherit form or add type to each form

前端 未结 2 1238
情深已故
情深已故 2020-12-17 23:00

I am searching for an easy way to add a bundle of fields to each form.

I have found a way to extend the AbstractType and use the buildForm meth

2条回答
  •  再見小時候
    2020-12-17 23:16

    Have you tried using inheritance?

    This is really simple, first you have to define a form type:

    # file: Your\Bundle\Form\BaseType.php
    add('name', 'text');
    
            $builder->add('add', 'submit');
        }
    
        public function setDefaultOptions(OptionsResolverInterface $resolver)
        {
            $resolver->setDefaults(array(
                'data_class' => 'Your\Bundle\Entity\YourEntity',
            ));
        }
    
        public function getName()
        {
            return 'base';
        }
    }
    

    Then you can extend this form type:

    # file: Your\Bundle\Form\ExtendType.php
    remove('some_field');
    
            $builder->add('number', 'integer');
        }
    
        public function setDefaultOptions(OptionsResolverInterface $resolver)
        {
            $resolver->setDefaults(array(
                'data_class' => 'Your\Bundle\Entity\YourEntity',
            ));
        }
    
        public function getName()
        {
            return 'extend';
        }
    }
    

    The BaseType will display a name field and an add submit button. The ExtendType will display a name field, an add submit button and a number field.

提交回复
热议问题