[SalesForce] Rename Attachment Name

I want to replace the attachment Name (File Name) with the ParentName. So can I replace the attachment name?

I have written the trigger on attachment an object. But Trigger is not working because of parent.name field is accessible after the insertion of an attachment.

Please find the code below

trigger renameAttachment on Attachment (before insert) {

    Map<Id,String> Mapattachment = new Map<Id,String>();

    set<Id> objParentIds = new set<Id>();
    for(Attachment objAtt : Trigger.new){
        objParentIds.add(objAtt.ParentId);
    }

    for(Attachment objAttachment : [SELECT id,Name,ParentId,Parent.Name FROM Attachment WHERE ParentId IN:objParentIds]){
        Mapattachment.put(objAttachment.ParentId,objAttachment.Parent.Name);
    }

    system.debug('Mapattachment=====>'+Mapattachment);

    for(Attachment objAttachment : Trigger.new){
        if(Mapattachment.containsKey(objAttachment.ParentId)){
            objAttachment.Name = Mapattachment.get(objAttachment.ParentId);
        }
    }
}

Best Answer

In before Insert Trigger, you do not have ID and that record doesn't exists in the database, thus your querry [SELECT id,Name,ParentId,Parent.Name FROM Attachment WHERE ParentId IN:objParentIds] will fail.

The logic here is to let the insert happen, and in after insert trigger do a DML to update the name of attachment with that of parent's Name. Thus your logic or trigger should be after insert.

trigger renameAttachment on Attachment (after insert) {
    List<Attachment> toBeUpdatedAttachment = new List<Attachment>();
    for(Attachment objAttachment : [SELECT id,Name,ParentId,Parent.Name FROM Attachment WHERE Id IN:Trigger.new]){
                   objAttachment.Name = objAttachment.Parent.Name;
                   toBeUpdatedAttachment.add(objAttachment);

    }

      update toBeUpdatedAttachment;
 }