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

By Mark Nelson | February 8, 2016

Creating a custom lookup in dynamics ax that filters across multiple fields

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

 

 

Related Posts

Recommended Reading:

Manage U.S. Use Tax on Purchase Orders in Dynamics 365 Finance and Operations

  Managing sales tax requirements on your business purchase can be complicated, but Dynamics 365 Finance and Operations can help […]

Read the Article
5.19.22 Dynamics CRM

How to Write a Great Support Ticket in the Stoneridge Support Portal

Submitting a support ticket through the Stoneridge Support Portal is a quick and effective way to get assistance for any […]

Read the Article

Managing Your Business Through Uncertain Times Using Dynamics 365 Finance and Operations

  Dynamics 365 Finance and Operations (F&O) can help you make informed decisions on how to move your business forward. […]

Read the Article
5.13.22 Power Platform

Using Power BI Object Level Security

  The following article will demonstrate how to use Power BI Object Level Security to disable column data based on […]

Read the Article
5.12.22 Dynamics CRM

How to Use the Stoneridge Support Portal

Stoneridge Software’s support portal is an intuitive and useful function that makes it easy for you to access resources to […]

Read the Article
5.6.22 Dynamics GP

Dynamics GP Transaction Removal: Purchase Orders

  Are you having performance issues with Purchase Orders?  Do you find that there are old Purchase Orders on your […]

Read the Article
5.5.22 Dynamics GP

The Real Story about the Long-Term Future of Dynamics GP Support

I’ve seen a number of people put forward comment that Dynamics GP is going away and you have to get […]

Read the Article

New Features in Dynamics 365 Business Central 2022 Wave 1 Release – Financial Enhancements

The Dynamics 365 Businses Central 2022 Wave 1 Release has a lot of new and exciting features to help your […]

Read the Article
4.29.22 Dynamics GP

Dynamics GP Transaction Removals: Bank Reconciliation

  This is part 2 of a 3 part series on Dynamics GP Transaction Removals. These quick tips will hopefully […]

Read the Article

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!

X