Question

I'm trying to setup Typeahead + Bloodhound to perform search with suggestions on a field. The HTML code for the field is as follow:

<div class="col-sm-10" id="products_forms">
    <input type="text" placeholder="Producto" id="ProductoForm_0_product_id" name="ProductoForm[0][product_id]" class="form-control typeahead">
</div>

I use two main functions from Symfony: one for return all the products and use this as a prefetch and the other for the filtered products. This is how the routes for that functions looks like:

 // the one I use as prefetch parameter in bloodhound
 * @Route("/get_products", name="all_products")

 // the one I use as remote
 * @Route("/get_products/{filter}", name="filter_products")

As you can see the first one didn't get any parameters since it returns all the products as JSON values but the second one takes {filter} as a argument for perform the LIKE and returns only the filtered products.

Now I don't know understand at all how Bloodhound works so I read the docs and also for typeahead read the docs and take a example from here the Remote one and made this code:

// Trigger typeahead + bloodhound
var products = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    prefetch: Routing.generate('all_products'),
    remote: Routing.generate('filter_products', { 'filter' : '%query' })
});

products.initialize();
$('#products_forms .typeahead').typeahead(null, {
    name: 'products',
    displayKey: 'value',
    source: products.ttAdapter()
});

Is that right? I mean when page loads I'll get all the products prefetched but if I type any on .typeahead element I'll get only the filtered ones? I don't know if %query is the right value I should pass to filter_products route in order to get the filtered values. Any help?

This is the first time I use Typeahead + Bloodhound

Was it helpful?

Solution

Replace remote: Routing.generate('filter_products', { 'filter' : '%query' }) with e.g.

var url = Routing.generate('filter_products', {filter: 'WILDCARD'});
// ... some code
remote: {
            url: url,
            wildcard: 'WILDCARD'
        }

That will generate a general url with the RoutingBundle first and takes 'WILDCARD' as your filter. Than tell bloodhound to use 'WILDCARD' on the url as placeholder and it will perfecly replace it with the entered query.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top