Lots of time i have seen the question on salesforce developer forum regarding the trigger on Attachment. As this is not a straightway, still we can have trigger on Attachment.
We cannot create trigger on Attachment from the standard salesforce UI however we will have to use the eclipse.
While creating the trigger, we have to keep some important points. We should be very careful while writing the trigger on Attachment, as it will be used by any standard or custom Object and therefore the criteria to run trigger for “particular object only” must be handled carefully.
In this article i will create the trigger which will check for the parent object “Opportunity”. If the object is opportunity then it will check let say for the file name cannot contain word “shivasoft”.
trigger CheckAttachmentName on Attachment (before insert) { for (Attachment att:Trigger.new) { String parentObjId = att.ParentId; //006 is the starting sting in ID for all opportunities if(parentObjId.startsWith('006') && att.Name.toLowerCase().contains('shivasoft')) { att.addError('Cannot upload file with name containing - shivasoft'); } } //This method will return true if the id belongs to Opportunity private Boolean isOpportunityParent(String id) { for(Opportunity opp : [SELECT Id FROM Opportunity WHERE Id = :id]) { return true; } return false; } }
In the above code, we are checking that the Parent id starts with “006” or not. As starting three characters in ID identifies the type of the object.
Alternate solution – Not recommended :
There is one method created named “isOpportunityParent” which uses the SOQL approach but it is not recommended and may cause SOQL limit exception in bulk processing. We can supply the list of Id in method and return the Map which will contain ParentId as Key and Boolean as value identifying that the particular id belongs to opportunity or not?
Leave a Reply to arpitCancel reply