Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
629 views
in Technique[技术] by (71.8m points)

symfony - Inherit form or add type to each form

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 method to add more fields.
When creating the form I give the name of my new type (How to Create a Custom Form Field Type).

In my opinion it is an easy way, but it is restricted to one type per form.

Is there a better way to achieve anything like that?
I have read the cookbook of symfony, but I have only found stuff how to extend an existing form not how to create an own form "template" with my fields.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Have you tried using inheritance?

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

# file: YourBundleFormBaseType.php
<?php

namespace YourBundleFormType;

use SymfonyComponentFormAbstractType;
use SymfonyComponentFormFormBuilderInterface;
use SymfonyComponentOptionsResolverOptionsResolverInterface;

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' => 'YourBundleEntityYourEntity',
        ));
    }

    public function getName()
    {
        return 'base';
    }
}

Then you can extend this form type:

# file: YourBundleFormExtendType.php
<?php

namespace YourBundleFormType;

use SymfonyComponentFormAbstractType;
use SymfonyComponentFormFormBuilderInterface;
use SymfonyComponentOptionsResolverOptionsResolverInterface;

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' => 'YourBundleEntityYourEntity',
        ));
    }

    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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...