UPDATE: AFter I have tried with the @Adrian approach I'm getting the following error now:
|EXCEPTION_THROWN|[65]|System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATE_VALUE, duplicate value found: unknown duplicates value on record with id: a1cV00000005bDm: [] |FATAL_ERROR|System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATE_VALUE, duplicate value found: unknown duplicates value on record with id: a1cV00000005bDm: []
Here is my code that executing my soql query
SObject existingRecord = Database.query('Select name, field2, field3....from where id='xyz');
SObject newRecord = sObjectId.getSObjectType().newSObject(sObjectId);
newRecord = existingRecord.clone(false, false, false, false);
insert newRecord;
UPDATE END
I'm in the process of creating a customize cloning so I have created custom button
which will invoke from Standard page layout that will call the apex class... I can't use standard cloning functionality because I have other business rules that user will select (through config) which fields to be clone etc...
I'm stuck on how to populate the values from old record to new one.
the whole purpose of this is to make generic so no hard-coding any object name or fields or anything.
I have asked the question here you can have a look to get the context of my question or I can copy and past it here if needed.
I'm having issue with the code block:
INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id
Understand that you can't have Id
when you are inserting a new record and I get it but given this scenario what will be the case?
String objPrefix = sObjectId.getSobjectType().getDescribe().getKeyPrefix();
SObject existRecord = Database.query(buildSOQL());
SObject newRecord = sObjectId.getSObjectType().newSObject(sObjectId);
newRecord = existRecord;
insert newRecord; //error
Any idea how would I (better) approach.