Creating A Custom Lookup in Dynamics AX That Filters Across Multiple Fields

By Mark Nelson | February 8, 2016

The normal item lookup in Dynamics AX is fine for finding items when you know part of the Item number or Search name. But, what if we have item information in a related table?

Custom Lookup in Dynamics AX

We want to create a custom lookup in Dynamics AX that displays fields from a related table, and allows us to filter records by typing into a search box. Start by creating a regular custom lookup form. Instead of standard data sources, we will use a query as the data source for our form. This will allow us to more easily filter our results. Add a text box and a button above the grid; this will serve as our filter box.

When opened, the form now looks like this:

Creating a Custom Lookup in Dynamics AX

The first problem we encounter is that a normal lookup form will disappear whenever a record is selected. We want to break this behavior and force the user to either click the select button or double click the desired record so that the user is able to use the filter box.

The following code implements this change:

public int task(int _taskId)
{
    #task
    int ret;

    // The Enter task is assigned to our Select button
    if (_taskId == #taskEnter)
    {
        canSelect = true;
    }

    ret = super(_taskId);

    return ret;

}
public void closeOk()
{
    // Prevent the closing of the lookup form simply by
    // clicking on an item in a grid.
    if (canSelect == true)
    {
        super();
    }
}
public void closeSelectRecord(Common _selectedRecord)
{
    if (canSelect == true)
    {
        // Only close when the flag is set
        if (callerForm.name() == formStr(SysTableBrowser))
        {
            element.closeSelect(int642str(_selectedRecord.RecId));
        }
        else
        {
            super(_selectedRecord);
        }
    }
}

Override the clicked method on the Select button:

void clicked()
{
    canSelect = true;
    element.closeSelectRecord(InventTable);

    super();
}

Override the doubleClicked method on the grid:

public int mouseDblClick(int _x, int _y, int _button, boolean _ctrl, boolean _shift)
{
    int ret;

    ret = super(_x, _y, _button, _ctrl, _shift);

    // make the OK button appear as the default action
    ok.clicked();

    return ret;
}

The canSelect variable is a flag that allows us to cancel the form closing that would normally happen when the user clicks on something.

Now for the interesting part.  When the user types a value into the filter box, we want to filter the grid to show all records where any field starts with the entered value.  To do this, we are going to use the addQueryFilter method on the query.  This will allow us to add a WHERE clause to the query that will match multiple fields and OR the results together.  By applying a normal filter we are only able to AND the results.

I also must point out that a query filter applied in this manner differs from the normal Range applied to a QueryBuildDataSource in that it's applied after the data sources are joined. This can produce unexpected results when your tables are linked with an Outer join.

public boolean filterItems(SSISearchValue _itemSearch)
{
    #Define.LogicalOr("||")

    str fieldMatchTemplate = '(%1.%2 like "%3")';

    Query query;
    QueryBuildDataSource qbds;
    QueryFilter qf;

    FormStringControl control;
    FormDataSource dataSource;
    int controlCount;
    int controlIndex;

    str searchString;
    str whereClause;
    container whereClauseCon;

    boolean success;

    // Prevent unnecessary searches
    if (lastSearchItem != _itemSearch)
    {
        lastSearchItem = _itemSearch;

        // Create a new query rather than try to cleanup the old one
        query = new query(queryStr(SSIInventItemLookup));

        if (strLen(_itemSearch) > 0)
        {
            // Make sure we properly escape the user entered value
            searchString = SysQuery::valueLikeAfter(SysQuery::value(_itemSearch));

            // Loop over each visible control in the grid so that we can create a filter for it
            controlCount = Grid.controlCount();
            for (controlIndex = 1; controlIndex <= controlCount; controlIndex++)
            {
                control = Grid.controlNum(controlIndex);

                if (control.visible() == true)
                {
                    dataSource = control.dataSourceObject();

                    if (dataSource != null)
                    {
                        // use the data source name and data field name in the filter
                        whereClause = strFmt(fieldMatchTemplate,
                            dataSource.name(),
                            control.dataFieldName(),
                            searchString);

                        // Add the filter to the collection
                        whereClauseCon += whereClause;
                    }
                }
            }

            // This will concatenate all of the filters together, separating
            // them with the logical OR operator
            whereClause = con2Str(whereClauseCon, #LogicalOr);

            // Apply the filter to the query
            qbds = query.dataSourceTable(tableNum(InventTable));
            qf = query.addQueryFilter(qbds, fieldStr(InventTable, DataAreaId));
            qf.value(strFmt('(%1)', whereClause));
        }
        else
        {
            searchString = SysQuery::valueUnlimited();
        }

        // Set the query on the form and execute it
        InventTable_ds.query(query);
        InventTable_ds.executeQuery();
    }

    return success;
}

The last thing to do is add a timer to automatically apply the filter 1 second after the user stops typing.

In the class declaration of the form, add a constant for the timeout:  *Remember that the timeout is specified in milliseconds.

public class FormRun extends ObjectRun
{
    #Define.SearchTimeout(1000)

    boolean canSelect;

    Form callerForm;
    Common common;

    SSISearchValue lastSearchItem;
}

Override the clicked method on the SearchValue button to apply the filter when it is clicked:

void clicked()
{
    super();

    // The search button was clicked, run the filter now
    SearchValue.runFilter();
}

Add a method to the SearchValue button to apply the filter:

public void runFilter()
{
    SSISearchValue text;
    int timerHandle;

    // Cancel the timer if still active.
    timerHandle = this.getTimeOutTimerHandle();
    if (timerHandle != 0)
    {
        this.cancelTimeOut(timerHandle);
    }

    text = this.text();
    element.filterItems(text);
}

Finally, override the textChanged method to start the timer whenever the text box value changes:

public void textChange()
{
    // Use the form timer to perform the search after the user
    // has stopped typing.  The final parameter tells Ax to
    // restart the timer everytime setTimeOut is called.
    this.setTimeOut(identifierstr(runFilter), #SearchTimeout, true);
}

Now when we type “Microsoft” into the filter we find all records with a field that starts with that string:
Custom Lookup in Dynamics AX


Under the terms of this license, you are authorized to share and redistribute the content across various mediums, subject to adherence to the specified conditions: you must provide proper attribution to Stoneridge as the original creator in a manner that does not imply their endorsement of your use, the material is to be utilized solely for non-commercial purposes, and alterations, modifications, or derivative works based on the original material are strictly prohibited.

Responsibility rests with the licensee to ensure that their use of the material does not violate any other rights.

Start the Conversation

It’s our mission to help clients win. We’d love to talk to you about the right business solutions to help you achieve your goals.

Subscribe To Our Blog

Sign up to get periodic updates on the latest posts.

Thank you for subscribing!