Posts

Showing posts from June, 2022

Write a trigger to count number of contacts associated with an account with it's test class.

Whenever new contact is created for an Account update the field Number of contacts(a custom field of type Integer/Number)with the number of contacts. It should also update the count when contact is deleted /removed from Account. The respective count would be increased/Decreased accordingly. ....Trigger.... trigger CountContacts on Contact (after insert, after update, after delete) { list<contact> conList = new list<contact>(); list<account> accList = new list<account>(); set<ID> accIDs = new set<ID>(); if(trigger.isInsert || trigger.isUpdate) { for(contact con : trigger.new) { if(String.isNotBlank(con.accountId)) { accIds.add(con.accountId); } } } if(trigger.isDelete) { for(contact con : trigger.old) { accIDs.add(con.AccountId); } } if(accIDs.size()>0) { conList = [select name, id, acc...

Write a trigger and it's Test class on Account when Account is update check all opportunity inside the account.

Update all Opportunities Stage to close lost if an opportunity created date is greater than 30 days from today and stage not equal to close won. ....Trigger.... trigger UpdateOpportunities on Account (after update) { Set<Id> accountIds = new Set<Id>(); for(Account a:Trigger.new){ accountIds.add(a.Id); } DateTime day30=system.now()-30; List<Opportunity> oppListToUpdate=new List<Opportunity>(); List<Opportunity> oppList = [Select Id, AccountId, StageName, CreatedDate, CloseDate from Opportunity where AccountId in :accountIds]; if(oppList.size()>0) { for(Opportunity opp : oppList) { if(opp.CreatedDate < day30 && opp.StageName!='Closed Won') { opp.CloseDate = system.today(); opp.StageName = 'Closed Lost'; oppListToUpdate.add(opp); update opp; } } }...