Sunday, November 7, 2021

How to override form control Lookup using extensions in D365 FO

In D365FO we have a bunch of events to subscribe to on a form control level:

right-click on lookup event of control to subscribe to the event and paste in class.


[FormControlEventHandler(formControlStr(PayrollEmployerTaxRegion, Overview_StateId), FormControlEventType::Lookup)]

    public static void Overview_StateId_OnLookup(FormControl sender, FormControlEventArgs e)

    {

                  // Logic here

    }



Now to cancel parent event, D365FO provide a class FormControlCancelableSuperEventArgs


You can cancel the parent(Original event with below code)


        FormControlCancelableSuperEventArgs ce = e as FormControlCancelableSuperEventArgs;


        //cancel super() to prevent error.

        ce.CancelSuperCall();





//Code

[FormControlEventHandler(formControlStr(PayrollEmployerTaxRegion, Overview_StateId), FormControlEventType::Lookup)]

    public static void Overview_StateId_OnLookup(FormControl sender, FormControlEventArgs e)

    {

        SysTableLookup      sysTableLookup  = SysTableLookup::newParameters(tableNum(LogisticsAddressState), sender);

        Query               query           = new Query();


        // Filter lookup to only show US states

        query.addDataSource(tableNum(LogisticsAddressState)).addRange(fieldNum(LogisticsAddressState, CountryRegionId)).value(LogisticsAddressCountryRegion::findByISOCode(SysCountryRegionCode::countryInfo(curext())).CountryRegionId);


        // Sort the lookup by state Id

        query.dataSourceTable(tableNum(LogisticsAddressState)).addOrderByField(fieldNum(LogisticsAddressState, StateId), SortOrder::Ascending);


        // Add fields

        sysTableLookup.addLookupfield(fieldNum(LogisticsAddressState, StateId));

        sysTableLookup.addLookupfield(fieldNum(LogisticsAddressState, Name));


        // Run lookup

        sysTableLookup.parmQuery(query);

        sysTableLookup.performFormLookup();

        FormControlCancelableSuperEventArgs ce = e as FormControlCancelableSuperEventArgs;


        //cancel super() to prevent error.

        ce.CancelSuperCall();

    } 

Reference