Tuesday, October 3, 2017

D365: passing through public method by means of Pre- and Post-event handlers

Let's say we need to change the logic of a standard public method in terms of Extensions approach in D367 (AX7).

The whole idea is basically in saving values provided by XppPrePostArgs parameter in Pre-event handler method in new parameters and then restoring them in Post- one from the latter.

pre()>Save
standard method()
post()>Restore

For example, our business scenario is to allow the user to select Default company without selecting a Project while creating a new Purchase requisition. (I added a new parameter to the module)



Therefore, we have to change the logic of validateCoexistenceOfProjectAndBuyingLegalEntity method, which is called inside of PurchReqTable.validateWrite().

Standard, it does not allow to have an empty Project once Default company is chosen.


First, we create Pre- and Post-event handlers.



Then we put them into a new class and add new "by-passing" logic.


class PurchReqTableHandler
{
    #define.CompanyInfoDefaultArgName('CompanyInfoDefaultArgName')
    
    [PreHandlerFor(tableStr(PurchReqTable), tableMethodStr(PurchReqTable, validateCoexistenceOfProjectAndBuyingLegalEntity))]
    public static void PurchReqTable_Pre_validateCoexistenceOfProjectAndBuyingLegalEntity(XppPrePostArgs _args)
    {
        RefRecId        companyInfoDefault;
        PurchReqTable   purchReqTable   = _args.getThis();

        if(PurchParameters::find().PurchReqAllowCmpInfoDefWithoutProjId)
        {
            
            // if the user opted for setting Company without a project
            // we have to save it and use after this standard validation process
            if ( !purchReqTable.ProjId && purchReqTable.CompanyInfoDefault)
            {
                companyInfoDefault                  = purchReqTable.CompanyInfoDefault;
                purchReqTable.CompanyInfoDefault    = 0;
            }
            // make it zero to pass through the standard validation
            _args.setArg(#CompanyInfoDefaultArgName, companyInfoDefault);
        }
    }

   
    [PostHandlerFor(tableStr(PurchReqTable), tableMethodStr(PurchReqTable, validateCoexistenceOfProjectAndBuyingLegalEntity))]
    public static void PurchReqTable_Post_validateCoexistenceOfProjectAndBuyingLegalEntity(XppPrePostArgs _args)
    {
        boolean         ret;
        RefRecId        companyInfoDefault;
        PurchReqTable   purchReqTable   = _args.getThis();

        if(PurchParameters::find().PurchReqAllowCmpInfoDefWithoutProjId)
        {
            ret                 = _args.getReturnValue();
            companyInfoDefault  = _args.getArg(#CompanyInfoDefaultArgName);
            purchReqTable       = _args.getThis();
            // restore it
            if (ret && companyInfoDefault && !purchReqTable.CompanyInfoDefault)
            {
                purchReqTable.CompanyInfoDefault = companyInfoDefault;
            }
        }
    }

}