继承表单或向每个表单添加类型 [英] Inherit form or add type to each form

查看:135
本文介绍了继承表单或向每个表单添加类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种简单的方法来向每个表单中添加字段字段.

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

我找到了扩展 AbstractType 并使用buildForm方法添加更多字段的方法.
创建表单时,请输入新类型的名称(如何创建自定义表单字段类型).

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.

是否有更好的方法来实现这样的目标?
我已经阅读了symfony的菜谱,但是我只发现了如何扩展现有表单的内容,而不是如何使用字段创建自己的表单模板"的东西.

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.

推荐答案

您是否尝试过使用继承?

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';
    }
}

然后您可以extend此表单类型:

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';
    }
}

BaseType将显示一个 name 字段和一个 add 提交按钮. ExtendType将显示一个 name 字段,一个 add 提交按钮和一个 number 字段.

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.

这篇关于继承表单或向每个表单添加类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆