【问题标题】:Symfony $form is nullSymfony $form 为空
【发布时间】:2017-05-15 18:43:12
【问题描述】:

我已经构建了一个 API GET 函数。表单如下所示:

<form action="/find" method="GET">
    <input type="text" name="Title" id="Title" value="">
    <input type="submit" value="Search">
</form>

这是我的函数,它应该处理上面的表单并将文本框中的字符串插入$form-&gt;get('Title')-&gt;getData()。但是当我尝试使用浏览器获取时,它给了我SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data。查看原始数据,我明白了:

<pre class='xdebug-var-dump' dir='ltr'>
<small>/home/vagrant/Code/symfony_awd/src/Blogsite/BooksBundle/Controller    /BookController.php:29:</small><font color='#3465a4'>null</font>
</pre>Google Volume Not Found

我知道变量为空,但为什么呢?函数代码如下:

public function findAction(Request $request)
{
    $form = $this->createForm(null, ['csrf_protection' => false])
        ->add('Title', TextType::class)
        ->add('Search', SubmitType::class)
        ->getForm();

    $form->handleRequest($request);

    var_dump($form->getData());

    if($form->isSubmitted() && $form->isValid()) {
        $json = file_get_contents("https://www.googleapis.com/books/v1/volumes?q=".$form->get('Title')->getData());
        $response = json_decode($json, true);

        if(array_key_exists('items', $response)){
            return $this->render('BlogsiteBooksBundle:Pages:results.html.twig', [
                'items' => $response['items']
            ]);
        } else {
            return new Response('Google did not have any items', 400);
        }
    }

    return new Response('Google Book Not Found', 404);
}

【问题讨论】:

    标签: php json forms rest symfony


    【解决方案1】:

    默认情况下表单期望通过POST发送数据,您需要将表单的方法设置为GET

    $this->createForm(null, ['csrf_protection' => false, 'method' => 'GET'])
        // ...
    

    更多详情请参考How to Change the Action and Method of a Form

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-04
      • 2015-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多