2

I'm trying to version a package that has a class that creates a Task record setting it's createdById. The assignment looks like this:

newTask.CreatedById = Utils.userID; 

However, when trying to version the DX package by running the following command:

sfdx force:package:version:create -p sf-common-classes --definitionfile config/project-scratch-def.json -d force-app -k Password123 --wait 10 --codecoverage 
--targetdevhubusername DevHub

We get an error: Field is not writeable: Task.CreatedById

Please note that this file is already saved in our Production Org (DevHub) and the feature already works.

Here is how our scratch org definition file looks like:

{
  "orgName": "Anything for this post",
  "edition": "Developer",
  "features": [
    "StateAndCountryPicklist",
    "PersonAccounts",
    "ProductsAndSchedules",
    "LiveAgent",
    "ContactsToMultipleAccounts",
    "Communities",
    "EinsteinBuilderFree",
    "AddCustomRelationships:5",
    "FieldAuditTrail"
  ],
  "settings": {
    "lightningExperienceSettings": {
      "enableS1DesktopEnabled": true
    },
    "mobileSettings": {
      "enableS1EncryptedStoragePref2": false
    }
  }
}
3

The problem is your original orgs including the scratch org or developer org can manually enable the feature Enable Create Audit Fields by following instructions here

When you create an unlocked/2GP package version, a scratch org is created behind scenes and you do not have any control over the same.

Unfortunately, there is no setting in Metadata API to expose Enable Create Audit Fields at this point. So you cannot add them to setting object in your scratch org definition file.

Workaround

Modify your test class and move away from directly assigning the CreatedById field.

Instead simply use System.RunAs() {} with appropriate user to create the Task so the createdBy is set to the user you want.

0

If you are facing compilation issue you can use SObject and try to add the field as shown below.

SObjectType taskSObjectType = Get your Task SObject Type;        
SObject taskSObject = taskSObjectType.newSObject();
taskSObject.put('CreatedById', Utils.userID);

Not sure if this will fail test class run or not. But should not give any compilation issue.

2
  • 1
    The test run will fail here and test run is also done during package creation! Hence the package creation will be blocked! Apr 30 at 4:07
  • 1
    Ok, in that case, this wont help. Apr 30 at 5:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.