Search code examples
salesforceapex

How can i insert a custom object into Slaesforce using Apex with requiredfields that are non-writeable?


A client has created a custom object call CustObj__c in Salesforce. They have required fields , one is Cust_Id which is of type Formula (Text)

I am trying to create a Custom Object item using the following

List<CustObj__c> CustList = new List<CustObj__c>();
CustObj__c Item_0 = new CustObj__c( Name__c='TEST1',  Cust_Id='Cust: '& 123);
CustList.add(Item_0); 
CustObj__c Item_1 = new CustObj__c( Name__c='TEST2', CustId__c='Cust: '& 456);   
CustList.add(Item_1);
insert CustList;

But it gives the error that Field is not writeable: CustObj__c.CustId__c

How can i insert if the field is non writeable but required ?

If it is a custom metadata object , do i need to do this ?

client hasnt provided any details


Solution

  • Formula fields are calculated at runtime when you view the record and are readonly, can't be marked as required. If your client has business need for it to be required they probably created a validation rule that checks the field value.

    You'll have to inspect the field's formula and insert data that would satisfy it. (Some other fields populated, maybe some dates or right amounts). Maybe they assign customer id(?) in some special way, only if account reaches certain status, moves from prospect to paying customer.

    You could ask them if they ever had to write unit tests that insert these records and steal get inspired by these code samples, see what prerequisites there are or fields that impact that formula.