3

I'm having issues with getting results from a query. I have 2 search parameters which i have set to variables. I would like to match both of these to get results.

At the moment the query is returning zero results. I think this is because it is turning the variables into strings. Replacing the variables with hardcoded values does return results.

{% set queryKeyword = craft.request.getParam('q') %}
{% set queryLocation = craft.request.getParam('l') %}

{%
    set entries = craft.entries.section('schools').find({
       search: 'body:queryKeyword categories:queryLocation'
    })
%}

I have tried:

{%
    set entries = craft.entries.section('schools').find({
       search: 'body:' + queryKeyword + 'categories:' + queryLocation,
    })
%}

This doesn't work.

I'm very new to Craft CMS and am not very experienced in PHP/MySQL so any help would be greatly appreciated. Thanks!

5

I think you are using the wrong string concatination operator. ~ is the twig string concatination operator (vs . for php and + for javascript).

Try this:

{%
  set entries = craft.entries.section('schools').find({
   search: 'body:' ~ queryKeyword ~ ' categories:' ~ queryLocation,
  })
%}
  • Also, don't forget the space before "categories"... Although I'm not sure it's possible to conduct a search through related categories. – Lindsey D Apr 19 '15 at 23:44
  • @LindseyD - good catch that space. – Marion Newlevant Apr 20 '15 at 3:30
1

Assuming your "categories" field is in fact a categories field then I'd recommend to use the relatedTo parameter to filter by that category instead of throwing everything into the search parameter.

{% set queryLocation = craft.request.getParam('l') %}
{% set queryKeyword = craft.request.getParam('q') %}

{# Set relationParam only if the param is set and a category with that slug exists #}
{% set category = craft.categories.group('location').slug(queryLocation).first() %}
{% set relationParam = queryLocation and category ? {targetElement: category} : '' %}

{# Set searchParam only if the param is set #}
{% set searchParam = queryKeyword ? 'body:' ~ queryKeyword : '' %}

{# Get the filtered entries #}
{% set entries = craft.entries.section('news').relatedTo(relationParam).search(searchParam) %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.