简体   繁体   English

将实体传递给FormType,以便可以在Symfony2的buildForm()中运行其方法

[英]Passing an Entity to a FormType so its methods can be run in buildForm() in Symfony2

Started working with the Symfony framework and so far all has went well, but the following has me stumped. 开始使用Symfony框架,到目前为止一切进展顺利,但以下内容让我感到困惑。

I have need to pull previously persisted data to prepopulate some fields on another stage of a multi page form. 我需要提取以前保留的数据以在多页表单的另一个阶段中预填充某些字段。

I had hoped to just pass in the object in order to use its methods but I can't seem to get it to work. 我曾希望仅传入对象以使用其方法,但似乎无法使其正常工作。

For example: 例如:

foo.php foo.php

...

$form = $this->formFactory->create('foo_type', $article);

...

fooType.php fooType.php

...

protected $article;

    public function __construct(Article $article)
    {
        $this->article = $article;
    }

 public function buildForm(FormBuilderInterface $builder, array $options)
    {

        $builder
            ->add(
                'fooTitle',
                'text',
                array('data' => $this->article->getTitle())
            );
    }

...

forms.xml 表格.xml

    <service id="footType" class="\Path\To\File\fooType">
        <argument type="service" id="article" />
        <tag name="form.type" alias="foo_type" />
    </service>

I feel like I am missing out a crucial step somewhere but i'm struggling to understand how to relate the xml with the type class being used to build the form. 我感觉好像错过了某个关键步骤,但是我正在努力了解如何将xml与用于构建表单的类型类相关联。

FormBuilder should NOT manipulate entity data, because as its name stands for, its role is to build the different fields of a Form . FormBuilder不应操纵实体数据,因为顾名思义,其作用是建立Form的不同字段。

About populating fields, it is actually pretty simple: if you set an attribute on your entity, when you bind your entity to your Form , the related field (ie the field with the same name as your attribute) will have its data changed adequately. 关于填充字段,实际上非常简单:如果在实体上设置属性,则在将实体绑定到Form ,相关字段(即与属性名称相同的字段)的数据将发生适当更改。

Example : 范例:

FooType.php FooType.php

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('title', 'text');
}

Foo.php Foo.php

$article->setTitle('HELLO');
$this->formFactory->create('foo_type', $article);

Then, your FormView will directly have its title field filled with "HELLO" . 然后,您的FormView将直接用"HELLO"填充其title字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM