Marcius Leandro
Marcius Leandro

Reputation: 789

Create form for service in Symfony2

I'm trying to create the form from my service, however is giving this error

this is the code excerpt in the controller

$service = $this->get('questions_service');
$form_question = $service->createQuestionForm($question, $this->generateUrl('create_question', array('adId' => $ad->getId())));

this is my function in service

public function createQuestionForm($entity, $route)
{
    $form = $this->createForm(new QuestionType(), $entity, array(
        'action' => $route,
        'method' => 'POST',
    ));

    $form
        ->add('submit', 'submit', array('label' => '>', 'attr' => array('class' => 'button button-question button-message')));

    return $form;
}

Upvotes: 4

Views: 3477

Answers (1)

Jason Roman
Jason Roman

Reputation: 8276

The createForm() function is an alias in Symfony's Controller class. You will not have access to it from within your service. You'll want to either inject the Symfony container into your service or inject the form.factory service. For example:

services:
    questions_service:
        class:        AppBundle\Service\QuestionsService
        arguments:    [form.factory]

and then in your class:

use Symfony\Component\Form\FormFactory;

class QuestionsService
{
    private $formFactory;

    public function __construct(FormFactory $formFactory)
    {
        $this->formFactory = $formFactory;
    }

    public function createQuestionForm($entity, $route)
    {
        $form = $this->formFactory->createForm(new QuestionType(), $entity, array(
            'action' => $route,
            'method' => 'POST',
        ));

        $form
            ->add('submit', 'submit', array(
                'label' => '>',
                'attr' => array('class' => 'button button-question button-message')
        ));

        return $form;
    }

Upvotes: 3

Related Questions