Friday, July 18, 2025

A Practical Guide to Using Event Handlers in D365 F&O (The Smart Way to Customize)

Customizing standard processes in Dynamics 365 Finance and Operations has evolved significantly. Gone are the days when overlayering was the norm. Today, we work with event handlers - a cleaner, upgrade-safe way to extend standard logic without touching Microsoft’s base code.

In this post, I’ll break down how event handlers work, when to use them, and walk you through a real-world example that illustrates how powerful (and easy) they are to implement.



Why Event Handlers Deserve Your Attention ?

As developers and technical consultants, we’re often tasked with extending standard business logic. Event handlers let us do that without modifying the original codebase. This ensures:

  • No conflicts during platform upgrades
  • Better code separation for long-term maintenance
  • Compliance with Microsoft's One Version policy


Mostly used types of event handlers

Depending on your use case, there are different handler types available:

Event Type         Purpose
Pre-event         Executes before the standard method – ideal for validations
Post-event         Executes after the method – great for additional processing
OnModified, OnValidated         Used for form field-level triggers
DataEventHandlers         Fire during insert/update/delete events on tables

Use Case: Auto-Generating Vendor Codes

Let’s say your client needs vendor records to be assigned a unique code automatically when a new vendor is created. The standard VendTable insert method doesn’t do this out-of-the-box.

Instead of overlayering the base method (which is a no-go in today’s world), we’ll attach a post-event handler.

Let's look at the below example of how to create an event handler :-



class VendTableEventHandler
{
    [PostHandlerFor(tableStr(VendTable), tableMethodStr(VendTable, insert))]
    public static void VendTable_PostInsert(XppPrePostArgs args)
    {
        VendTable vendTable = args.getThis() as VendTable;

        if (!vendTable)
            return;

        vendTable.selectForUpdate(true);
        vendTable.VendCode = VendTableEventHandler::generateVendorCode(vendTable.RecId);
        vendTable.doUpdate();
    }

    private static str generateVendorCode(RecId recId)
    {
        return strFmt("VEND-%1", recId);
    }
}

Now, every time a vendor is created, this handler fires after the insert and assigns a custom vendor code like VEND-123456.

Tips to Keep in Mind

  • Keep event logic focused - Don’t clutter handlers with business rules. Move complex logic into helper or service classes.
  • Naming matters - Use consistent names like VendTableEventHandler so future developers can easily trace logic.
  • Avoid assumptions about execution order - If multiple handlers exist, the order isn’t guaranteed — so design your logic to be independent.


When to Use Event Handlers vs. Chain of Command

Both are powerful, but they serve different purposes:

Use case      What to use ?
Working with public table/form methods      Event Handler
Modifying protected business logic (services, controllers)      Chain of Command
Handling table-level inserts/updates      DataEventHandler
UI interaction (field validations)      Form event methods

Conclusion

Understanding how and when to use event handlers is essential for any D365 F&O developer or architect. Not only does it keep your codebase cleaner and upgrade-ready, but it also aligns with how Microsoft expects us to extend their platform moving forward. If you’re still relying on overlayering, it’s time to re-think your approach. With just a few lines of code, event handlers give you the flexibility you need — without the headaches that come with platform updates.


That's all for now. Please let us know your questions or feedback in comments section !!!!

Monday, May 22, 2023

How to reverse Free Text Invoice Voucher entries without Dialog

 Hey Folks , 


This blog post is in continuation of the previous post for Reversing Free Text Invoice Voucher entries with Dialog. Only difference is this time we are doing it without dialog or you can say by suppressing

For doing it we have extended TransactionReversal_Cust class. 

We have a staging table FTIVouchers which contains the Voucher Number to be reversed.

We can use the below code to achieve this : - 



class TransactionReversal extends TransactionReversal_Cust
{
    public static TransactionReversal construct()
    {
        return new TransactionReversal();
    }

    public boolean showDialog()
    {
        return false;
    }

    public static void main(Args _args)
    {
        CustTrans 				custTrans;
        FTIVouchers                             vouchers;
        TransactionReversal 	                transactionReversal;
        ReasonTable 			        reasonTable;
        ReasonCode 				reasonCode;
        ReasonRefRecID 			        reasonRefRecID;
        InvoiceId 				invoiceId;
        Args 					args;
        

        while select vouchers where vouchers.Voucher!=''
        {
            args = new Args();
            custTrans = CustTrans::findByVoucher(vouchers.Voucher);
            args.record(custTrans);  
            reasonCode = 'XYZ';
            reasonTable = ReasonTable::find(reasonCode);
            reasonRefRecID = ReasonTableRef::createReasonTableRef(
            reasonTable.Reason, vouchers.Voucher+'REV');
            transactionReversal = transactionReversal::construct();
            transactionReversal.parmReversalDate(custTrans.TransDate);
            transactionReversal.parmReasonRefRecId(reasonRefRecID);
            transactionReversal.reversal(args);
            info(strFmt("%1 %2 %3 %4 reversed.",
                custTrans.Voucher,
                custTrans.TransDate,
                custTrans.Invoice,
                custTrans.Txt));
        }
        
    }

}

}


That's all for now. Please let us know your questions or feedback in comments section !!!!

Thursday, May 11, 2023

How to reverse Free Text Invoice voucher entry through x++ with Dialog

 Hey Folks , 


In order to do quick reversal of wrongly created Customer Invoices it will take lot of time and effort to do this manually. Here x++ pitches in to help us achieve this quickly.

For doing it through a dialog for a single transaction we have TransactionReversal_Cust class. 

We have a staging table FTIVouchers which contains the Voucher Number to be reversed.

We can use the below code to achieve this : - 



internal final class RunnableClass1
{
    /// 
    /// Class entry point. The system will call this method when a designated menu 
    /// is selected or when execution starts and this class is set as the startup class.
    /// 
    /// The specified arguments.
    public static void main(Args _args)
    {
        FTIVouchers                vouchers;
        TransactionReversal_Cust   transactionReversal = TransactionReversal_Cust::construct();

        Args        args = new Args();

        while select vouchers  where vouchers.Voucher!=''
        {
            CustTrans   custTrans = CustTrans::findByVoucher(vouchers.Voucher);

            args.record(custTrans);

            transactionReversal.parmReversalDate(systemdateget());

            transactionReversal.reversal(args);
        }
    }

}


That's all for now. Please let us know your questions or feedback in comments section !!!!

Monday, January 9, 2023

How to get data from InventDim for InventSum table

 

When we get a requirement to fetch the data for InventDim from tables like InventTable , SalesTable , SalesLine , PurchTable , PurchLine its pretty straight forward. All we need to do is check the relations which is based on the field InventDimId

For e.g InventTable.InventDimId = InventDim.InventDimId

But when we have a requirement to get the data from InventSum table which only has transactional records from InventTrans and moreover the data replicates and has no unique index. Its gets difficult most of the time to get the data. 

To save the day InventSum has the method joinChild() 

Given below is a sample code to illustrate the use of joinChild() method : - 



    [SysClientCacheDataMethodAttribute]
    public display Str1000 getProfVal(InventSum _inventSum)
    {
        InventDim               inventDimJoin;

        inventDimJoin.data(_inventSum.joinChild());

        WHSLocationProfile whsLocationProfile = WHSLocationProfile::findByWarehouseAndLocation(inventDimJoin.InventLocationId, inventDimJoin.wMSLocationId);

        return whsLocationProfile.LocProfileId;

    }


That's all for now. Please let us know your questions or feedback in comments section !!!!

Monday, August 29, 2022

How to use Electronic Signature before inserting data into a table through x++ in D365 Fin Ops

 

Validation of data through Electronic Signatures has become one of the most commonly used processes in any ERP. This helps us to ensure data validation before any transaction is committed.

The Info class has a method named collectESignature which enables us to ensure whether electronic signature is provided properly or not. We can use this in our code before committing a particular transaction.


Note : - The Code block should not be inside Transaction Tracking System ( ttsbegin or ttscommit)

Here is sample code to show the implementation : -




boolean             flag = false;

CustTable          custTable;

custTable.AccountNum =  'A1101';

custTable.CustGroup =  'C02';

custTable.PaymTermId = '5D';

flag = info.collectESignature(DatabaseLogType::Insert , custTable);

if(flag)
{
   custTable.insert();
}
else
{
   throw error('Electronic Signature verification failed. Please try again');
}


That's all for now. Please let us know your questions or feedback in comments section !!!!

Tuesday, June 21, 2022

How to get messages from Infolog through x++ in Dynamics 365 FO


Error Handling is one of the very good practices to used especially when we are using integration of Dynamics 365 Fin Ops with other applications.


When we encounter these errors in an infolog the best way to get those error messages is through two most important classes : - 


SysInfologEnumerator  

SysInfoLogMessageStruct


Lets see throw below code snippet how these classes help us to achieve our goal : - 



class GetInfologMessages
{
    public static str getErrorStr()
    {
        SysInfologEnumerator         enumerator;

        SysInfologMessageStruct     msgStruct;

        Exception                              exception;

        str                                          error;   

        enumerator      =   SysInfologEnumerator::newData(infolog.copy(1,infolog.num()));

        while(enumerator.moveNext())
        {
            msgStruct   =   new SysInfologMessageStruct(enumerator.currentMessage());

            exception   =   enumerator.currentException();

            error       =   strfmt("%1 %2", error, msgStruct.message());
        }

        return error;
    }

    public static utcdatetime getErrorDatetime()
    {

        SysInfologEnumerator        enumerator;

        SysInfologMessageStruct     msgStruct;

        Exception                   exception;

        str                         errormsg;

        utcdatetime                 errordatetime;

        enumerator      =   SysInfologEnumerator::newData(infolog.copy(1,infolog.num()));

        while (enumerator.moveNext())
        {
            msgStruct   =   new SysInfologMessageStruct(enumerator.currentMessage());

            exception   =   enumerator.currentException();

            errormsg       =   strfmt("%1 %2", errormsg, msgStruct.message());
        }

        if(errormsg!='')
        {
            errordatetime = DateTimeUtil::getSystemDateTime();
        }

        return errordatetime;
    }
}


That's all for now. Please let us know your questions or feedback in comments section !!!!

Monday, June 6, 2022

How to call an external web link through x++ in Dynamics 365 Fin Ops

 

Calling an external web link is very easy to implement. Sometimes we get this requirement to redirect user to a website based on customer's requirements.

We can easily do that using Browser class.


Here is the code mentioned below : - 


public static void main(Args _args)
{
    Browser browser = new Browser();

    browser.navigate('www.google.com', true, false);
}


That's all for now. Please let us know your questions or feedback in comments section !!!!

A Practical Guide to Using Event Handlers in D365 F&O (The Smart Way to Customize)

Customizing standard processes in Dynamics 365 Finance and Operations has evolved significantly. Gone are the days when overlayering was th...