Showing posts with label Forms. Show all posts
Showing posts with label Forms. Show all posts

Tuesday, 23 August 2022

Allocate multiple number sequence while creating the purchase order in d365 F&O

1. Create a new Table to manage Number sequence Code with CodeID and  add the relation to Number sequence Code with NumberSequenceTable like as a Fixed asset Table

2. Create a new form to manage CodeID and number sequence code Fields 

3. Create a CodeID Field that needs to add to the purchcreateOrder form and PurchTable form 

4. Purchase order number sequence should be set to manual from procurement and sourcing -> parameters-> number sequence form 

5. Create two new classes which extend the standard forms 

 /// <summary>

/// This class is a COC of PurchCreateOrder form

/// </summary>

[ExtensionOf(formDataFieldStr(PurchCreateOrder, PurchTable, TSSSourceApplicationCode))]

final class PurchCreateOrderFormDSField_TSS_Extension

{

    public NumberSeq           purchIdNumberSeq;

    public PurchId             purchIdAllocated;


    /// <summary>

    /// This method is used to modify the values

    /// </summary>

    public void modified()

    {

        FormDataObject dataObject = any2Object(this) as FormDataObject;

        FormDataSource ds = dataObject.datasource();

        PurchTable     purchTable = ds.cursor();

        #Define.empty('')


        next modified();

                

        if (purchIdNumberSeq)

        {

            purchIdNumberSeq.abort();

        }

        

        if (purchTable.TSSSourceApplicationCode)

        {

            purchIdNumberSeq =  NumberSeq::newGetNumFromId(TSSPurcTSSurceApplication::find(purchTable.TSSSourceApplicationCode).NumberSequencecode, true);

            if (purchIdNumberSeq)

            {

                PurchTable.purchid = purchIdNumberSeq.num();

                if (PurchTable.purchid)

                {

                    purchIdAllocated   = PurchTable.purchid;

                    ds.object(fieldNum(PurchTable, PurchId)).allowEdit(false);

                }

                else

                {

                    ds.object(fieldNum(PurchTable, PurchId)).allowEdit(true);

                }

            }

            

        }

        else 

        {

            PurchTable.purchid = #empty;

            ds.object(fieldNum(PurchTable, PurchId)).allowEdit(false);

        }


        if (purchIdNumberSeq)

        {

            element.parmPurchIdNumberSeq(purchIdNumberSeq);

        }

    }


}


-----------------------------------------------------------------------------------------------

/// <summary>

/// This class is a COC of PurchCreateOrder form

/// </summary>

[ExtensionOf(formStr(PurchCreateOrder))]

final class PurchCreateOrderFrom_TSS_Extension

{

    public NumberSeq purchIdNumberSeq;


    /// <summary>

    /// this mthod is use to pass the parm values

    /// </summary>

    /// <param name = "_numberSeq">_numberSeq</param>

    /// <returns>NumberSeq</returns>

    public NumberSeq parmPurchIdNumberSeq(NumberSeq  _numberSeq)

    {

        purchIdNumberSeq = _numberSeq;


        return purchIdNumberSeq;

    }


    /// <summary>

    /// This method is called with we close the form

    /// </summary>

    public void close()

    {

        if (! PurchTable.RecId && purchIdNumberSeq)

        {

            purchIdNumberSeq.abort();

        }

       else if  if (PurchTable.RecId && purchIdNumberSeq)

      {

             purchIdNumberSeq.used();

       }

        next close();

    }


    /// <summary>

    /// This method is used to run the logic

    /// </summary>

    void run()

    {

        next run();


        PurchTable_ds.object(fieldNum(PurchTable, PurchId)).allowEdit(false);

    }


}

Wednesday, 23 March 2022

Add logo to form in d365 F&O

 /// <summary>

/// This class is a EventHandler of vend paramters

/// </summary>

class XDDVendParametersEventHandler

{

    /// <summary>

    /// This method is used to remove the image

    /// </summary>

    /// <param name="sender">FormControl</param>

    /// <param name="e">FormControlEventArgs</param>

    [FormControlEventHandler(formControlStr(VendParameters, Remove), FormControlEventType::Clicked),

    SuppressBPWarning('BPParameterNotUsed','False positive')]

    public static void Remove_OnClicked(FormControl sender, FormControlEventArgs e)

    {

        FormDataSource  vendParameters_ds  = sender.formRun().dataSource(0) as FormDataSource;

        VendParameters  VendParameters     = vendParameters_ds.cursor() as VendParameters;


        if (VendParameters.RecId)

        {

            ttsbegin;

            VendParameters.selectForUpdate(true);

            VendParameters.XDDSignature    = conNull();

            VendParameters.update();

            ttscommit;

        }


        vendParameters_ds.research(true);

    }


    /// <summary>

    /// This method is used to change the image

    /// </summary>

    /// <param name="sender">FormControl</param>

    /// <param name="e">FormControlEventArgs</param>

    [FormControlEventHandler(formControlStr(VendParameters, Change), FormControlEventType::Clicked),

    SuppressBPWarning('BPParameterNotUsed','False positive')]

    public static void Change_OnClicked(FormControl sender, FormControlEventArgs e)

    {

        FormDataSource  vendParameters_ds   =  sender.formRun().dataSource(0) as FormDataSource;

        VendParameters  vendParameters      = vendParameters_ds.cursor() as VendParameters;

        str             imageFilePathName;

        ;


        imageFilePathName = XDDVendParametersEventHandler::uploadImageFile();


        if (imageFilePathName && vendParameters)

        {

            ttsbegin;

            vendParameters.selectForUpdate(true);

            vendParameters.XDDSignature = ImageReference::GetPackedBinaryData(imageFilePathName);

            vendParameters.update();

            ttscommit;

        }


        vendParameters_ds.research(true);

    }


    /// <summary>

    /// This method is used to call OnActivated

    /// </summary>

    /// <param name="sender">FormDataSource</param>

    /// <param name="e">FormDataSourceEventArgs</param>

    [FormDataSourceEventHandler(formDataSourceStr(VendParameters, VendParameters), FormDataSourceEventType::Activated),

    SuppressBPWarning('BPParameterNotUsed','False positive')]

    public static void VendParameters_OnActivated(FormDataSource sender, FormDataSourceEventArgs e)

    {

        VendParameters          vendParameters  = sender.cursor() as VendParameters;

        FormWindowControl       logoImage       = sender.formRun().design().controlName(formControlStr(VendParameters, LogoImage)) as FormWindowControl;

        Image                   image;


        if (vendParameters.XDDSignature)

        {

            image = new Image();

            image.setData(vendParameters.XDDSignature);

            logoImage.image(image);

        }

        else

        {

            logoImage.image(null);

        }


    }


    /// <summary>

    /// This method is used to upload image file

    /// </summary>

    /// <returns>str</returns>

    public static str uploadImageFile()

    {

        FormRun         visualForm;

        FileUpload      fileUploadControl;

        str             imageFilePathName;

        ;


        visualForm = classFactory::formRunClassOnClient(new Args(formstr(SysGetFileFromUser)));

        visualForm.init();

        visualForm.design().caption("@ApplicationPlatform:GetFileImageCaption");


        fileUploadControl = visualForm.design().controlName('FileUpload1');


        visualForm.run();

        visualForm.wait();


        FileUploadTemporaryStorageResult fileUploadResult = fileUploadControl.getFileUploadResult();


        if (fileUploadResult != null && fileUploadResult.getUploadStatus())

        {

            imageFilePathName = fileUploadResult.getDownloadUrl();

        }


        return imageFilePathName;

    }


}

Sunday, 6 March 2022

Create general journal using X++ in D365FO

 The general journal can be created using X++ code. This code which I am sharing in this article helps you to create general journal using X++ in D365FO.

In Microsoft Dynamics 365 for Finance and Operations, creating the general journal through X++ is different than creating in Microsoft Dynamics AX 2012. In D365FO, there is an abstract class named as MCRLedgerJournal, which you have to inherit and implement by yourselves.

I have created the MCRLedgerJournal_XYZ class which inherits (extends) the abstract class. To see how to implement the abstract class, you can get the example by viewing MCRLedgerJournal_CustPayment, MCRLedgerJournal_Daily and MCRLedgerJournal_Payment etc. classes.

In our case, I have copied the MCRLedgerJournal_Daily class and pasted it in my own class (MCRLedgerJournal_XYZ) and modifies it according to my requirements. Apart from this, you can also use the MCRLedgerJournal_Daily class directly if you don’t want to implement your own class.

Following is the code to implement the MCRLedgerJournal abstract class.

class MCRLedgerJournal_XYZ extends MCRLedgerJournal
{
    public LedgerJournalTrans createLedgerJournalTrans(AmountCurCredit _amtCurCredit, AmountCurDebit _amtCurDebit, LedgerJournalACType _ledgerJournalACType = LedgerJournalACType::Ledger)
    {
        LedgerJournalTrans ledgerJournalTrans;

        // Validate the input to the ledger journal trans and ensure that a ledgerjournaltable
        // exists before creating the ledger journalTrans.
        if (this.validateInputLedgerJourTrans(_amtCurCredit, _amtCurDebit)
            && ledgerJournalTable.RecId != 0)
        {
            this.initLedgerJournalTrans(ledgerJournalTrans);

            ledgerJournalTrans.JournalNum = ledgerJournalTable.JournalNum;
            ledgerJournalTrans.AccountType = LedgerJournalACType::Ledger;
            ledgerJournalTrans.LedgerDimension = ledgerAccount;
            ledgerJournalTrans.OffsetAccountType = ledgerOffsetAccountType;
            ledgerJournalTrans.OffsetLedgerDimension = ledgerOffsetAccount;
            ledgerJournalTrans.Txt = transTxt;
            ledgerJournalTrans.CurrencyCode = curCode;
            ledgerJournalTrans.ExchRate = exchRate;
            ledgerJournalTrans.Approver = approver;
            ledgerJournalTrans.Approved = approved;
            // Bank reconciliation specific.
            ledgerJournalTrans.MCRCCGeneralLedgerId = MCRCCGeneralLedgerId;
            ledgerJournalTrans.Due = dueDate;
            ledgerJournalTrans.LineNum = lineNum;
            ledgerJournalTrans.AccountType = ledgerAccountType;
            ledgerJournalTrans.Voucher = voucherNum;
            ledgerJournalTrans.PaymReference = paymReference;
            ledgerJournalTrans.BankTransType = bankTransType;
            ledgerJournalTrans.PaymMode = paymentMode;
            // Add the ref paym id and the paym order id to ledger journal trans.
            ledgerJournalTrans.MCRRefPaymID = MCRRefPaymID;
            ledgerJournalTrans.MCRPaymOrderId = MCRPaymOrderID;

            if (_amtCurCredit != 0)
            {
                ledgerJournalTrans.AmountCurCredit = _amtCurCredit;
            }
            if (_amtCurDebit != 0)
            {
                ledgerJournalTrans.AmountCurDebit = _amtCurDebit;
            }
            ledgerJournalTrans.initValue();
            ledgerJournalTrans.defaultRow();

            ledgerJournalTrans.insert();
        }
        else
        {
            throw error("@MCR35845");
        }

        return ledgerJournalTrans;
    }

    /// <summary>
    /// Creates a new instance of the <c>MCRLedgerJournal_Daily</c> class.
    /// </summary>
    /// <param name="_ledgerJournalType">
    /// The type of journal to be used in the instantiation of this class.
    /// </param>
    /// <param name="_journalName">
    /// The name of the journal to be used in the instantiation of this
    /// class; optional.
    /// </param>
    public void new(LedgerJournalType _ledgerJournalType, LedgerJournalNameId _journalName="")
    {
        super(_ledgerJournalType, _journalName);
    }

    protected boolean validateInputLedgerJourTrans(AmountCur _amtCurCredit, AmountCur _amtCurDebit)
    {
        boolean ret;

        ret = super(_amtCurCredit, _amtCurDebit);
        if (ret)
        {
            if (ledgerAccount == 0)
            {
                throw error(strFmt("@MCR36388"));
            }
        }
        return ret;
    }

}

Now, the next step is to create the General journal using the above created class. I have written a job which creates the General journal using X++. See the following code:

class GenerateGeneralJournalJob
{
    /// <summary>
    /// Runs the class with the specified arguments.
    /// </summary>
    /// <param name = "_args">The specified arguments.</param>
    public static void main(Args _args)
    {       
        MCRLedgerJournal        journalTable;
        LedgerJournalTable      ledgerJournalTable;
        Counter                 recordsInserted;

        ttsbegin;
        //Creates the journal header table
        journalTable = new MCRLedgerJournal_XYZ(LedgerJournalType::Daily);        
        ledgerJournalTable = journalTable.createLedgerJournalTable();
        journalTable.parmLedgerJournalTable(ledgerJournalTable);
        journalTable.parmMCRCCGeneralLedgerId();
        journalTable.parmCurrencyCode(CompanyInfoHelper::standardCurrency());


        //I am creating two lines to balance out each other.

        // creates a new line in general journal
        journalTable.parmLineNum();
        journalTable.parmLedgerAccountType(LedgerJournalACType::Vend);
        journalTable.parmLedgerAccount(LedgerDynamicAccountHelper::getDynamicAccountFromAccountNumber("V-000001",LedgerJournalACType::Vend)); //You need to use the vendor account as per your environment's data.
        journalTable.parmTransDate(today());
        journalTable.parmTransTxt("txt");
        journalTable.createLedgerJournalTrans(abs(0),abs(100),LedgerJournalACType::Vend);

        // creates a new line in general journal
        journalTable.parmLineNum();
        journalTable.parmLedgerAccountType(LedgerJournalACType::Ledger);
        //Using RecId of Ledger Dimension, you need to enter the RecId as per your environment's data.
        journalTable.parmLedgerAccount(5637179073); 
        journalTable.parmTransDate(today());
        journalTable.parmTransTxt("txt");
        journalTable.createLedgerJournalTrans(abs(100),abs(0),LedgerJournalACType::Ledger);
        ttscommit;
    }

}

Thursday, 3 March 2022

QueryExecuting in D365 F&O

 [FormDataSourceEventHandler(formDataSourceStr(CustPaymEntry, CustTransOpen), FormDataSourceEventType::QueryExecuting)]

public static void CustTransOpen_OnQueryExecuting(FormDataSource sender, FormDataSourceEventArgs e)

{

sender.query().dataSourceTable(tableNum(CustTransIdRef)).addRange(fieldnum(CustTransIdRef,TransRefType)).value(queryValue(CustTransRefType::Invoice));

}

ShowOpenDate Filter on form in D365 F&O

 [ExtensionOf(FormControlStr(CustTrans, ShowOpenDateFilter))]

final class DDDCustTransForm_ShowOpenDateFilterControl_Extension

{

    public boolean modified()

    {

        boolean         ret;

        FormDataSource  custTrans_ds = this.formRun().dataSource(1);

        element.criteriaOpen         = SysQuery::findOrCreateRange(custTrans_ds.query().dataSourceNo(1), fieldnum(CustTrans, Closed));

        ret = next modified();

        return ret;

    }

}

/// <summary>

/// Extension class of custtrans form

/// </summary>

[ExtensionOf(formDataSourceStr(CustTrans,CustTrans))]

final class DDDCustTransForm_Extension

{

    /// <summary>

    /// Extension of form execute query

    /// </summary>

    void executeQuery()

    {

        if (element.args().dataset() == tableNum(CustTable))

        {

            FormCheckBoxControl        myCheckBox            = element.design().controlName(formControlStr(CustTrans, DDDViewChildTransactions));

            //NoYes                    viewChildTransactions = myCheckBox.value();

            FormDataSource             custTrans_ds          = this.formRun().dataSource('CustTrans');

            CustTrans                  custTrans             = custTrans_ds.cursor();

            CustTable                  custTable             = element.args().record();;

            CustAccount                custAccount           = custTable.AccountNum;//custTrans.AccountNum;

            FormComboBoxControl        showOpenOptions       = element.design().controlName(formControlStr(CustTrans, ShowOpenOptions));

            EnumId                     enumId                = showOpenOptions.selection();

            FormDateControl            showOpenDateFilter    = element.design().controlName(formControlStr(CustTrans, ShowOpenDateFilter));

            date                       showDate              = showOpenDateFilter.dateValue();

        

            if (myCheckBox.checked())

            {

                DDDCustParentChild   parentCustomer;

                CustTable            custTableLoc;

                CustAccount          custId;

                container            custList;

            

                custList             = conNull();

                


                // get the all child customers of the parent

                while select parentCustomer

                join custTableLoc

                    where custTableLoc.RecId       == parentCustomer.ParentAccount

                    &&  custTableLoc.AccountNum    == custAccount

                {

                    custList += parentCustomer.ChildAccount;        

                }


                if(custList)

                {

                    this.query().dataSourceTable(tableNum(CustTrans)).clearRanges();

                    this.query().dataSourceTable(tablenum(CustTrans)).clearDynalinks();


                    for (int i = 1; i <= conLen(custList); i++) // adding all child ranges to query

                    {

                        custId         = conPeek(custList, i);

                        this.query().dataSourceName(custTrans_ds.name()).addRange(fieldnum(CustTrans, AccountNum)).value(queryValue(custId));

                    }


                    switch (enumId)

                    {

                        case CustVendShowTransaction::All:

                            this.query().dataSourceName(custTrans_ds.name()).addRange(fieldnum(CustTrans, Closed)).value(SysQueryRangeUtil::valueUnlimited());

                            break;


                        case CustVendShowTransaction::Open:

                            this.query().dataSourceName(custTrans_ds.name()).addRange(fieldnum(CustTrans, Closed)).value(strfmt('%1..', dateNull()));

                            break;


                        case CustVendShowTransaction::OpenAsOf:

                            this.query().dataSourceName(custTrans_ds.name()).addRange(fieldnum(CustTrans, Closed)).value(queryValue(dateNull()));

                            this.query().dataSourceName(custTrans_ds.name()).addRange(fieldnum(CustTrans, Closed)).value(strFmt(' > %1', queryValue(showDate)));

                            break;


                        case CustVendShowTransaction::Closed:

                            this.query().dataSourceName(custTrans_ds.name()).addRange(fieldnum(CustTrans, Closed)).value(SysQuery::valueNot(queryValue(dateNull())));

                            break;

                    }

                }

            }

            if(!myCheckBox.checked() && element.args().dataset() == tableNum(CustTable))

            {

                if (element.args().dataset() == tableNum(CustTable))

                {

                    custTable = element.args().record();

                    this.query().dataSourceTable(tableNum(CustTrans)).clearRanges();

                    this.query().dataSourceTable(tablenum(CustTrans)).clearDynalinks();

                    this.query().dataSourceName(custTrans_ds.name()).addRange(fieldnum(CustTrans, AccountNum)).value(queryValue(custTable.AccountNum));


                    switch (enumId)

                    {

                        case CustVendShowTransaction::All:

                            this.query().dataSourceName(custTrans_ds.name()).addRange(fieldnum(CustTrans, Closed)).value(SysQueryRangeUtil::valueUnlimited());

                            break;


                        case CustVendShowTransaction::Open:

                            this.query().dataSourceName(custTrans_ds.name()).addRange(fieldnum(CustTrans, Closed)).value(strfmt('%1..', dateNull()));

                            break;


                        case CustVendShowTransaction::OpenAsOf:

                            this.query().dataSourceName(custTrans_ds.name()).addRange(fieldnum(CustTrans, Closed)).value(queryValue(dateNull()));

                            this.query().dataSourceName(custTrans_ds.name()).addRange(fieldnum(CustTrans, Closed)).value(strFmt(' > %1', queryValue(showDate)));


                            break;


                        case CustVendShowTransaction::Closed:

                            this.query().dataSourceName(custTrans_ds.name()).addRange(fieldnum(CustTrans, Closed)).value(SysQuery::valueNot(queryValue(dateNull())));

                            break;

                    }


                }

            }

        }


        next executeQuery();

    }


}

Filter on form in D365 F&O

Add new checkbox DDDIsParent unbound control on CustTable (form) 

class DDDCustTableFormEventhandler

{

    [FormControlEventHandler(formControlStr(CustTable, DDDIsParent), FormControlEventType::Modified)]

    public static void DDDIsParent_OnModified(FormControl sender, FormControlEventArgs e)

    {

        FormCheckBoxControl  process = sender as FormCheckBoxControl;

        FormRun             fr                    = process.formRun();

        FormDataSource      CustTable_ds          = fr.dataSource('CustTable');

        CustTable_ds.executeQuery();

    }


[ExtensionOf(formDataSourceStr(CustTable,CustTable))]

final class DDDCustTableFormDS_Extension

{

    void executeQuery()

    {

        FormCheckBoxControl        myCheckBox            = element.design().controlName(formControlStr(CustTable, DDDIsParent));

        FormDataSource             custTable_ds          = this.formRun().dataSource('CustTable');

        if (myCheckBox.checked())

        {

            DDDCustParentChild   parentCustomer;

            CustTable            custTableLoc;

            str                  custId;

            container            custList;

            custList             = conNull();

            // get the all child customers of the parent

            while select PARENTACCOUNT from parentCustomer group by PARENTACCOUNT

            exists join custTableLoc

                where custTableLoc.RecId == parentCustomer.ParentAccount 

            {

                custList += CustTable::findRecId(parentCustomer.PARENTACCOUNT).AccountNum;

            }

            if(custList)

            {

                this.query().dataSourceTable(tableNum(CustTable)).clearRanges();

                this.query().dataSourceTable(tablenum(CustTable)).clearDynalinks();


                for (int i = 1; i <= conLen(custList); i++) // adding all child ranges to query

                {

                    custId         = conPeek(custList, i);

                    this.query().dataSourceName(custTable_ds.name()).addRange(fieldnum(CustTable, AccountNum)).value(queryValue(custId));

                }

            }

        }

        else 

        {

            this.query().dataSourceTable(tableNum(CustTable)).clearRanges();

            this.query().dataSourceTable(tablenum(CustTable)).clearDynalinks();

        }

        next executeQuery();

    }

}


Wednesday, 2 March 2022

Update vendor status to No in D365 F&O

vendTable.reread();

if (vendTable.Blocked != CustVendorBlocked::No)

{

VendTable::updateOnHold([vendTable], CustVendorBlocked::No, utcDateTimeNull(), false);

VendTableChangeProposal change = VendTableChangeProposal::findByVendRecId(vendTable.RecId, false);

if (change)

{

change.delete();

}

}

Tuesday, 22 February 2022

Copy data from one buffer to another buffer

static void CopyData(Args _args)

{

    InventTable inventTable;

    CopyInventTable copyInventTable ;

    while select inventTable

    {

         buf2Buf(inventTable ,copyInventTable );

         copyInventTable .insert();

    }

    info("Done");

}

Monday, 21 February 2022

Create vendor party id in d365 F&O

 vendTable.Party    = DDDCustVendGlobal::createPartyId(DirPartyType::Organization,vendorCreateContract.VendorOrganizationName(),LanguageID());

public static RefRecId createPartyId( DirPartyType    _partyType,

DirPartyName    _custVendName,

LanguageId      _sourceLanguageId )

{

FirstName                   firstName  = '';

MiddleName                  middleName = '';

LastName                    lastName   = '';

DirPerson                   person;

DirPersonName               personName;

DirPartyTable               partyRecord;

if (_partyType == DirPartyType::Person)

{

if (lastName == '')

{

[firstName, middleName, lastName] = DirPerson::splitNameParts(_custVendName);

}

person.initValue();

person.Name                           = _custVendName;

person.insert();

personName  = DirPersonName::addNewNameToPerson(person.RecId, firstName, middleName, lastName);

partyRecord = DirPartyTable::findRec(person.RecId, true);

}

else

{

partyRecord = DirPartyTable::createNew(_partyType, _custVendName);

}

partyRecord.LanguageId     = _sourceLanguageId;

partyRecord.update();

return partyRecord.RecId;

}

Sunday, 20 February 2022

OnInitialized FormEventHandler in D365 F&O

 class DDDInventJournalNameFormEventHandler

{

    [FormEventHandler(formStr(InventJournalName), FormEventType::Initialized),

    SuppressBPWarning('BPParameterNotUsed', 'False positive')]

    public static void InventJournalName_OnInitialized(xFormRun sender, FormEventArgs e)

    {

        FormRun       element = sender;

        FormControl   processBudget = element.design(0).controlName(formControlStr(inventJournalName, DDDBudget_DDDProcessBudget));

        FormControl   defaultGeneralJournal = element.design(0).controlName(formControlStr(inventJournalName, DDDBudget_DDDDefaultGeneralJournal));

        

        processBudget.visible(false);

        defaultGeneralJournal.visible(false);

    }

}

onValidatingField TableEventHandler in D365 F&O

class DDDInventJournalNameTableEventHandler

{

    [DataEventHandler(tableStr(InventJournalName), DataEventType::ValidatingField)]

    public static void InventJournalName_onValidatingField(Common sender, DataEventArgs e)

    {

        ValidateFieldEventArgs  validateFieldEventArgs = e as ValidateFieldEventArgs;

        InventJournalName       inventJournalName = sender as InventJournalName;

        boolean                 ret = validateFieldEventArgs.parmValidateResult();

        LedgerJournalName       ledgerJournalName;

        #Define.defaultGeneraljournal('Please provide the valid default general journal.')

         if(ret)

        {

            switch(validateFieldEventArgs.parmFieldId())

            {

                case fieldNum(InventJournalName,DDDDefaultGeneralJournal):

                    select firstonly ledgerJournalName

                        where ledgerJournalName.JournalName == inventJournalName.DDDDefaultGeneralJournal

                        && ledgerJournalName.DDDBudget == NoYes::Yes;

                    if (!ledgerJournalName.RecId && inventJournalName.DDDDefaultGeneralJournal)

                    {

                        ret = checkFailed(#defaultGeneraljournal);

                    }

                    break;

            }

        }

        if (!ret)

        {

            validateFieldEventArgs.parmValidateResult(false);

        }

    }

OnModified FormEventHandler in D365 F&O

class DDDInventJournalCreateFormEventHandler

{

    [FormControlEventHandler(formControlStr(InventJournalCreate, InventJournalTable_JournalNameId), FormControlEventType::Modified),

    SuppressBPWarning('BPParameterNotUsed', 'False positive')]

    public static void InventJournalTable_JournalNameId_OnModified(FormControl sender, FormControlEventArgs e)

    {

        FormDataSource      inventJournalTable_ds   = sender.dataSourceObject();

        InventJournalTable  inventJournalTable      = inventJournalTable_ds.cursor() as InventJournalTable;

        InventJournalName  inventJournalName = InventJournalName::find(inventJournalTable.JournalNameId);

        inventJournalTable.DDDFinancialDimensions   = (inventJournalName.DDDProcessBudget == NoYes::Yes) ? inventJournalName.DDDFinancialDimensions : 0;

        sender.formRun().design().controlName(formControlStr(InventJournalCreate, DDDTabFinancialDimensions)).visible(inventJournalName.DDDBudget == NoYes::Yes);

    }

}

OnActivated FormEventHandler in D365 F&O

class DDDInventJournalCreateFormEventHandler

{

    [FormDataSourceEventHandler(formDataSourceStr(InventJournalCreate, InventJournalTable), FormDataSourceEventType::Activated),  SuppressBPWarning('BPParameterNotUsed', 'False positive')]

    public static void InventJournalTable_OnActivated(FormDataSource sender, FormDataSourceEventArgs e)

    {

        InventJournalTable   inventJournalTable   = sender.cursor();

        sender.formRun().design().controlName(formControlStr(InventJournalCreate, DDDTabFinancialDimensions)).visible(InventJournalName::find(inventJournalTable.JournalNameId).DDDBudget == NoYes::Yes);

    }

}



Filter DataSource in form D365 FO

[Form]

public class DDD_ViewContracts extends FormRun

{

    [DataSource]

    class DDD_ViewContractsView

    {

        public void init()

        {

            if(element.args().record())

            {

                SalesTable   salesTable = element.args().record();

                super();

                Query q = DDD_ViewContractsView_ds.query();

                QueryBuildDataSource rootDS = q.dataSourceTable(tablenum(DDD_ViewContractsView));

                rootDS.clearRanges();

                QueryBuildRange range = rootDS.addRange(fieldnum(DDD_ViewContractsView, CustAccount));

                range.value(SysQuery::value(salesTable.CustAccount));

                range.status(RangeStatus::Locked);

                if(salesTable.InventLocationId)

                {

                    range = rootDS.addRange(fieldnum(DDD_ViewContractsView, LocationId));

                    range.value(SysQuery::value(salesTable.InventLocationId));

                    range.status(RangeStatus::Locked);

                }          

            }

        }

    }

Thursday, 17 February 2022

OnModified FormEventHandler in D365 FO

class NYXCustPaymEntryFormEventHandler

{

 [FormControlEventHandler(formControlStr(CustPaymEntry, NYXGlobalName), FormControlEventType::Modified)]

    public static void NYXGlobalName_OnModified(FormControl sender, FormControlEventArgs e)

    {

        FormdataSource      LedgerJournalTransDS = sender.formRun().dataSource(formDataSourceStr(CustPaymEntry, LedgerJournalTrans)) as FormDataSource;

        LedgerJournalTrans  ledgerJournalTrans   = LedgerJournalTransDS.cursor() as LedgerJournalTrans;


        ledgerJournalTrans.LedgerDimension = 0;

        LedgerJournalTransDS.object(fieldnum(ledgerJournalTrans,LedgerDimension)).modified();

    }

}

Wednesday, 9 December 2020

PO Registering in AX D365

class Class1
{
    public static void main(Args _args)
    {
        PurchLine               upPurchLine;
        InventTrans             inventtrans;
        InventTransWMS_Register inventTransWMS_register;
        InventBatch             inventBatch;
        TmpInventTransWMS       tmpInventTransWMS;
        InventDim               regInventDim;
        InventBatchId           inventBatchId;

        try
        {
            ttsbegin;
            upPurchLine = PurchLine::find('01PO00000122', 40);
            inventTransWMS_Register = InventTransWMS_Register::newStandard(tmpInventTransWMS);
            inventTrans             = InventTrans::findTransId(upPurchLine.InventTransId);
            tmpInventTransWMS.initFromInventTrans(inventTrans);
            tmpInventTransWMS.InventQty = 2;//Purchline.Qty;
            tmpInventTransWMS.LineNum   = int642int(upPurchLine.LineNumber);

            regInventDim.clear();
            regInventDim.InventSizeId    = 'AUTO';
            regInventDim.InventSiteId    = 'SIMPSON';
            regInventDim.InventLocationId= 'DW2';
            inventBatchId = 'Batch001';
            InventBatch=InventBatch::find(inventBatchId,upPurchLine.itemId);
            if(!InventBatch)
            {
                inventBatch.clear();
                inventBatch.itemId = upPurchLine.ItemId;
                inventBatch.inventBatchId=inventBatchId;
                inventBatch.insert();
            }

            regInventDim.inventBatchId  = inventBatch.inventBatchId;
            regInventDim.wMSLocationId  = 'Packing';
            regInventDim.InventStatusId = 'Available';
            regInventDim.LicensePlateId = '05082019';
            regInventDim = InventDim::findOrCreate(regInventDim);

            tmpInventTransWMS.ItemId      = upPurchLine.ItemId;
            tmpInventTransWMS.InventDimId = regInventDim.InventDimId;
            tmpInventTransWMS.insert();
            inventTransWMS_Register.writeTmpInventTransWMS(tmpInventTransWMS, inventTrans, InventDim::find(tmpInventTransWMS.InventDimId));
            if (!inventTransWMS_Register.updateInvent(upPurchLine))
            {
                throw Error("Error during purchase order registration");
            }
            else
            {
                info("done");
            }
            ttscommit;
        }
        catch (Exception::Error)
        {
            ttsabort;
            error("An error occurred. Please try again");
        }
    }

}

Friday, 22 June 2018

Call PurchCreateOrder form event handler in dynamics 365

public class GHMCPurchOrderCreateFormEventHandler
{
    [PostHandlerFor(formStr(PurchCreateOrder), formMethodStr(PurchCreateOrder, run))]
    public static void PurchCreateOrder_Post_run(XppPrePostArgs args)
    {
        FormRun formRun = args.getThis();

        if (formRun.args().menuItemName() == menuItemDisplayStr(GHMCAffidavitPurchCreateOrder))
        {
            FormDataSource formDataSource = formRun.dataSource(tableStr(PurchTable));
            PurchTable purchTable = formDataSource.cursor();
            purchTable.PurchPoolId = GHMCPurchParameters::find().AffidavitPurchPoolId;
        }
    }

    [FormDataFieldEventHandler(formDataFieldStr(PurchCreateOrder, PurchTable, OrderAccount), FormDataFieldEventType::Modified)]
    public static void OrderAccount_OnModified(FormDataObject sender, FormDataFieldEventArgs e)
    {
        FormDataSource formDataSource = sender.datasource();
        FormRun formRun = formDataSource.formRun();
         
        if (formRun.args().menuItemName() == menuItemDisplayStr(GHMCAffidavitPurchCreateOrder))
        {
            PurchTable purchTable = formDataSource.cursor();
            purchTable.PurchPoolId = GHMCPurchParameters::find().AffidavitPurchPoolId;
        }
    }
}

validate offsetLedgerDimension in d365 FO

 /// <summary> /// This class is used to validate offsetLedgerDimension /// </summary> class PNG_InventMovValidateOffsetLedgerDi...