> For the complete documentation index, see [llms.txt](https://docs.gridmate.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.gridmate.io/advanced-guides/filters-and-data/grid-advanced-filtering.md).

# Grid - Advanced Filtering

Filter grid records with junctions, inline SOQL, merge fields and Apex value providers.

## Using Junctions

To filter the records either as an admin or as an end user can combine conditions with conjunctions like ‘OR’, ‘AND’. Below is a complex filter query:

```json
{
   "or": [
      {
         "ParentId": {
            "operator": "=",
            "value": "$recordId"
         }
      },
      {
         "UltimateParent__c": {
            "operator": "=",
            "value": "$recordId"
         }
      }
   ]
}
```

{% hint style="info" %}
$recordId can be used to implicitly use the current recordId
{% endhint %}

## Using Inline SOQL

An inline SOQL query can be used to filter records within the current record. Inline SOQL can be used with “in” operator only:

```json
{
   "Id": {
      "operator": "in",
      "value": "SELECT Project__c FROM Assignment__c WHERE Manager__c=$$recordId$"
   }
}
```

{% hint style="info" %}
$$recordId$ can be used to implicitly use the current recordId in the SOQL query
{% endhint %}

## Using Parent Field

Any field from the current object can be used to filter the related records. Parent fields can be referenced in the filter property as a merge field $record.**fieldApiName**

```json
{
   "Country__c": {
      "operator": "=",
      "value": "$record.BillingCountry"
   }
}
```

## Using $USER

Any field from the logged user can be used to filter the related records. User fields can be referenced in the filter property as a merge field $USER.**fieldApiName**

```json
{
   "Amount": {
      "operator": "<",
      "value": "$USER.Minimum_Amount__c"
   }
}
```

## Using $CUSTOMSETTING

Any field from any custom settings can be used to filter the related records. Custom settings fields can be referenced in the filter property as a merge field $CUSTOMSETTING.**objectApiName**.**fieldApiName**

```json
{
   "Discount__c": {
      "operator": ">",
      "value": "$CUSTOMSETTING.Quote_Settings__c.Max_Discount__c"
   }
}
```

## Using $APEX

For complex use cases, an apex class can be provided as a value provider for a filter property as a merge field $APEX.className({params})

```json
{
   "Id": {
      "operator": "in",
      "value": "$APEX.AttachedDocumentFilter({\"recordId\":\"$recordId\"})"
   }
}
```

{% hint style="info" %}
Apex class parameters should be always an escaped JSON string. $recordId can be used to implicitly use the current recordId.
{% endhint %}

The value provider class should implement a Callable interface and should be global. GridMate runs the value provider dynamically:

```java
Callable handler = (Callable) Type.forName(handlerClass).newInstance();
return (String) handler.call('getValue', params);
```

The example below showcases a specific value provider to filter ContentVersion based on the current record:

{% tabs %}
{% tab title="AttachedDocumentFilter.cls" %}

```java
global with sharing class AttachedDocumentFilter implements Callable {
    global Object call(String action, Map<String, Object> args) {
        if (action == 'getValue') {
            String recordId = (String) args.get('recordId');

            //Build the list of linked documents
            List<ContentDocumentLink> linkList = [
                SELECT Id, ContentDocument.LatestPublishedVersionId
                FROM ContentDocumentLink
                WHERE LinkedEntityId = :recordId
            ];

            List<Id> idList = new List<Id>();
            for (ContentDocumentLink link : linkList) {
                idList.add(link.ContentDocument.LatestPublishedVersionId);
            }

            return '(\'' + String.join(idList, '\',\'') + '\')';
        } else {
            throw new ExtensionMalformedCallException('Action not implemented');
        }
    }

    public class ExtensionMalformedCallException extends Exception {
    }
}
```

{% endtab %}

{% tab title="AttachedDocumentFilterTest.cls" %}

```java
@isTest
class AttachedDocumentFilterTest {
    @testSetup
    static void createTestData() {
        ContentVersion content = new ContentVersion(
            Title = 'Demo Script',
            PathOnClient = '/demo_script.txt',
            VersionData = Blob.valueOf('Unit Test ContentVersion Body'),
            Origin = 'H'
        );

        insert content;
    }

    static testMethod void testExecute() {
        Test.startTest();

        Callable handler = (Callable) Type.forName('AttachedDocumentFilter').newInstance();
        String values = (String) handler.call(
            'getValue',
            new Map<String, String>{ 'recordId' => UserInfo.getUserId() }
        );

        Test.stopTest();

        System.assert(values != null);
    }
}
```

{% endtab %}
{% endtabs %}

## Querying All Rows

To query all rows set the flag **gmpkg\_\_allRows** to true. The example below showcases a filter fetching all the emails including the archived ones:

```json
{
    "and": [
        {
            "AccountId": {
                "operator": "=",
                "value": "$recordId"
            }
        },
        {
            "Subject": {
                "operator": "like",
                "value": "Email%"
            }
        },
        {
            "gmpkg__allRows": true
        }
    ]
}
```

## Next steps

<table data-view="cards"><thead><tr><th></th><th></th><th data-hidden data-card-target data-type="content-ref"></th></tr></thead><tbody><tr><td><strong>Grid - Enhanced Filter Builder</strong></td><td>Build filters that combine AND and OR conditions.</td><td><a href="/advanced-guides/filters-and-data/grid-enhanced-filter-builder.md">Grid - Enhanced Filter Builder</a></td></tr><tr><td><strong>User Grid - Data Filtering</strong></td><td>Filter User Grid records with Quick Filters or the Advanced Filter Query Builder.</td><td><a href="/advanced-guides/user-grid/user-grid-data-filtering.md">User Grid - Data Filtering</a></td></tr><tr><td><strong>Grid - Advanced Configuration</strong></td><td>Generate smart grid property values step by step with the Config Wiz.</td><td><a href="/advanced-guides/grid-setup/grid-configuration.md">Grid - Advanced Configuration</a></td></tr></tbody></table>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.gridmate.io/advanced-guides/filters-and-data/grid-advanced-filtering.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
