I'm trying to to display entries related to "all" the given categories instead of "any" using the updated relatedTo method provided in Craft 2.5.
In a related question, @BrandonKelly explains how to do this in the "Updated" portion of his answer. However, I still seem to be getting "any" behavior instead of entries matching "all" categories.
Here is an example URL if only one category in the Social Services group is selected
http://website.com/technologies/someSocialService
Here is an example URL if additional technology categories are also added:
http://website.com/technologies/someSocialService?type[]=88&type[]=117
So, ideally, I want to first filter the entries by the social service category, determined by segment 2 in the URL.
Then, I want to filter even further if there are types of technology in the URL.
Here is my code:
{% set slug = craft.request.getSegment(2) %}
{% set socialServiceCategory = craft.categories.group('socialServices').slug(slug).first() %}
{% set socialServiceCategoryId = socialServiceCategory.id %}
{% set technologyCategoryIds = [] %}
{% if craft.request.getParam('type') %}
{% set technologyCategoryIds = technologyCategoryIds|merge(craft.request.getParam('type')) %}
{% endif %}
{% set categoryIds = [socialServiceCategoryId]|merge(technologyCategoryIds) %}
{% set entries = craft.entries({
section: 'solutions',
relatedTo: {
targetElement: ['and']|merge(categoryIds)
}
}).order('listingType desc', 'title asc') %}
When the page loads with only the segment slug, and no query string, I get entries filtered by that category. However, once I add one or more technology IDs to the categoryIds array, I get all entries matching "any" categories in the categoryIds array.
Given a URL such as the 2nd example I displayed above, here is a dump of my categoryIds output:
array(3) { [0]=> string(2) "15" [1]=> string(2) "88" [2]=> string(3) "117" }
...which contains exactly the right categories I'd like to inclusively relate my entries to.
For the time being, I was able to get this working the way I need with pre-Craft 2.5 beta syntax for relatedTo using the following code:
{% set entries = entries.relatedTo(socialServiceCategoryId).order('listingType desc', 'title asc') %}
{% if technologyCategoryIds|length %}
{% set entries = entries.relatedTo(
'and',
{ targetElement: socialServiceCategoryId },
{ targetElement: technologyCategoryIds|join(',') }
).order('listingType desc', 'title asc') %}
{% endif %}