2015-12-15 65 views
3

I'm trying to create the form from my service, however is giving this error在Symfony2的服務創建形式

這是在控制器

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

代碼摘錄這是我在服務功能

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; 
} 
+1

'createForm'是在'Controller'類中定義的快捷方式的方法,你的控制器延伸。您的服務不包含這種方法。 – Artamiel

回答

3

createForm()功能是Symfony's Controller class別名。您將無法從您的服務中訪問它。您需要將Symfony容器注入您的服務或注入form.factory服務。例如:

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

,然後在類:

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; 
    } 
+2

請注意,從Symfony 2.8''...-> createForm(QuestionType :: class,$ entity ...''是首選的。在Symfony 3.x中刪除了在createForm調用中實例化類的選項。使用Symfony 3.x時,使用例如''SubmitType :: class''而不是''submit'''。 – Xatoo