3

I have a template where I would like to pass a search parameter to a craft.entries.section in an included template. The current main template has this:

{% include "_includes/testimonial" with
  { type: "agency" } 
  %}

Then in the include I have this code where entry.clientsOrAgency is a dropdown field and I want it to only show results of the "type" passed in the parent template.

{# get one random testimonial entry #}
{% set testimonial = craft.entries.section('testimonials').search(entry.clientsOrAgency,type).order('RAND()').limit(1) %}

{% for quotes in testimonial %}
<div class="testimonial">

  {# matrix field is 'testimonial' - find different quote types #}
  {% for quote in quotes.testimonial %}
    more code here
  {% endfor %} {# quotes.testimonial #}

</div><!--testimonial-->
{% endfor %}{# quote in testimonial #}

The above code results in a template error Undefined index: query

Not sure how to resolve this.

3

Your syntax is a bit off – the search() parameter doesn't accept multiple parameters, only a search query (e.g. .search('body:foobar')) or an object containing the search query plus search term options. In your case, you're actually passing an object (.search(entry.clientsOrAgency)), in which case Craft will look for a query parameter on that object (the second parameter is just ignored). Hence your error.

That being said, here's what you probably want:

{% set testimonial = craft.entries.section('testimonials').search('clientsOrAgency:'~type).order('RAND()').limit(1) %}

The above will search for entries in the testimonials section, which has the value equal to type in each clientsOrAgency field.

However – unless you need (which can be enabled as a default for all searching in Craft, or per-search using search term options mentioned above) for the clientsOrAgency field, I don't actually think using search() is the appropriate approach here. The following would be easier and probably more performant:

{% set testimonial = craft.entries.section('testimonials').clientsOrAgency(type).order('RAND()').limit(1) %}

Also, you should probably add .first() to your craft.entries query, in order to only pull a single entry:

{% set testimonial = craft.entries.section('testimonials').clientsOrAgency(type).order('RAND()').limit(1).first() %}

{% if testimonial %}
    ...
{% endif %}
  • That's perfect. Used the second code block - wasn't aware that you could search a field in that way. – CreateSean Oct 4 '16 at 15:44
  • 1
    Awesome. Yeah, you can even do more advanced stuff like for example .clientsOrAgency(type~'*'), to search for clientsOrAgency values starting with type. – Mats Mikkel Rummelhoff Oct 4 '16 at 16:02

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.