Purpose:
This post provides an excellent example of how to set a form control value in X++. It also demonstrates how to control the visibility of form controls in X++. Additionally, it explains how to obtain the reference of a form control on the caller form to get its value in a simple and elegant manner.
Application:
Dynamics 365 for Finance and Operations
Business requirement:
Default vendor account from Purchase Order to Add Products form.
Solution:
We can use the following code to set the default value of a form control on a given form based on the form control from the caller form. In this scenario, we’re defaulting control value from Purchase Order form to Add Products form.
Code
internal final class ATLAS_RetailAddItems_Form_EventHandler
{
/// <summary>
/// Defaults vendor from PO to Add Products screen. Apr 14, 24 MK
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
[FormEventHandler(formStr(RetailAddItems), FormEventType::Initialized)]
public static void RetailAddItems_OnInitialized(xFormRun sender, FormEventArgs e)
{
FormStringControl ATLAS_ApprovedVendorControl;
FormDataSource purchTable_ds;
PurchTable purchTable;
FormRun callerFormRun;
FormRun formRun;
formRun = sender;
callerFormRun = formRun.args().caller();
if (callerFormRun.name() == formStr(PurchTable))
{
purchTable_ds = callerFormRun.dataSource(formDataSourceStr(PurchTable, PurchTable)) as FormDataSource;
purchTable = purchTable_ds.cursor() as PurchTable;
if (purchTable)
{
ATLAS_ApprovedVendorControl = formRun.control(formRun.controlId(formControlStr(RetailAddItems, ATLAS_ApprovedVendor)));
ATLAS_ApprovedVendorControl.text(purchTable.OrderAccount);
ATLAS_ApprovedVendorControl.modified();
}
}
else
{
formRun.control(formRun.controlId(formControlStr(RetailAddItems, ATLAS_VSplitterFilter))).visible(false);
formRun.control(formRun.controlId(formControlStr(RetailAddItems, ATLAS_MiddleGroup))).visible(false);
}
}
}