3

This is a Follow up question to this. What I am trying to do is set the createdDate field in Account record using the below code as suggested by cropredy. I have enabled Enable "Set Audit Fields upon Record Creation" and "Update Records with Inactive Owners User Permissions". Here is my code.

Account acc = (Account) Json.deserialize('{"createdDate" : "2016-01-01T00:00:00Z","Name":"TempAccount"}',Account.class);
insert acc;
acc = [Select id, name, createdDate from Account where id =: acc.id];
System.debug(acc.id + '' + acc.CreatedDate);
3

I forgot, in V36.0, there's a new method in the Test class. Create the sObject and then use the method Test.setCreatedDate(..) on the ID of the sobject that needs a createdDate other than now. You have to do this before Test.startTest() From the doc:

public static void setCreatedDate(Id recordId, Datetime createdDatetime)


@isTest 
private class SetCreatedDateTest {
    static testMethod void testSetCreatedDate() {
        Account a = new Account(name='myAccount');
        insert a;
        Test.setCreatedDate(a.Id, DateTime.newInstance(2012,12,12));
        Test.startTest();
        Account myAccount = [SELECT Id, Name, CreatedDate FROM Account 
                             WHERE Name ='myAccount' limit 1];
        System.assertEquals(myAccount.CreatedDate, DateTime.newInstance(2012,12,12));
        Test.stopTest();
    }
}

Note - outstanding issue using this on Note, hopefully resolved by time someone looks at this answer in the future (Summer 16+).

1

The "Set Audit Fields upon Record Creation" permission applies only to the API (being called via SOAP/REST from an external tool), cf. https://help.salesforce.com/apex/HTViewSolution?urlname=Enabling-Create-Audit-Fields&language=en_US The reasoning I think being that you want to be able to set those dates when you migrate from other systems, but not in other cases.

You are however trying to set the CreatedDate from within APEX code rather than via the API. So here, the permission doesn't apply and there is no alternative permission to my knowledge to allow you to set the CreatedDate from within APEX. I guess what you could do is make a REST/SOAP call from the APEX code to your own org... but it is a crooked solution.

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.