LWC Scenario - 5 (Mini Project)
25:42
Пікірлер
@user-fd3cv1op4s
@user-fd3cv1op4s 11 сағат бұрын
What if there are more than 1 contact associated with a type?
@sriniwasjoshi2295
@sriniwasjoshi2295 Күн бұрын
can we get all scenarios in a pdf , TIA
@prashantpandey3644
@prashantpandey3644 Күн бұрын
Hi Guys, I have gone through the comments and try to give my input. So, please find the updated code here which will work for If Account phone is null and on false update on Account means If we are changing other fields instead of Create_Contact__c. Note: I have not handled it for duplicate Contact creation. On again and again Checking the checkbox field, this will create new Contact associated with the same account. trigger CreateContactAssAccount on Account (after insert, after update) { List<Contact> conList = new List<Contact>(); for(Account acc : trigger.New){ if(acc.Create_Contact__c == true && (trigger.isInsert || (trigger.isUpdate && acc.Create_Contact__c != trigger.oldMap.get(acc.Id).Create_Contact__c))){ Contact con = new Contact(); con.FirstName = 'Trigger'; con.LastName = acc.Name; con.Phone = acc.Phone != null ? acc.Phone : ''; con.AccountId = acc.Id; conList.add(con); } } if(!conList.isEmpty()) insert conList; }
@shivam_diwan
@shivam_diwan 2 күн бұрын
sorry for increasing the like count from 69 to 70😂😂....good scenario though👍👍
@shivam_diwan
@shivam_diwan 2 күн бұрын
small request - also add for how many years of experience these triggers are for. Nice content btw
@sedentaryhooman
@sedentaryhooman 3 күн бұрын
I did it with the Aggregate query, here's the code : CODE : ============================================== public static void afterInsert(List<Contact> newList){ List<Opportunity> oppListToInsert = new List<Opportunity>(); List<Account> accListtoUpdate = new List<Account>(); set<id> accIdset = new set<id>(); Map<Id,Decimal> accIdWithTotalSum = new Map<Id,Decimal>(); for(Contact newCon : newList){ if(newCon.accountid!=null){ accIdset.add(newCon.accountid); } } List<AggregateResult> agrList = [Select accountId, SUM(Amount) totalsum From Opportunity where accountId in: accIdset group by accountId]; for(AggregateResult agr : agrList){ if(!accIdWithTotalSum.containsKey((Id)agr.get('accountId'))){ accIdWithTotalSum.put((Id)agr.get('accountId'),(Decimal)agr.get('totalsum')); } } for(Id accId : accIdset){ if(!accIdWithTotalSum.containskey(accId)){ Opportunity opp = new Opportunity(); opp.accountId = accId; opp.stagename = 'Prospecting'; opp.name = 'Test opp'; opp.CloseDate = system.today().addDays(7); oppListToInsert.add(opp); Account acc = new Account(); acc.Id = accId; acc.description = String.valueOf(opp.Amount); accListtoUpdate.add(acc); }else{ Account acc = new Account(); acc.Id = accId; acc.description = String.valueOf(accIdWithTotalSum.get(accId)); accListtoUpdate.add(acc); } } if(!oppListToInsert.isEmpty()){ insert oppListToInsert; } if(!accListtoUpdate.isEmpty()){ update accListtoUpdate; } }
@sruthikasthuri1023
@sruthikasthuri1023 5 күн бұрын
Will this trigger works on Bulk insert or Update , for example when we are loading data via data import or data loader? At the end of the for loop over extistingRecords , errorMessage will be set to a single value -->either phone,email or email and phone. so when we Iterate over trigger.new, for every record will it give same error? or it will change specific to record? Can you please clarify?
@erantona
@erantona 6 күн бұрын
I've tried trigger AccountTrigger on Account(after update){ if(Trigger.isAfter && Trigger.isUpdate){ Map<Id, DateTime> accMap = new Map<Id, DateTime>(); Map<Id, List<Contact>> accMapToCon = new Map<Id, List<Contact>>(); List<Messaging.SingleEmailMessage> emailList = new List<Messaging.SingleEmailMessage>(); for(Account acc : Trigger.new){ accMap.put(acc.Id, Trigger.oldMap.get(acc.Id).LastModifiedDate); } System.debug(accMap); for(Contact con :[Select Id, LastModifiedDate, Name,AccountId, Account.Owner.Email from Contact Where AccountId IN: accMap.keySet()]){ if(con.LastModifiedDate >= accMap.get(con.AccountId) && !accMapToCon.containsKey(con.AccountId)){ accMapToCon.put(con.AccountId, new List<Contact>{con}); }else if(con.LastModifiedDate >= accMap.get(con.AccountId) && accMapToCon.containsKey(con.AccountId)){ accMapToCon.get(con.AccountId).add(con); } } for(Id accId: accMapToCon.keySet()){ Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); email.setToAddresses(new List<String>{accMapToCon.get(accId)[0].Account.Owner.Email}); email.setPlainTextBody('the acc '+ accId+' has been modified and these contacts has been modified '+accMapToCon.get(accId)); emailList.add(email); } Messaging.sendEmail(emailList); } }
@erantona
@erantona 7 күн бұрын
I've tried: trigger CaseDeletion on Case (after delete) { if(Trigger.isDelete && Trigger.isAfter) { List<Case> deletedCase = Trigger.old; Set<Id> accountIds = new Set<Id>(); if(!deletedCase.isEmpty()){ for(Case caseRec : deletedCase){ accountIds.add(caseRec.AccountId); } } Map<Id, Account> accMap = new Map<Id, Account>([Select id, Owner.Email,OwnerId from Account where Id IN: accountIds]); List <Messaging.SingleEmailMessage> emailList = new List<Messaging.SingleEmailMessage>(); List<Task> taskList = new List<Task>(); for(Case caseRec: deletedCase){ Task taskRec = new Task(); taskRec.OwnerId = accMap.get(caseRec.AccountId).OwnerId; taskRec.Status = 'Not Started'; taskRec.Subject = 'Case Deleted '+caseRec.CaseNumber; taskRec.WhatId = caseRec.AccountId; taskList.add(taskRec); Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); email.setToAddresses(new List<String>{accMap.get(caseRec.AccountId).Owner.Email}); email.setSubject('An email from Salesforce'); email.setPlainTextBody('This email has been sent through Apex'); emailList.add(email); } insert taskList; Messaging.sendEmail(emailList); } }
@erantona
@erantona 7 күн бұрын
I've tried: trigger ContactHandler on Contact ( after insert, after update) { if(Trigger.IsAfter && (Trigger.isInsert || Trigger.isUpdate)){ Map<Id,Contact> newConMap = Trigger.newMap; Map<Id,Contact> oldConMap = Trigger.oldMap; Map<Id,String> accountIdsMapPhone = new Map<Id,String>(); for(Contact con : newConMap.values()){ if((oldConMap==null || oldConMap.get(con.Id).Phone != con.Phone)){ accountIdsMapPhone.put(con.AccountId,con.Phone); } } List<Account> acclistToUpdate = new List<Account>(); List<Contact> conlistToUpdate = new List<contact>(); for(Account acc: [Select Id, Phone from Account where Id IN: accountIdsMapPhone.keySet()]){ if(acc.phone != accountIdsMapPhone.get(acc.Id)){ acc.phone = accountIdsMapPhone.get(acc.Id); acclistToUpdate.add(acc); } } for(Contact con : [Select id, Phone,AccountId from Contact where AccountId In: accountIdsMapPhone.keySet()]){ if(con.Phone != accountIdsMapPhone.get(con.AccountId)){ con.Phone = accountIdsMapPhone.get(con.AccountId); conlistToUpdate.add(con); } } if(!acclistToUpdate.isEmpty()){ update acclistToUpdate; } if(!conlistToUpdate.isEmpty()){ update conlistToUpdate; } } }
@erantona
@erantona 7 күн бұрын
I've tried: trigger OpportunityHandler on Opportunity ( after insert, after update) { if(Trigger.IsAfter && (Trigger.isInsert || Trigger.isUpdate)){ Set<Id> accIds = new Set<Id>(); List<Account> accList = new List<Account>(); for(Opportunity opp: Trigger.new){ if(Trigger.oldMap == null || opp.Amount != Trigger.oldMap.get(opp.Id).Amount){ accIds.add(opp.AccountId); } } for(Account acc : [Select Id,Description,(Select id,Amount from Opportunities order by Amount desc) from Account where Id IN: accIds]){ if(acc.Opportunities.size()>1){ acc.Description = 'The 2nd Highest amount from Opportunities is '+acc.Opportunities[1].Amount; accList.add(acc); } } if(accList.size()>0){ update accList; } } }
@prashaanthi
@prashaanthi 9 күн бұрын
Helpful videos. But can you please add helper class for all the scenarios
@akashrai2814
@akashrai2814 16 күн бұрын
public static void updateContactName(List<Account> accList){ if(!accList.isEmpty()){ List<Contact> conList = new List<Contact>(); set<Id> accids = new Set<Id>(); for(Account acc: accList){ Contact con = new Contact(); con.AccountId = acc.id; con.LastName = acc.Name+' triggerAccount4'; conList.add(con); accids.add(acc.Id); } if(!conList.isEmpty()){ insert conList; } if(!accids.isEmpty()){ List<Account> newAccList = [Select Id, client_contact__c, (Select AccountId, name From Contacts) from Account where Id IN: accids]; List<Account> updatedList = new List<Account>(); for(Account acc: newAccList){ if(!acc.contacts.isEmpty()){ acc.client_contact__c = acc.Contacts[0].Name; updatedList.add(acc); } } if(!updatedList.isEmpty()){ update updatedList; } } } }
@rajdwahraknath5615
@rajdwahraknath5615 16 күн бұрын
is this triggers for freshers or 2+ years experience?
@SolitudeStar2226
@SolitudeStar2226 17 күн бұрын
Do we really need line 30 31? As new case is inserted
@SolitudeStar2226
@SolitudeStar2226 17 күн бұрын
Hi, might be i am new for this but please check line 30 31 else part. Don't think there should be else if(op. Amount change) Then only add accid. Otherwise anyfield update trigger will be executed Infact in every event.
@ranjitabehera9333
@ranjitabehera9333 18 күн бұрын
only for insert operation public static void createtaskOnPrimaryContact(List<Case> lstCs) { set<id> accIds=new set<id>(); List<Task> tkToInsert=new List<Task>(); if(!lstCs.isempty()) { for(Case newcs:lstCs) { if(newcs.accountid != null && newcs.Create_Task__c == true) { accIds.add(newcs.accountid); } } } if(!accIds.isempty()) { List<Contact> lstCon=[select id, name, accountid, primary_contact__C from contact where accountid in:accIds and primary_contact__C=true]; for(Contact con:lstCon) { Task tk=new task(); tk.Status='New'; tk.Priority='High'; tk.Subject='Account details need to be send'; tk.WhoId=con.id; tkToInsert.add(tk); } } if(!tkToInsert.isempty()) { insert tkToInsert; } }
@SolitudeStar2226
@SolitudeStar2226 19 күн бұрын
Apex trigger 7 - what if account does not have phone number? Should we consider to create contact? Or need to filter those account from trigger.new whose phone is blank
@prashantpandey3644
@prashantpandey3644 Күн бұрын
Please check the updated code in the comment section.
@srisadgurusairam1688
@srisadgurusairam1688 20 күн бұрын
Hi, can you pls share the code.
@gauravjoshi3879
@gauravjoshi3879 22 күн бұрын
sir , can we acheive this requirement with the help of set
@santanuroy571
@santanuroy571 22 күн бұрын
what about after insert or before delete? I can introduce a new trigger or delete
@natarajans1961
@natarajans1961 22 күн бұрын
Hi bro, I have seen plenty of videos regarding trigger, but you nailed it bro, really thanks for your teaching bro.
@ranjitabehera9333
@ranjitabehera9333 22 күн бұрын
Trigger:trigger contactTrigger on Contact (after insert) { if(trigger.isafter) { if(trigger.isinsert) { ContactTrgHelper.createOpp(Trigger.new); } } } Handler class: public class ContactTrgHelper { public static void createOpp(List<Contact> lstcon) { set<Id> accIds=new set<Id>(); if(!lstcon.isempty()) { for(Contact newcon:lstcon) { if(newcon.AccountId != null) { accIds.add(newcon.AccountId); } } } if(!accIds.isempty()) { map<id, decimal> mapOfCon=new map<id, decimal>(); List<Account> accToupdate=new List<Account>(); List<Opportunity> oppToInsert=new List<Opportunity>(); for(Aggregateresult agr:[select Accountid acid, sum(Amount) totalAmnt from Opportunity where Accountid in:accIds group by accountid]) { mapOfCon.put((Id)agr.get('acid'), (decimal)agr.get('totalAmnt')); } for(Contact ncon:lstcon) { if(mapOfCon.containskey(ncon.AccountId)) { Account accrec=new Account(); accrec.id=ncon.AccountId; accrec.Total_Opportunity_Amount__c=mapOfCon.get(ncon.AccountId); accToupdate.add(accrec); } else { Opportunity opprec=new Opportunity(); opprec.Name='Test Opp'; opprec.StageName='Prospecting'; opprec.CloseDate=system.today()+30; opprec.AccountId=ncon.AccountId; oppToInsert.add(opprec); } } if(!accToupdate.isempty()) { update accToupdate; } if(!oppToInsert.isempty()) { Insert oppToInsert; } } } }
@namanshetty2781
@namanshetty2781 23 күн бұрын
What's the difference between : database.getQuerylocator and datatable.querylocator. Because in Salesforce documentation the governor limit for records retrieved by database.getquerylocator is 10 thousand but you told it's 50 million. Wanted clarity for it
@user-pu2yc3vn2k
@user-pu2yc3vn2k 26 күн бұрын
Great Content! Try this approach! Set<Id> accIds = new Set<Id>(); for (Case c : oldCases.values()) { if (c.AccountId != null) { accIds.add(c.AccountId); } } if (accIds.size() > 0) { List<Account> accList = [SELECT Id, Owner.Email, Owner.Name FROM Account WHERE Id IN :accIds]; List<Task> taskList = new List<Task>(); List<Messaging.SingleEmailMessage> emailList = new List<Messaging.SingleEmailMessage>(); for (Account a : accList) { taskList.add( new Task( Subject = 'Followup Task while deleting Case on Account', Status = 'In Progress', // WhoId = con.Id, WhatId = a.Id ) ); Messaging.SingleEmailMessage ms = new Messaging.SingleEmailMessage(); ms.setToAddresses(new List<String>{a.Owner.Email}); ms.setPlainTextBody(a.Owner.Name); ms.setSubject('Case is deleted from these Account and Task is being created in respect of this!'); emailList.add(ms); } if (taskList.size() > 0) { try { insert taskList; } catch (Exception e) { System.debug('Exception occured while inserting the task --> '+e.getMessage()); } } if (emailList.size() > 0) { try { Messaging.sendEmail(emailList); } catch (Exception e) { System.debug('Error while sending mails'+e); } } }
@swaroopragswaroop5210
@swaroopragswaroop5210 26 күн бұрын
Hi 2 things I wanted to ask.. 1. Can we handle this in before delete context 2. And I saw u iterated over deleted caselist and created tasks and email. Here can we iterate over account list right? I am just trying to understand if there is any problem in my approach Please let me know
@naveenyalamala
@naveenyalamala 26 күн бұрын
Hi Sir could you please write a trigger on Account object whenever Account getting updated we need to send an email to the account owner also send contacts data only those created between last update and current update of account
@rajeshprogram2488
@rajeshprogram2488 28 күн бұрын
Hi just wanted to know do u need null check
@naveenyalamala
@naveenyalamala 29 күн бұрын
public static void preventDuplicateRecord(List<Account> accList){ // Collect unique account names (normalized to lowercase) Set<String> newAccNames = new Set<String>(); for (Account acc : accList) { if (acc.Name != null) { newAccNames.add(acc.Name.toLowerCase()); } } // Query existing accounts with names in the set List<Account> existingAccounts = [ SELECT Id, Name FROM Account WHERE Name IN :newAccNames ]; // Collect existing account names and their IDs Set<String> existingAccNames = new Set<String>(); Map<String, Id> existingNameToIdMap = new Map<String, Id>(); for (Account acc : existingAccounts) { existingAccNames.add(acc.Name.toLowerCase()); existingNameToIdMap.put(acc.Name.toLowerCase(), acc.Id); } // Flag duplicate records for (Account acc : accList) { if (acc.Name != null) { String normalizedName = acc.Name.toLowerCase(); // Check if the name exists and if it's not the same as the current record if (existingAccNames.contains(acc.Name.toLowerCase()) && !existingNameToIdMap.get(acc.Name.toLowerCase()).equals(acc.Id)) { acc.addError('Duplicate Account Name detected: ' + acc.Name); } } } }
@naveenyalamala
@naveenyalamala 29 күн бұрын
You are trying to insert 4 Account records, all with the same name, and that name does not currently exist in the database. Will it allow Insertion ?
@JShorts511
@JShorts511 27 күн бұрын
The following code will not allow /*Trigger Scenario: Write a trigger to prevent duplicate accounts based on name whenever an Account is inserted or updated. Scenario is to validate records before they are saved to database. so we use before trigger. context variables to access runtime contexts are Trigger.isInsert and Trigger.isUpdate*/ trigger AccountTrigger on Account(before insert,before update){ //set to collect Account Name from triggering records. List<String> accNames=new List<String>(); //accessing run time context if(Trigger.isBefore){ if(Trigger.isInsert){ //iterating over triggering records for(Account acc:Trigger.new){ accNames.add(acc.Name); } } if(Trigger.isUpdate){ //iterating over triggering records for(Account acc:Trigger.new){ //checking whether the account's Name is changed or not if(acc.Name != Trigger.oldMap.get(acc.Id).Name){ accNames.add(acc.Name); } } } } List<Account> accList=[SELECT Id,Name FROM Account WHERE Name IN:accNames]; set<String> accNameSetToCheckDups=new set<String>(); //Map to get number of accounts with same name Map<String,Integer> accNamesCountwithName=new Map<String,Integer>(); //iterating over accNames if(!accNames.isEmpty()){ for(String acctName:accNames){ if(!accNamesCountwithName.containsKey(acctName)){ accNamesCountwithName.put(acctName,0); }else { Integer count=accNamesCountwithName.get(acctName)+1; accNamesCountwithName.put(acctName,count); } } } //iterating over accList to collect existing names if(!accList.isEmpty()){ for(Account acc:accList){ accNameSetToCheckDups.add(acc.Name); } } //iterating over Triggering records to prevent duplicates if(!accNameSetToCheckDups.isEmpty() || accNamesCountwithName.keySet() !=null ){ //if triggering records has the same name more than one (If we are inserting /updating with same name at a time) for(Account acc:Trigger.new){ if(accNamesCountwithName.get(acc.Name)>1 || accNameSetToCheckDups.contains(acc.Name)){ acc.addError('Account already exists with the same name'); } } } }
@naveenyalamala
@naveenyalamala 27 күн бұрын
@@JShorts511 thank you
@srisadgurusairam1688
@srisadgurusairam1688 Ай бұрын
Nice Explanation
@Rohitkumar-vg5xi
@Rohitkumar-vg5xi Ай бұрын
but an opportunity might have multiple Tasks ?
@user-pu2yc3vn2k
@user-pu2yc3vn2k Ай бұрын
Thanks for making amazing content, keep it up bro :) Try this approach, Map<Id, String> phoneToIdMap = new Map<Id, String>(); for (Contact c : newContacts) { if (c.Phone != null && c.Phone != oldContacts.get(c.Id).Phone && c.AccountId != null) { phoneToIdMap.put(c.AccountId, c.Phone); } } if (phoneToIdMap.size() > 0) { List<Contact> conList = [SELECT Id, AccountId, Phone FROM Contact WHERE AccountId IN :phoneToIdMap.keySet()]; List<SObject> updateList = new List<SObject>(); Map<Id, Account> accMap = new Map<Id, Account>(); //we take map because if we directly insert acc in above list it gives duplicate Ids found error! for (Contact c : conList) { c.Phone = phoneToIdMap.get(c.AccountId); updateList.add(c); accMap.put( c.AccountId, new Account( Id = c.AccountId, Phone = phoneToIdMap.get(c.AccountId) ) ); } if (accMap.size() > 0) { updateList.addAll(accMap.values()); } if (updateList.size() > 0) { try { update updateList; } catch (Exception e) { System.debug('Exception occured in updating list --> '+e.getMessage()); } } }
@hemantsinghbisht4371
@hemantsinghbisht4371 Ай бұрын
Hi can anyone tell me why I'm not getting any changes in account object even tho I have done all the steps just like video .! 😮
@sfdcninjas
@sfdcninjas Ай бұрын
Hi can you please share your code
@niteshreddy7891
@niteshreddy7891 Ай бұрын
Hi SFDC ninja: I have a doubt, Instead of adding to Map. Directly in line 25 we can null check accountId and create instance of Account there itself and update account. Works right ? Great work by the way, Your classes are very useful 🙏
@AJAYKUMARGHANTA
@AJAYKUMARGHANTA Ай бұрын
I think we can also use account list and fetching related contacts and updating phone through map , its works for me actually in a simple way
@gauravjoshi3879
@gauravjoshi3879 22 күн бұрын
can you please share that code
@kumareshghosh5593
@kumareshghosh5593 Ай бұрын
I used a diff approach , class: public with sharing class phoneAccConsHandler { //whenever a contact phone gets updated, it's parent account phone should get updated, also all of the account's other contacts phone also should get updated with the same phone number. public static void afterUpdate(List<contact> newCons,Map<id,contact> oldConMap){ set<id> accIds=new Set<id>(); Map<id,string> accidPhoneMap=new Map<id,string>(); for(Contact con:newCons){ if(con.accountId!=null && con.Phone!=null && oldConMap==null){ accIds.add(con.accountId); accidPhoneMap.put(con.accountId,con.phone); }else if(con.accountId!=null && con.Phone!=null && oldConMap.get(con.id).phone!=con.phone || oldConMap.get(con.id).accountId!=con.accountId){ accIds.add(con.accountId); accIds.add(oldConMap.get(con.id).accountId); accidPhoneMap.put(con.accountId,con.phone); accidPhoneMap.put(oldConMap.get(con.id).accountId,con.phone); } } //update account Phone List<account> Accounts=new List<account>(); for(Account acc:[select id,phone from account where id in:accIds]){ acc.phone=accidPhoneMap.get(acc.id); Accounts.add(acc); } If(Accounts.size()!=0){ update Accounts; } //list all contact's of that account: List<contact> allConsToBeUpdated=new List<contact>(); List<contact> allCons=[Select id,accountId,Phone from Contact where accountId in:accIds]; for(Contact con:allCons){ con.phone=accidPhoneMap.get(con.accountId); allConsToBeUpdated.add(con); } if(allConsToBeUpdated.size()!=0){ update allConsToBeUpdated; } } }
@srisadgurusairam1688
@srisadgurusairam1688 Ай бұрын
pls upload the codes
@sfstart9655
@sfstart9655 Ай бұрын
@SFDC NINJA ,I saw all Ur Trigger Videos .Champion effect loved it. In this scenario lets say Account A has contacts c1,c2,c3 .where C1 phone updated to 999 and C2 phone to 888 .so Account phone and all c1,c2,c3 phone now 888. But if u update multiple contacts with apex and show the difference in video i think it adds more value and understandability for Biggers.
@ypravallika9080
@ypravallika9080 Ай бұрын
Thank you for sharing the solution, this is the trigger which I got in Accenture interview😊
@awesomekj5812
@awesomekj5812 Ай бұрын
Were you able to solve it ?
@Anitha-f5m
@Anitha-f5m Ай бұрын
Please can you write and show with apex handler
@saikrishna2972
@saikrishna2972 Ай бұрын
Why did this not go into recusrion 🤔
@sfstart9655
@sfstart9655 Ай бұрын
Here in line 31 a check to make sure not include contact which phone is same to update rel cons of acc.This way recursion can be avoided although After Trigger is Used..Correct me if i was wrong
@saikrishna2972
@saikrishna2972 9 күн бұрын
Ya i agree to your first point . Its good if we could skip that extra update on the record . But even if its after trigger it would still has to go recursively right ? Or i might be understanding it wrong
@adeshlandge767
@adeshlandge767 Ай бұрын
We need not to use a for loop in the Trigger.
@shivanandtotar4357
@shivanandtotar4357 Ай бұрын
good information
@shivamsaini7252
@shivamsaini7252 Ай бұрын
thank you bro for this awesome work and i have a scenario .if if are handling bulk delete an account does not have any opp but others have in this scenario else of Aggregate function will not execute .i have tried for this scenario plz have a look and guide me further trigger OppAmountSumOnAccount on Opportunity(after insert,after undelete,after delete,after update){ set<id> accountIds = new set<id>(); if(!trigger.new.isEmpty()){ if(trigger.isAfter && (trigger.isInsert || trigger.IsUndelete)){ for(opportunity opp : trigger.new){ if(opp.accountid != null){ accountIds.add(opp.accountId); } } } if(trigger.isAfter && trigger.isUpdate){ for(opportunity opp : trigger.new){ if(opp.accountid != null){ accountIds.add(opp.accountId); } if(trigger.oldMap.get(opp.id).accountId != null && (opp.accountId != trigger.oldMap.get(opp.id).accountId || opp.amount != trigger.oldMap.get(opp.id).amount)){ accountIds.add(trigger.oldMap.get(opp.id).accountId); } } } } if(!trigger.old.isEmpty()){ if(trigger.isAfter && trigger.isDelete){ for(opportunity opp : trigger.old){ if(opp.accountid != null){ accountIds.add(opp.accountId); } } } } map<id,account> accMap = new map<id,account>(); if(!accountIds.isEmpty()){ list<AggregateResult> agrList = [select accountId ids,sum(amount) sumAmnt from opportunity where accountId IN : accountIds group by AccountId]; if(!agrList.isEmpty()){ for(AggregateResult agr: agrList){ account acc = new account(); acc.id = (id)agr.get('ids'); acc.totalOppAmount__c = (Decimal)agr.get('sumAmnt'); accMap.put(acc.id,acc); if(accountids.contains(acc.id)){ accountids.remove(acc.id); } } } //here we are handling account which doesnot have any associated opportunity after the action for(id accid:accountids){ account acc1 = new Account(); acc1.id =accid; acc1.totalOppAmount__c = 0; accMap.put(acc1.id,acc1); } } if(!accMap.isEmpty()){ update accMap.values(); } }
@infantremi408
@infantremi408 Ай бұрын
Hi, I guess there is an issue in this snippet, In the second for loop you were iterating the trigger.new again but the accMap was created for only the records where the related account Id is not null and description should be updated. So, if a contact record is updated without any change on the description, we will face an issue in line 26 as KeyNotExists I guess. However we can overcome this by adding a containsKey() in line 26. Thanks!
@mayankmj35
@mayankmj35 Ай бұрын
want more iterview videos like this for different topics please
@sfstart9655
@sfstart9655 Ай бұрын
public static void updtAccDescriptionWithCon(List<Contact> newList , Map<Id,Contact> oldMap) { List<Account> AccLsts = new List<Account>(); if(!newList.isEmpty()){ for(Contact con : newList){ //if Update event if(oldMap !=null && con.AccountId !=null && (oldMap.get(con.Id).Description != con.Description)){ AccLsts.add(new Account(Id=con.AccountId ,Description =con.Description)); } } } if(!AccLsts.isEmpty()){ update AccLsts; } } //Please correct me if i was wrong.
@swatisharma-oz6df
@swatisharma-oz6df Ай бұрын
Can you take this one in your next video. write a trigger to get the product count of opportunity and update count field on account
@RanjitaBehera-nw3vl
@RanjitaBehera-nw3vl Ай бұрын
Only for Insert Operation----> public with sharing class OpportunityAmountTriggerHelper { public static void getOppAmount(List<Opportunity> lstNewOpp) { set<id> accIds=new set<id>(); if(!lstNewOpp.isEmpty()) { for(Opportunity opp:lstNewOpp) { if(opp.AccountId != null && opp.Amount != null) { accIds.add(opp.AccountId); } } } if(!accIds.isEmpty()) { List<Account> accToUpdate=new List<Account>(); map<id, Opportunity> mapOpp=new map<id, Opportunity>(); List<Opportunity> getAcc=[select Accountid, Amount from Opportunity where Accountid in: accIds ORDER BY Amount desc limit 1 OFFSET 1]; if(!getAcc.isEmpty()) { for(Opportunity opt:getAcc) { mapOpp.put(opt.Accountid, opt); } } for(Id ids:accIds) { if(mapOpp.containskey(ids)) { account accnt=new account(); accnt.id=ids; accnt.AnnualRevenue=mapOpp.get(ids).amount; accToUpdate.add(accnt); } } if(!accToUpdate.isEmpty()) { update accToUpdate; } } } }