I'm writing a method that has to insert a clone of a given record of Object__c.
I'm obtaining the clone performing a deep clone. That is:
object.clone(false, true, false, false)
The insertion of the clone fails because of “duplicate value found: 'unknown' duplicates value on record with id: 'unknown'” error.
There is a workflow rule that updates the field unique__c to be equal to 'C' + Object__c.Name. And the field unique__c has to be, indeed, unique. If I modify unique__c to not be unique I can insert the clone. Name is non writeable auto number, so I cleared unique__c in the clone before trying to insert it like:
clone.unique__c = null
But it still gives me the error. Per the workflow rule, I guess the unique__c field is populated with 'C' + the name as expected, but before doing the insert I compare the original object's name and the cloned one's and they differ. The latter is null.
Why can't I insert this clone? I got it clear from the steps above that the problem is the unique__c field so: Why, if I clear it before inserting, do I still get the error? Also, I checked that the Name of the clone is null before inserting so the workflow should not set nothing or set null in unique__c so, how come it gets to interfere with the insert?
PS: This is all being done in a test without seeing all data, so I discarded that there was already a record of Object__c that had unique__c to null.