php - 在 Symfony2 中创建服务表单

标签 php symfony service

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

这是 Controller 中的代码摘录

$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;
}

最佳答案

createForm() 函数是 Symfony's Controller class 中的别名.您将无法从您的服务中访问它。您需要将 Symfony 容器注入(inject)您的服务或注入(inject) 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;
    }

关于php - 在 Symfony2 中创建服务表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34299169/

相关文章:

symfony2 : cannot redeclare class

php - 在 collectionOperations (GET) 上使用 Symfony 选民

PHP:根据 $value 更改文本颜色

php - 在 PHP 中,diff : $var2=$var1 ; $var2=&$var1; 是什么

html - 我无法正确定位导航栏中的某个元素

java - 如何以正确的方式定期运行代码

sql - 授予对所有服务代理对象的权限

java - 在tomcat中使用Thread Pool executor服务加速请求

php - 单击链接时不显示正确的图像

php - 更改两个域的根目录