we have a approval system and when every step is approved it updates Revision number. There is a trigger on the change of Revision Number, which is responsible for cloning the the existing record and relinking the related list of file attachments to this new clone. My problem is that instead of cloning the record once its been cloned twice. I checked all other places and there is no where else this is getting triggered except below code.
trigger SaveHistory on PA_Process__c (after Update) {
private String query {get; set;}
private String sObjectApiName = 'PA_Process__c';
for (PA_Process__c PA : Trigger.New) {
PA_Process__c oldPA = Trigger.oldMap.get(PA.ID);
if (PA.PA_Rev_No__c != Trigger.oldMap.get(PA.Id).PA_Rev_No__c && PA.clone__c == false) {
Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();
Schema.SObjectType ctype = gd.get('PA_Process__c');
Map<String, Schema.SobjectField> fmap = ctype.getDescribe().fields.getMap();
String commaSepratedFields = '';
for (String fieldName : fMap.keyset()) {
if (fieldName != 'Id' && fieldName != 'ID') {
if (commaSepratedFields == null || commaSepratedFields == '') {
commaSepratedFields = fieldName;
} else {
commaSepratedFields = commaSepratedFields + ', ' + fieldName;
}
if (commaSepratedFields.endsWith(',')) {
commaSepratedFields = commaSepratedFields.substring(0, commaSepratedFields.lastIndexOf(','));
}
}
}
query = 'select ' + commaSepratedFields + ' from ' + SobjectApiName + ' where id = \'' + oldPA.ID + '\' Limit 1';
System.debug('##### Query: Field Clone = ' + query );
System.debug('##### Clone: Field Clone = ' + commaSepratedFields );
PA_Process__c PAValues = Database.query(query);
PA_Process__c PAClone = PAValues.Clone(false);
PAClone.PA_Rev_No__c = oldPA.PA_Rev_No__c;
PAClone.clone__c = true;
PAClone.parentIdForclones__c = oldPA.id;
PAClone.StandardStat__c = 'Approved-History';
PAClone.Master_Approval_Status__c = 'Approved-History';
insert PAClone;
String id = PAClone.id;
/* for cloning the child which is attahment*/
List<LinkAttachment__c> files = new List<LinkAttachment__c>();
for (LinkAttachment__c file : [Select la.Id, la.Filename__c, la.Filelink__c, la.Description__c, la.File_Location__c, la.PAId__c From LinkAttachment__c la where PAId__c = : oldPA.id]) {
LinkAttachment__c newfile = file.clone(false);
newfile.PAId__c = PAClone.id;
newfile.id = file.id;
files.add(newfile);
}
Update files;
}
}
}