// Trigger to update the Attachment__c custom checkbox field in Custom Object(Custom_Obj__c) if it has any attachment.
trigger TiggerName on attachment (after insert)
{
List<Custom_Obj__c> co = [select id, Attachment__c from Custom_Obj__c where id =: Trigger.New[0].ParentId];
if(co.size()>0)
{
co[0].Attachment__c = true;
update co;
}
}
Usually we can’t create a trigger in the Salesforce user interface for certain objects like Attachment, ContentDocument and Note standard objects.So, alternatively we can use Developer Console or the Force.com IDE.
Please find below example:(if you wanna write trigger on Attachment object)
trigger AttachmentTriggerDemo on Attachment (before insert) { List accountList = new List(); Set accIds = new Set(); for(Attachment att : trigger.New){ //Check if added attachment is related to Account or not if(att.ParentId.getSobjectType() == Account.SobjectType){ accIds.add(att.ParentId); } } accountList = [select id, has_Attachment__c from Account where id in : accIds]; if(accountList!=null && accountList.size()>0){ for(Account acc : accountList){ acc.has_Attachment__c = true; } update accountList; } }
Please find below example (if you wanted to create an attachment on some other objects DML operation )
Please find below example:(if you wanna write trigger on Attachment object)
trigger AttachmentTriggerDemo on Attachment (before insert) {
List accountList = new List();
Set accIds = new Set();
for(Attachment att : trigger.New){
//Check if added attachment is related to Account or not
if(att.ParentId.getSobjectType() == Account.SobjectType){
accIds.add(att.ParentId);
}
}
accountList = [select id, has_Attachment__c from Account where id in : accIds];
if(accountList!=null && accountList.size()>0){
for(Account acc : accountList){
acc.has_Attachment__c = true;
}
update accountList;
}
}
Please find below example (if you wanted to create an attachment on some other objects DML operation )
String encodedContentsString = System.currentPageReference().getParameters().get('fileContents');
Id accountId = System.currentPageReference().getParameters().get('accountId');
Attachment attachment = new Attachment();
attachment.Body = Blob.valueOf(encodedContentsString);
attachment.Name = String.valueOf('test.txt');
attachment.ParentId = accountId;
insert attachment;
Keep learning :)