Monday, April 7, 2014

Modify the System fields in a Table

The system fields in Dynamics AX are the CreatedBy, ModifiedBy, Created Date Time, Modified Date Time, Partition, DataareaId, RecId, these fields are not directly modifiable by the users as they are auto generated during insert and update operations. If in any case you are doing a migration or would need to capture some relevant user id or created/modified date time you can still do it. Here is how,

First inform the kernel and as proper permission for the OverwriteSystemfieldsPermission.assert() and then activate the relevant table's overwriteSystemFieldsmethod - True to indicate these tables system fields values will be provided, however for the values that you don't provided the system will still populate with the default values. To refer to the fields use the tables field id's rather than the intellisense field name. Update remaining business column values and then insert the record. Make sure to set back the overwriteSystemFields method - False to revert to the settings. 

So the sample code would look like this.

Table      sampleTable;

ttsbegin;

new OverwriteSystemFieldsPermission().assert();
sampleTable.clear();
sampleTable.overwriteSystemFields(True);
sampleTable.(fieldNum(Table, CreatedBy) = 'DM-Admin'; //User id - If possible get from SysUserInfo table
sampleTable.(fieldNum(Table, ...othersystemFields)) = //Use appropirate assignment for the system fields
sampleTable.NormalColumns = //Your normal business column values
sampleTable.insert();
sampleTable.overwriteSystemFields(false);

CodeAccessPermission::revertAssert();

ttscommit;