Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 382
Marcius Leandro Avatar asked Sep 18 '25 16:09

Marcius Leandro


1 Answers

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;
    }
like image 146
Jason Roman Avatar answered Sep 21 '25 07:09

Jason Roman