TransWikia.com

Getting unique values from Smart Map addresses

Craft CMS Asked by Eric Snyder on January 10, 2021

Using the following filter will return all the entries for ‘CA’.

{% set params = {
    filter: {
        state: 'CA'
    }
} %}

{% set meetings = craft.entries.address(params) %}

Let’s say that I get 10 returns for ‘CA’:

Los Angeles
Los Angeles
Los Angeles
San Diego
San Diego
San Diego
San Diego
San Diego
San Diego
Modesto

How would I go about one getting 3 results returned for each unique value for City? I only want to list each city once rather than 3 Los Angeles, 16 San Diego’s and 1 Modesto. Like this:

Los Angeles
San Diego
Modesto

It could also be helpful to have them like this:

3 Los Angeles
6 San Diego
1 Modesto

I am building a navigation by state with a list of cities under each state. To look like this:

CA
   Los Angeles
   San Diego
   Modesto
KS
   Wichita
   Kansas City

One Answer

You'd actually need to retrieve all of the entries to count them in this way. Once you've got the complete collection, it would simply be a matter of looping through them and adding everything up.

1. Get all entries in California.

{% set params = {
    filter: {
        state: 'CA'
    }
} %}

{% set meetings = craft.entries.address(params).all() %}

2. Loop through those entries. Build a new array based on the results.

{% set stateMeetings = {} %}
    
{% for meeting in meetings %}

    {% set city = meeting.address.city %}

    {% if stateMeetings[city] is defined %}
        {% set cityTotal = stateMeetings[city] + 1 %}
    {% else %}
        {% set cityTotal = 1 %}
    {% endif %}

    {% set stateMeetings = stateMeetings|merge{(city):cityTotal} %}

{% endfor %}

3. By the time that's all done, you'll have a neat associative array, where each key is a different city, and the value of each represents how many times it was found.

{
    "Los Angeles": 3,
    "San Diego": 6,
    "Modesto": 1,
}

You'll definitely want to cache all of that... it'll be a pretty expensive process.

To be honest, I'd actually recommend doing all of this work in a plugin (or module). It's a fairly easy thing to achieve with a template hook. This kind of heavy merging is ill-fitted for Twig, but much simpler in PHP.

Correct answer by Lindsey D on January 10, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP