4

I have profiles (Users) that can have multiple addresses (currently two Smart Map fields called profileAddress1 and profileAddress2).

I know how to filter by a single address:

{% set results = craft.users({
    group: 'profiles',
    profileAddress1: {
        target: 'Cologne',
        range: 20
    }
}) %}

How would I search across both fields? So if a profile had two addresses – one in Cologne and one in Munich – it should show up in the results in both search cases (Cologne and Munich).

Is that even possible?

3
  • Carl's answer is spot on. You can only do a proximity search for one address field at a time. However, the workaround is to perform two separate queries, and merge together the resulting entry ids. Carl's answer (and linked references) describes the technique very well.
    – Lindsey D
    Commented May 23, 2016 at 6:04
  • @LindseyD thanks for the hint. Unfortunately I have trouble making clean searches for the separate address fields. Querying only for the profileAddress2 field returns results whose profileAddress2 field is empty. It seems like it’s querying for profileAddress1 instead. Other results that should show up (because they have a matching address set in profileAddress2 won’t show up. Is that maybe a bug in the SQL query or something? It’s driving me crazy :) Commented May 24, 2016 at 15:28
  • Hmm, it might be a bug... email [email protected], and we can sort it out there.
    – Lindsey D
    Commented May 24, 2016 at 16:49

1 Answer 1

4

You would need to setup two criteria models, one for each Smart Map field, and query for the element IDs. Merge these IDs and have a 3rd criteria model where you pass in the IDs to the id parameter.

See this question for example code:

Complex logic on a ElementCriteriaModel parameter?

Here's a blog post describing the technique in details:

Manipulating Craft's ElementCriteriaModel objects with Twig

If you need better performance, have a look at the custom Yii query builder code I posted here:

How can I query for entries that have one of two Lightswitch fields enabled?

4
  • Beat me to it... and with a perfect answer! :)
    – Lindsey D
    Commented May 23, 2016 at 5:48
  • Thanks for the nudge into the right direction! Especially the blog post helps a lot. Commented May 24, 2016 at 15:31
  • Do you have any clue how this would work using the element api plugin? Commented May 24, 2016 at 15:43
  • You can setup the criteria models in the transformer, have a look at this answer to get an idea of this craftcms.stackexchange.com/a/14691/125
    – carlcs
    Commented May 24, 2016 at 16:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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