Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Create a field on Account Named (Client Contact lookup to Contact). Once an Account is inserted a Contact will create with the name of the Account and that Contact will be the Client Contact on the Account.
- trigger accClientContact on Account(after Insert, after update){
- if(trigger.isAfter){
- if(trigger.isInsert){
- accountHandler.afterInsert(trigger.new);
- }if(trigger.isUpdate){
- accountHandler.afterUpdate(trigger.new, trigger.oldMap);
- }
- }
- public with sharing class accountHandler {
- public static string afterInsert(list<Account> accNew){
- if(!accNew.isEmpty()){
- Map<Id,Contact> updatedContacts = new Map<Id,Contact>();
- for(Account aObj : accNew){
- Contact cc = new Contact();
- cc.AccountId = aObj.Id;
- cc.LastName = aObj.Name;
- updatedContacts.put(aObj.Id, Contact);
- }
- if(!updatedContacts.isEmpty()){
- INSERT udpatedContacts;
- List<Account> udpatedAccount = new List<Account>();
- for(Account aObj : accNew){
- if(udpateContacts.containsKey(aObj.Id){
- aObj.Client_Contact__c = updateContact.get(aObj).Id;
- updatedAccount.add(aobj);
- }
- }
- }
- if(!updatedAccount.isEmpty()){
- insert udpatedAccount;
- }
- }
- } public static List<Account> afterUpdate(list<Account> accNew, Map<Id,Account> oldAccMap){
- if(accNew.isEmpty() && oldAccMap.isEmpty()) return;
- list<Contact> updatedContacts = new list<contact>();
- Map<Id, Id> AccountToContactMapping = new Map<Id, Id>();
- for(Account aObj : accNew){
- if(aObj.Client_contact__c != oldAccMap.get(aObj.Id).contact_client__c){
- Contact cc = new Contact();
- cc.AccountId = aObj.Id;
- cc.LastName = aObj.Name;
- updatedContacts.add(cc);
- }// end if
- else{
- free();
- } //end else
- }// end for
- // Buld Insert New Contact
- if(!updatedContats.isEmpty()){
- Databae.SaveResults[] conInsert = Database.Insert(updatedContats, false); // partial insert is allowed
- for( integer i =0 ; i < conInsert.size(); i++){
- if(conInsert[i].isSuccess){
- Contact insertedContact = updatedContacts[i];
- AccountToContactMapping.put(insetedContact.AccountId, insertedContact.Id);
- }else{
- system.debug('Error while inserting contact'+conInsert[i].getError();
- }
- }
- list<Account> accountUpdates = new list<Account>();
- for( Account aObj : accNew){
- aObj.Client_contact__c = AccountToContact.get(aObj.Id);
- accountUpdates.add(aObj);
- }
- if(!accountUpdates.isEmpty()){
- Database.SaveResults[] accResults = Databse.Update(accountUpdates, false);
- for(integer i = 0; i<accResults.size(); i++){
- if(!accResults[i].isSuccess){
- system.debug('Error while updating account'+accResults[i].getError();
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement