You need to sign in to do that
Don't have an account?
Miles Sonnenfeld 2
Count Opportunity Attachment with specific text in name/title
Hey, I just finished writing some code to count the number of attachments with 'proposal' in the name. I am still pretty new to APEX so please let me know if you have a way to make this work better. Please see the Trigger, Class, & TestClass Below.
Trigger
Thank you!
Trigger
trigger AfterAttachment on Attachment (after insert, after delete, after undelete) { if(Trigger.new<>null){ for(attachment a:trigger.new){ String OppID = a.ParentId; Opp_ProposalAttachmentCount.CountAttachment(OppID); } }else if(Trigger.old!=null){ for(attachment a: trigger.old){ String OppID = a.ParentId; Opp_ProposalAttachmentCount.CountAttachment(OppID); } } }Class
public class Opp_ProposalAttachmentCount { public static void CountAttachment(String OppID){ Integer ACount = [SELECT count() FROM Attachment WHERE name like '%Proposal%' AND ParentID =:OppID]; system.debug('Count of attachements with Proposal in the name----->'+ACount); Opportunity O = [SELECT Proposal_Count__c FROM Opportunity WHERE Id =:OppID]; O.Proposal_Count__c = ACount; update O; } }@IsTest Class
@IsTest public class Test_AddDeleteAttachment { static testMethod void testAttachment(){ //Create Account Account a = new Account(); a.name = 'TestAccount'; a.Property_Owner_Type__c = 'other'; a.BillingStreet = '660 Newport Center Dr.'; a.BillingCity = 'Newport Beach'; a.BillingState = 'CA'; a.BillingPostalCode = '92660'; insert a; //Create Opportunity Opportunity o = new Opportunity(); o.accountid = a.id; o.name = 'TestOpportunity1'; o.stagename = '0 - Prospecting'; o.CloseDate = date.newInstance(2014, 9, 18); o.Stage_Detail__c = 'Researching Opportunity'; o.Current_Status_Next_Steps__c = 'This is a Test Class'; o.Agreement_Type__c = 'MLA'; o.vertical__c = 'Sports'; o.venue_type__c = 'MLB'; insert o; //Attach test file Attachment Attach = new Attachment(); attach.Name = 'Proposal - Test'; Blob bodyBlob=Blob.valueOf('proposal attachement test class'); attach.body=bodyBlob; attach.ParentId=o.id; insert attach; delete attach; } }
Thank you!
Raj Vakati
Use below code and it was bulkified