Intro

Sometimes you may want to add custom search fields to a module that do more than simply search a field. In this post we’ll be looking at how to add a custom search field which will allow searching for all accounts that have no associated contacts.

Adding the field

First off we create a copy of `modules/Accounts/metadata/searchdefs.php`and place this in `custom/modules/Accounts/metadata/searchdefs.php`. We then add a new key to the `$searchdefs [‘Accounts’][‘layout’][‘basic_search’]`array which  will look something like: We also need to add a language string for our new search field. This can be done by simply adding a new file at `custom/Extension/modules/Accounts/Ext/Language/en_us.NoContactFilter.php`:

This will give us the following:

NoContactSearchExample1

Unfortunately, SuiteCRM displays our new search field as a dropdown rather than a checkbox, stay tuned for a future post on how to change this.

Adding the logic

Now we have a wonderful search dropdown on our Accounts list view. It doesn’t actually do anything however. Let’s change that.

We create a copy of modules/Accounts/metadata/SearchFields.phpand place this in custom/modules/Accounts/metadata/SearchFields.php in exactly the same manner as we did for searchdefs.php above. We add our new search field to the $searchFields['Accounts']  array.

It should look something like:

This creates a subquery filter type. Specifying a query type of format allows us to use {0} in our query to access the dropdown value. SuiteCRM will only display account ids that match what our subquery returns.

SELECT accounts.id 
FROM accounts 
LEFT JOIN accounts_contacts ON (accounts.id = accounts_contacts.account_id AND accounts_contacts.deleted = 0)WHERE (NOT {0} AND accounts_contacts.id IS NOT NULL) OR ({0} AND accounts_contacts.id IS NULL)

We make use of this to force only accounts with contacts when “No” is selected (the NOT {0} AND accounts_contacts.id IS NOT NULL part of the query) and only accounts with no contacts when “Yes” is selected (the {0} AND accounts_contacts.id IS NULL part of the query).

Conclusion

Adding custom subqueries in this manner allows a huge amount of custom filters to be created. Have an idea for a custom filter? Have a better way of doing the above? Then let me know in the comments.