Inherit form or add type to each form

笑着哭i 提交于 2019-11-29 06:38:04

Have you tried using inheritance?

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

# file: Your\Bundle\Form\BaseType.php
<?php

namespace Your\Bundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class BaseType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->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
<?php

namespace Your\Bundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class ExtendType extends BaseType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        parent::buildForm($builder, $options);

        # you can also remove an element from the parent form type
        # $builder->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.

You can do this with the getParent() function.

<?php

namespace Your\Bundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;


class ChildType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // $builder->remove('field');
        // $builder->add('field);
    }

    public function getParent()
    {
        return ParentType::class;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!