Search all entities Symfony2

473 views Asked by At

I'm working on a webapplication in Symfony2. At the moment I have several pages that include a search form where you can search for specific entities that belong to that page.

For example; I have a client page with an overview of client information. Here you can search for clients with a name like your search value. Thats no rocket science I guess.

At the front page I want to somehow search all my entities at once. I was thinking about combining the searches I already have, or maybe there is a function in Symfony that allows this?

Here's some of my code for the search(es) I have so far:

Live search action for clients:

public function liveSearchAction(Request $request)
{
    $string = $this->getRequest()->request->get('sQuery');
    $clients = $this->getDoctrine()
                 ->getRepository('clientsBundle:client')
                 ->findByLetters($string);

    $response = new JsonResponse(array('clients' => $clients));
    $response->headers->set('Content-Type', 'application/json');

    return $response;
}

The repository function findByLetters:

public function findByLetters($string){
        $query = $this->getEntityManager()
            ->createQuery(
                'SELECT c FROM clientsBundle:client c
                 WHERE c.name LIKE :string'
                )->setParameter('string', '%'.$string.'%');

        $result = $query->getArrayResult();

        return $result;
    }

The AJAX call for returning searchresults

(function($, Handlebars, window, document, undefined) {
    var that = this;
    var oXHR;

    var source   = $("#searchResult").html();
    var template = Handlebars.compile(source);
    var action   = $('#quickSearch').data('action');
    var route    = $('#quickSearch').data('route');

    Handlebars.registerHelper('url', function(options) {
        console.log(this, options);
        return new Handlebars.SafeString(
            Routing.generate(route, {'id': this.id})
        );
    });

    $('#quickSearch').on('input',function() {
        var $this = $(this);
        var searchText = $this.val();
        console.log('searching for: ' + searchText);

        if (typeof oXHR !== 'undefined') {
            oXHR.abort();
        }

        oXHR = $.ajax({
            type: "POST",
            url: action,
            dataType: "json",
            data: {
                sQuery : searchText
            },
            success: function(response)
            {
                var html = template(response);
                // console.log(html);
                $('#list .list-group').html(html);
            },
            error: function(failresponse)
            {
                console.log( failresponse );
            }
        });


    });
}).call(window.Test = window.Test || {}, jQuery, Handlebars, window, document);

As you might have noticed, the return of the AJAX call gets handled by handlebars.

0

There are 0 answers