KandeeHolly
KandeeHolly

Reputation: 59

How can I render search results using Symfony?

I've created a form for searching data in the DB.

This is the form:

<form role="search" method="post" action="{{ path('search') }}">
    <div>
        <input type="text" placeholder="Cerca" name ="search">
        <span>
            <button type="submit"></button>
        </span>
    </div>
</form>

And of course I also have the action in the controller:

public function searchAction(Request $request)
{
    $request = $this->getRequest();
    $data = $request->request->get('search');

    $em = $this->getDoctrine()->getManager();
    $query = $em->createQuery('SELECT a FROM AppBundle:Article a WHERE a.titolo LIKE :data')
                ->setParameter('data', $data);

    $result = $query->getResult();

    return $this->render('default/search.html.twig', array('result' => $result));
}

In this way, I can write in the field what I want to search, and submit the form. The form is submitted, but it renders the form again without any message or results.

If I want to render the results, do I have to create a results template where I use a for loop to render all the results?

How can I render the results?

Upvotes: 0

Views: 486

Answers (1)

Yoshi
Yoshi

Reputation: 54649

You're already passing $results to the render function. So with the required code in your template it should work without much hassle:

E.g.

{% for result in results %}
  <div>
    // use result, e.g. {{ result.title }} or whatever your data has to offer
  </div>
{% else %}
  <em>no results found</em>
{% endfor %}

Upvotes: 1

Related Questions