03 May 2016

How to make enum a mandatory field on a table

It seems obvious, just set Mandatory property on a field to Yes. Is it enough? No.

Problem description
Null value concept is important for a mandatory field, but null values are not supported in Dynamics AX. Instead there are default values for each data type and they are considered null.
For enum it is an element with value set to 0. An assumption can be made that it shouldn't be possible to select and save enum element with value 0 on mandatory field. MSDN post proves the assumption:
"when the validateField method checks whether a user has entered a value in a mandatory field ...
the first entry is not accepted in an enum type field".
In another MSDN post there is an alternative requirement:
"If you want to make an enum a mandatory field on a table, make the first outcome with the value zero, as none, with the label Not selected"
What is correct? Let's analyse. You can also jump to the conclusion section.
Solution
Let's make different enums mandatory fields on a test table.
Case 1. Enum without None element
The first element of ABCModel enum is Revenue with value 0:
Let's add a field based on the enum and set Mandatory property to Yes:
There is no indication of mandatory field and the first element with value 0 is available in lookup:
It is possible to select and save element with value 0, in SQL 0 is saved:
It is not an expected behaviour.

Case 2. Enum with None element
The first element of ABC enum is None:
Let's add a field based on the enum and set Mandatory to Yes:
The field is marked as mandatory and the element with value 0 is eliminated in lookup:
An error is thrown on attempt to save empty value:
Let's select B and save the record:
2 is saved in SQL:

Conclusion
If you want to make an enum a mandatory field on a table, then you should at least make the first element of the enum with the value 0 as None and set Mandatory property on the field to Yes. Best practises include setting Label to Not selected.

No comments:

Post a Comment