kamil1995b
kamil1995b

Reputation: 121

Symfony $form is null

I've built an API GET function. The form looks like this:

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

and this is my function which should handle the form above and insert string from the text box into $form->get('Title')->getData(). But when I try to GET using a browser, it gives me SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data. Looking at raw data, I get this:

<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

I understand that the variable is null, but why? Here is the function code:

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

Upvotes: 0

Views: 418

Answers (1)

malarzm
malarzm

Reputation: 2966

By default the form is expecting the data to be sent through POST, you need to set the form's method to GET:

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

For more details please refer to How to Change the Action and Method of a Form

Upvotes: 1

Related Questions