Friday, March 5, 2010

The Basics: Using X++ to throw a user-friendly message on an invalid table insert

Let’s say your customer needs a custom table called VisitorTable, which has an integer field called VisitorCount, and a date field called VisitDate. Duplicate dates are not allowed in the table, and once a record is entered into the system, only the VisitorCount field can be edited. Setting all of this up is rather simple in the AOT strictly using MorphX.

However, in addition, the customer has stated that they need a more user friendly error message displayed when an attempt is made to insert a record with a duplicate date. Performing this task is not quite as straight forward, and requires a little X++. One of any number possible solutions could work, one for example, is as follows:

To accomplish such functionality, you could override the aosValidateInsert () method on the VisitorTable with the following code:

public boolean aosValidateInsert()
{
boolean ret;
VisitorTable vt;
;

select vt
where vt.VisitDate == this.VisitDate;

if (vt.RecId)
{
ret = false;
throw error("The date already exists, you must specify a different date");
}
else
{
ret = super();
}

return ret;
}


This method is executed prior to an insert on the table. “this” is an object reference representing the record that is going to be inserted, thus we use the VisitDate value of “this” as the lookup in our query. If a record is returned matching that date, which is flagged by the existence of a RecId, then we can throw a more user friendly error alerting the user of this issue, otherwise, continue.

2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. why can't we use validatewrite instead aosValidateInsert

    ReplyDelete