Symfony3 - Using a form as a service

Hello,

I’ trying to use a form as a service in Symfony3. The current documentation is little (ie http://symfony.com/doc/current/service_container.html), and the answers here and there are not alway helpful.

When used standalone, my form works fine, and is correctly inserting data in the database through Doctrine.

I’ve written a service.yml file :

services:
    tasks_form:
        factory_method: create
        factory_service: form.factory
        class: Symfony\Component\Form\Form
        arguments: ["@tasks_form_type"]

    tasks_form_type:
        class: AppBundle\Form\Type\TasksFormType
        tags:
        - { name: form.type, alias: tasks_form_type }

The form controller is TasksFormController. I try to call the service in another controller with :

$form=$this->get('tasks_form');

… and all I get is an error message :

Catchable Fatal Error: Argument 1 passed to Symfony\Component\Form\Form::__construct() must be an instance of Symfony\Component\Form\FormConfigInterface, instance of AppBundle\Form\Type\TasksFormType given, called in […]

A bit lost here. Is it a matter of symfony2 vs 3 syntax ? Is the error message due to an error in the services.yml file or to the way I call the service ?

Best regards,

MC

Maybe not related to your problem.

But are those tab indents in the yml file instead of two space indents?

Did you validate it? eg.

Yes, it’s valid. Thanks for the link to yamllint.com anyway. It’s useful.

1 Like

Well, I guess the $form=$this->get(‘tasks_form’); was wrong.
I got rid of the error with :

    	$taskSet=new TaskSetClass();
    	$form=$this->createForm(TasksFormType::class, $taskSet);
or
        $form = $this->container->get('form.factory')->create(TasksFormType::class, $taskSet);

The form now appears on the page, but no more validation, and no more writing to the database. The form is just looping on itself when submitted.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.