cosmicsafari
cosmicsafari

Reputation: 4049

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.

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

...

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

...

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

    <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.

Upvotes: 0

Views: 44

Answers (1)

Terenoth
Terenoth

Reputation: 2598

FormBuilder should NOT manipulate entity data, because as its name stands for, its role is to build the different fields of a 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 (i.e. the field with the same name as your attribute) will have its data changed adequately.

Example :

FooType.php

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

Foo.php

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

Then, your FormView will directly have its title field filled with "HELLO".

Upvotes: 1

Related Questions