Need some help with your project? Contact me

How to dynamically search for related contacts in CiviCRM

I’ve been learning CiviCRM in Drupal lately and there was an issue I ran into that bugged me for days: how to search for some contacts that meet certain criteria AND the ones that relate to them via a certain relationship? And I finally figured it out...

For example, I had two types of contacts: organisations and individuals employed in the organisations. So your classic employer-employee relationship. But how to search for the organisations in a certain country and bring them up together with the employees working for those organisations? Easy right? Well, perhaps, but boy I banged my head against the wall...

You’d think that given the complexity of the Advanced Search, it’s logical to have like a checkbox to select for the result page to also include contacts of relationship X. But no. Anyway, after many tries and no luck finding a solution online, evrika!

When you do the Advanced Search, you have to select under Display Results As - Related Contacts and specify which relationship you want the results to show. So, if select there employee and search for all the organisations in the US, you will get as a result all the people working in all the organisations in the US - but not the organisations themselves.

To get both, you need to save this result as a smart group, and perform the search again, but without the last step. By this I mean to skip changing the Display Results As setting. Save this group too and then merge the two in whatever context you need them - either into a third inclusive group, or in your mailing or whatever.

Hope this helps.

Some related articles you might enjoy


This post helped me a lot, but now I would like to do the same but using multiples relationship types. For example if you have a relationship "CIO of" between individuals and companies, I would like to be able to fetch all indivuals that are employees or CIO of all companies. Do you have an idea to do so ? I think I could create smart groups for each relationship types and merge them but maybe there is an easier solution ?

Add new comment

You can post comments in Markdown and basic HTML tags.
For code blocks, wrap your code within '~~~'. For example:
$var = 'my variable';