获取POST请求Symfony 3

时间:2017-01-31 13:18:54

标签: php symfony

尝试使用Symfony从我的POST表单中获取响应,但是'名称'变量总是返回null?被困在这几个小时,并希望得到一些帮助。

我正在使用$ request-> request-> get(' ...','默认'),如文档中所述。

{
    $project = new Project();

    $form = $this->createFormBuilder($project)
        ->add('name', TextType::class)
        ->add('save', SubmitType::class, array('label' => 'Load Project'))
        ->getForm();

    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        return $this->render('default/show.html.twig', array(
            'name' => $request->request->get('name', 'null'),
        ));
    }

    return $this->render('default/new.html.twig', array(
        'form' => $form->createView(),
    ));
}

1 个答案:

答案 0 :(得分:0)

您可以从项目对象中获取name的值:

$project = new Project();

$form = $this->createFormBuilder($project)
    ->add('name', TextType::class)
    ->add('save', SubmitType::class, array('label' => 'Load Project'))
    ->getForm();

$form->handleRequest($request);

if ($form->isSubmitted() && $form->isValid()) {
    return $this->render('default/show.html.twig', array(
        'name' => $project->getName(),
    ));
}

return $this->render('default/new.html.twig', array(
    'form' => $form->createView(),
));

或来自表格:

$project = new Project();

$form = $this->createFormBuilder($project)
    ->add('name', TextType::class)
    ->add('save', SubmitType::class, array('label' => 'Load Project'))
    ->getForm();

$form->handleRequest($request);

if ($form->isSubmitted() && $form->isValid()) {
    return $this->render('default/show.html.twig', array(
        'name' => $form->get('name'),
    ));
}

return $this->render('default/new.html.twig', array(
    'form' => $form->createView(),
));