php - OPENCART Search by category questions ← (PHP, JQuery)

Solution:

Well I am php developer But I didn't worked upon opencart's yet. But as i watched to your code, it seems to be understanding to me. I think this may work. try this out:

$('#search input[name=\'search\']').parent().find('button').on('click', function() {
        url = $('base').attr('href') + 'index.php?route=product/search';

        var filter_name = $('input[name=\'filter_name\']').attr('value');

        if (filter_name) {
            url += '&filter_name=' + encodeURIComponent(filter_name);
        }

        location = url;
    });

    $('#header input[name=\'filter_name\']').bind('keydown', function(e) {
        if (e.keyCode == 13) {
            url = $('base').attr('href') + 'index.php?route=product/search';

            var filter_name = $('input[name=\'filter_name\']').attr('value');

            if (filter_name) {
                url += '&filter_name=' + encodeURIComponent(filter_name);
            }

            location = url;
        }
    });

and your header file will be look like this:

<div id="search">
    <div class="button-search"></div>
    <?php if ($filter_name) { ?>
    <input type="text" name="filter_name" value="<?php echo $filter_name; ?>" />
    <?php } else { ?>
    <input type="text" name="filter_name" value="<?php echo $text_search; ?>" onclick="this.value = '';" onkeydown="this.style.color = '#000000';" />
    <?php } ?>
  </div>
</div>

Answer



Solution:

There is no way you could search categories by name. What you could do is get all the products that are under a certain category, for that you will need the category's id (for example: all products under category_id=20):

index.php?route=product/search&search=&category_id=20

What you need to do is find a way to get the category's id from the search input, I can't find an easy way to do it at the moment but you could:

  • 1. Modify the categories model by adding a function inside catalog/model/catalog/category.php:

    public function getCategoryByName($category_name) {
        $query = $this->db->query("SELECT category_id FROM ". DB_PREFIX . "category_description WHERE name LIKE '%".$category_name."%'");
    
        if(isset($query->row[0]['category_id'])) return $query->row[0]['category_id'];
        return false;
    }
    
  • 2. Modify the index() function inside catalog/contoller/product/search.php to look for a Get parameter you would send (example &category=true) and then call your function getCategoryByName() [after loading the category model] to get a category_id then integrate it with the reste of the index() function.

  • 2'. Or, Create a controller to handle an AJAX request, get the category_id and plug it through JQuery to your url:

    "index.php?route=product/search&search=&category_id=" + category_id

N.B: This is a simple code, I did not test it, so make sure it is ready for your production environment.

Source