Dynamics 365 Finance and Operations: How to overwrite system fields.

In some cases, we need to modify the values of system fields. Below is a code example of how to do this. The key points are the "OverwriteSystemFieldsPermission" and "overwriteSystemFields" commands:

public void insert()

{
   // Assert and enable the system overwrite permission and metadata property.
   new OverwriteSystemfieldsPermission().assert();

   this.overwriteSystemfields(true);

   this.setAuditFieldsAnonymous();

   super();

   // Revert and disable the system overwrite permission and metadata property.
   this.overwriteSystemfields(false);
   CodeAccessPermission::revertAssert();
}

public void update()

{
   // Assert and enable the system overwrite permission and metadata property.
   new OverwriteSystemfieldsPermission().assert();

   this.overwriteSystemfields(true);
   this.setAuditFieldsAnonymous();
     
   super();
 
   // Revert and disable the system overwrite permission and metadata property.
   this.overwriteSystemfields(false);
   CodeAccessPermission::revertAssert();
}

public void setAuditFieldsAnonymous()

{
   utcdatetime  now = DateTimeUtil::utcNow();
   SysDictField createdByField;
   SysDictField createdDateTimeField;
   SysDictField modifiedByField;
   SysDictField modifiedDateTimeField;

   createdByField = new SysDictField(tableNum(Table), 

                                    fieldNum(Table, CreatedBy));
   createdDateTimeField = new SysDictField(tableNum(Table), 
                                           fieldNum(Table, CreatedDateTime));
   modifiedByField = new SysDictField(tableNum(Table), 
                                      fieldNum(Table, ModifiedBy));
   modifiedDateTimeField = new SysDictField(tableNum(Table), 
                                            fieldNum(Table, ModifiedDateTime));
           

   if (createdByField.isSQL())

   {
      this.(fieldNum(Table, CreatedBy)) = '';
   }

 

   if (modifiedByField.isSQL())
   {
      this.(fieldNum(Table, ModifiedBy)) = '';
   }

 

   if (modifiedDateTimeField.isSql())
   {
      this.(fieldNum(Table, ModifiedDateTime)) = now;
   }

 

   if (this.RecId == 0 && createdDateTimeField.isSql())
   {
      // CreatedDateTime is only set on insert.
      this.(fieldNum(Table, createdDateTime)) = now;
   }
}

Dynamics 365 Finance and Operations: How to overwrite system fields.

In some cases, we need to modify the values of system fields. Below is a code example of how to do this. The key points are the " Overw...