Tuesday, March 10, 2020

Data validation by ValidateField and ValidateWrite (old but good)

The most time data are meant to be changed by a user via different kinds of forms or even without it, and sometimes we need to implement additional business logic there.

Say, we want that a discount never be more than 10%, while a user creates lines in a sales order. For such a scenario the best way is to implement ValidateField and check the value for the field of Discount. After that the form does not allow the user to leave the field of discount until its value is less or equal to 10%.

public boolean validateField(FieldId _fieldIdToCheck)
    boolean ret;

    ret = super(_fieldIdToCheck);
        case fieldNum(MySalesLine, Discount):
            if(this.Discount <= 10)
               ret = true;
                ret = checkFailed("Discount cannot be more than 10%");

    return ret;

But we should remember that ValidateField method is called automatically for a form data source field only.

In other words, if the table record is inserted or updated by code, this logic will be NOT triggered.

            public boolean validate()
     public boolean validateField(FieldId _fieldIdToCheck)

So, if we need to implement validation logic for the whole record, which is supposed to be triggered every time Insert or Update is called (not for form data sources only), we go with ValidateWrite.

Thanks Mohamed for this brilliant article Microsoft dynamics ax2012 : forms and tables methods call sequences, How To? Watch this presentation! It contains much more very useful information.

No comments: