Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/232.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 在Symfony2中创建服务表单_Php_Symfony_Service - Fatal编程技术网

Php 在Symfony2中创建服务表单

Php 在Symfony2中创建服务表单,php,symfony,service,Php,Symfony,Service,这是控制器中的代码摘录 $service = $this->get('questions_service'); $form_question = $service->createQuestionForm($question, $this->generateUrl('create_question', array('adId' => $ad->getId()))); 这是我在职期间的职责 public function createQuestionForm($ent

这是控制器中的代码摘录

$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容器注入到您的服务中,或者注入
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;
    }

createForm
是控制器扩展的
Controller
类中定义的快捷方式方法。您的服务不包含此方法。请注意,从Symfony 2.8
…->createForm(QuestionType::class,$entity…
是首选。在Symfony 3.x中删除了在createForm调用中实例化类的选项。也不赞成按类型名称添加表单字段。使用Symfony 3.x时,请使用例如
SubmitType::class
而不是
submit'