• Sana123
  • NEWBIE
  • 60 Points
  • Member since 2021

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 1
    Likes Given
  • 20
    Questions
  • 18
    Replies
HEllo everyone ,
I am new to salesforce , i want to know that how can i insert parent object and its field value dynamically and then insert child objects records to it dynamically.

Note :-  i want to pass argument by which i have to pass objects and its field and records

For eg :- I have two args
Map<String, List<String>> mapOfsobject:
In this i pass parent object and list of child objects 

EX:- 'Account'=>{'Contact' ,'Opportunity'}

Map<String, Map<String, String>> mapOfsobjectField

then in this arguments i pass the field and values which i have to insert in objects 

Ex:-'Account'=>new map{'Name'=>'Test'},'Contact'=>new map{'LastName'=>'Test1'}


I have to use dynamic apex in this



I write some code but by my code i only able to insert account i am not able to insert child contact record in the account whicjh i made recently..


Here is my code:--

public class dynamicInsertFieldsRecords {  
    public static void getSobjectRecords(Map<String, List<String>> mapOfsobject ,Map<String, Map<String, String>> mapOfsobjectField ,Map<String, Integer> mapofrecord) {
        
        List<Sobject> listOfParent = new List<Sobject>();
        List<Sobject> listOfChild = new List<Sobject>();
        
        List<Sobject> sObjects = new List<Sobject>();
        List<Sobject> childsObjects = new List<Sobject>();
        
        List<Sobject> litOfsObjects = new List<Sobject>();
        
       // Map< List<Sobject>, List<Sobject>> MapParentChild = new  Map< List<Sobject>, List<Sobject>>();
        
        
        for(String sobj : mapOfsobject.keySet()){
            sObject sObj1 = Schema.getGlobalDescribe().get(sobj).newSObject() ;
            sObjects.add(sObj1);
            
            system.debug(sObjects);
        }
        
        
        for(List<String> objname1 : mapOfsobject.Values()){
            //system.debug(objname1);
            for(String str : objname1)    
            {
                sObject childsObj1 = Schema.getGlobalDescribe().get(str).newSObject() ;
                childsObjects.add(childsObj1);     
            }
        }
        
        
        String objType = String.valueOf(sObjects);
        String ChildobjType = String.valueOf(childsObjects);
        system.debug(objType);
        
        for(String str : mapOfsobjectField.Keyset()){
            system.debug(str);
            
            if(objType.contains(str)){
                //System.debug('str: ' + str);
                for(Integer i = 0; i < mapofrecord.get(str); i++){
                    //System.debug('i: ' + i);
                    sObject sObj = Schema.getGlobalDescribe().get(str).newSObject() ;
                    
                    //System.debug('sObj: ' + sObj);
                    for (String K : mapOfsobjectField.get(str).keyset()){
                        // System.debug('k  '+k);
                        sObj.put(k, (mapOfsobjectField.get(str).get(k) + i));
                        // System.debug('SObject: ' + sObj);
                    }
                    listOfParent.add(sObj);
                    System.debug('SObject: ' + sObj);
                }
                System.debug('listOfParent: ' + listOfParent);
            }  
        }
        insert listOfParent;
        // 
        Map<Id, Sobject> recordsMap = new Map<Id, Sobject>();
        recordsMap.putAll(listOfParent);
        Set<Id> recordIds = recordsMap.keySet();
        system.debug(recordIds);
        
        
        
        for(Id accId : recordIds ){
            String sObjName = accId.getSObjectType().getDescribe().getName();
             SObjectType objToken = Schema.getGlobalDescribe().get(sObjName); 
            DescribeSObjectResult objDef = objToken.getDescribe();
             Map<String, SObjectField> fields = objDef.fields.getMap();
            system.debug(sObjName);
            system.debug(objToken);
            system.debug(objDef);
            system.debug(fields);
            
            for(String str : mapOfsobjectField.Keyset()){
                system.debug(str);
                
                if(ChildobjType.contains(str)){
                    //System.debug('str: ' + str);
                    for(Integer i = 0; i < mapofrecord.get(str); i++){
                        //System.debug('i: ' + i);
                        sObject sObj = Schema.getGlobalDescribe().get(str).newSObject() ;
                        
                        //System.debug('sObj: ' + sObj);
                        for (String K : mapOfsobjectField.get(str).keyset()){
                            // System.debug('k  '+k);
                            sObj.put(k, (mapOfsobjectField.get(str).get(k) + i));
                            System.debug('SObject: ' + sObj);
                        }
                        
                        // listOfChild.add(sObjName);
                        listOfChild.add(sObj);
                        System.debug('SObject: ' + sObj);
                       // MapParentChild.put(listOfParent,listOfChild);  
                     //    System.debug('listOfParent: ' + MapParentChild);
                    }
                    System.debug('listOfParent: ' + listOfChild);
                
                    
                    
                }  
            } 
            
        }
       // insert listOfChild;
      // update MapParentChild.values();
    }
}

Can someone please help me to resolve this
 
Hlo community ,

public class getTheSobjectDetails {
    public static Map<Sobject, Map<String, List<Sobject>>>  getSobjectfield(Map<String,List<String>> mapOfsobject ,Map<String,List<String>> mapOfsobjectField) {
        
        List<Sobject> accList = new List<Sobject>();

        //Creating set of all account Ids
        Set<id> accIdsSet = new Set<id>() ;
        List<ID> listOfObj = new List<ID>();
            listOfObj.addAll(accIdsSet);
        
        Map<Sobject, Map<String, List<Sobject>>> mapOfParentChildObject = new Map<Sobject, Map<String, List<Sobject>>>();
        //system.debug
        for(String objname : mapOfsobjectField.keySet()){
            system.debug(objname);
            String dynamicParentfields = string.join(mapOfsobjectField.get(objname),',');
           system.debug('dynamicParentfields   '+ '  '+   dynamicParentfields);
            String dynamicsoql = ' SELECT ' + '' +  dynamicParentfields   + ' FROM ' +  objname ;
            for(List<sObject> sobjList1 :Database.query(' SELECT ' + '' +  dynamicParentfields   + ' FROM ' +  objname)){
               Map<Id,Sobject> accountIdObjMap = new Map<Id,Sobject>(sobjList1);
                system.debug('accountIdObjMap' + accountIdObjMap);
            system.debug(dynamicsoql);
            system.debug(sobjList1);  
                
                accList = accountIdObjMap.values();

                //getting set of account Id’s using map.keySet method
                accIdsSet = accountIdObjMap.keySet();
                
                 system.debug(accList);
            system.debug(accIdsSet); 
            }
            if(accList != listOfObj){

            }
        }
    
    }
}

This is my code ..But i cant understand how can i populate data to my nested return type ........

----------In my argument 1i am passing :Map<String, List<String>>: Key: Will be the Parent Object and 
##### Value: List of Child Objects 

---------In my argument 2 i am passing : Map<String, List<String>>: Key: Will be the Object (the object which i pass in 2 argument include all the object which i pass in argument 1)
### and  Value: Listof Fields of the object

now i am trying dynamic soql on object by which i get my output in this form for return type:-
1 Recrod => new Map<String, List<Sobject>>{'Contact' => List<Contact>; 'Opportunity' => List<Opportunity>}

In my execution window i am passing:-
getTheSobjectDetails.getSobjectfield(new Map<String, List<String>>{'Account'=>new List<String>{'Contact''}}, new Map<String, List<String>>{'Account'=>new List<String>{'Id', 'Name'},'Contact' => new List<String>{'Id', 'Name', 'AccountId', 'Account.Name'}});


Please Help me in this ...how can i solve this


 
I am getting this error----
System.DmlException: Delete failed. First exception on row 0 with id 0015g00000N5pRcAAJ; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, AccountTrigger1: execution of AfterDelete

caused by: System.NullPointerException: Attempt to de-reference a null object

Class.AccountTriggerHandler1.createContactsv1: line 124, column 1
Trigger.AccountTrigger1: line 21, column 1: []



this is my trigger ---
@isTest
public class AccountTriggerHandlerTest {
    @isTest
    public static void createContactsv2Test()
    {
        List<Account> listOfaccounts = new List<Account>();
        
        String str = 'FirstName=Anjana,LastName=Sharma,MobilePhone=32342342,Email=anjana@gmail.com';
        String str2 = 'FirstName=Anjana,LastName=Sharma,MobilePhone=32342342,Email=anjana@gmail.com'+'\r\n'
            +'FirstName=Bob23,LastName=Bob23,MobilePhone=322222,Email=bb212@gmail.com';
        
        Account acc = new Account();
        acc.Name = 'Test Account';
        acc.Contacts__c='FirstName=A,LastName=A,MobilePhone=1,Email=aa@unknown.com'+'\r\n'
            +'FirstName=B,LastName=B,MobilePhone=2,Email=bb@unknown.com';
        listOfaccounts.add(acc);
 
        Account acc1 = new Account();
        acc1.Name = 'Test12';
        acc1.Contacts__c = str;
        acc1.Move_To_Contacts__c = 'FirstName=Anjanakk,LastName=Sharmakk,MobilePhone=323242342,Email=anjana11@gmail.com';
        listOfaccounts.add(acc1);
        
        Account acc2 = new Account();
        acc2.Name = 'Testing';
        acc2.Contacts__c = str2;
        acc2.Move_To_Contacts__c = 'FirstName=Anjana,LastName=Sharma,MobilePhone=32342342,Email=anjana@gmail.com';
        listOfaccounts.add(acc2);
        
        Account lookUpAccount = new Account(Name = 'LookUp');
        insert lookUpAccount;
        
        listOfaccounts[1].Move_To_Account__c = lookUpAccount.Id;
        listOfaccounts[2].Move_To_Account__c = lookUpAccount.Id;
        
        insert listOfaccounts;
        
        system.debug('listOfaccounts'+ listOfaccounts);
        
        
        //insert con;

        List<Contact> insertedContacts = [SELECT Id, FirstName ,LastName , MobilePhone, Email FROM Contact WHERE AccountId = :listOfaccounts] ;
        
        Contact con = new Contact();
        con.LastName = 'Test Contact';
        con.AccountId = acc.Id;
        con.email='abc@gmail.com';
        insertedContacts.add(con);
        system.debug('insertedContacts'+ insertedContacts);
        
                
        //acc.Name='Test';
        //
        listOfaccounts[0].Contacts__c = '';
            //System.debug('accounts[0].Contacts__c: ' + accounts[0].Contacts__c);
        
       String st = 'FirstName=an,LastName=Sh,MobilePhone=32342,Email=anjana541@gmail.com';
       String str1 = 'FirstName=Anjana1,LastName=Sharma1,MobilePhone=323424342,Email=anjana1@gmail.com'+'\r\n'
            +'FirstName=Bob,LastName=Bob,MobilePhone=3222,Email=bb12@gmail.com';   
        
         listOfaccounts[1].Contacts__c=st;
         listOfaccounts[1].Move_To_Contacts__c ='FirstName=Bob1,LastName=Bob3,MobilePhone=32232,Email=bb312@gmail.com';
     
         listOfaccounts[2].Contacts__c=str1;
         listOfaccounts[2].Move_To_Contacts__c ='FirstName=Anjana1,LastName=Sharma1,MobilePhone=323424342,Email=anjana1@gmail.com'+'\r\n'
            +'FirstName=Bob,LastName=Bob,MobilePhone=3222,Email=bb12@gmail.com';
              
        update listOfaccounts;
        
        system.debug('listOfaccounts'+ listOfaccounts);
        
        system.assertEquals(listOfaccounts[2].Contacts__c,listOfaccounts[2].Move_To_Contacts__c);
        
        /*String st = 'FirstName=an,LastName=Sh,MobilePhone=32342,Email=anjana541@gmail.com';
           
         acc2.Contacts__c=st;
         acc2.Move_To_Contacts__c ='FirstName=Bob1,LastName=Bob3,MobilePhone=32232,Email=bb312@gmail.com';*/
        
         //  acc1.Move_To_Contacts__c ='FirstName=Anjana1,LastName=Sharma1,MobilePhone=323424342,Email=anjana1@gmail.com';
           
        //update listOfaccounts;
        //delete listOfaccounts;
        //system.assertEquals(listOfaccounts, null);
        //
        List<Contact> totalContacts = [SELECT AccountId, FirstName ,LastName , MobilePhone, Email FROM Contact WHERE AccountId = :listOfaccounts[1].Id];
        System.assertEquals(1 , totalContacts.size());
        
        List<Contact> listOfContactDeleted = [SELECT AccountId, FirstName ,LastName , MobilePhone,email FROM Contact WHERE AccountId = :listOfaccounts[0].Id];
        //System.debug('listOfContactDeleted: '+ listOfContactDeleted.size());
        System.assertEquals(0 , listOfContactDeleted.size());
        
      delete listOfaccounts[2];
        
    }
        }


this is my handler----

public static void createContactsv2 (List<Account>listAccounts, Map<Id, Account>mapOfoldAccount){
        
        Set<Id> accountIds = new Set<Id>();
        Set<String> contactEmailStringSet = new  Set<String>();
        Set<Account> accIDs = new Set<Account>();
 
        for (Account acc: listAccounts){
            accIDs.add(acc);
        }
    
        List<Contact> listOfdeletContact = [SELECT AccountId FROM Contact WHERE AccountId IN : accIDs];
        if(listOfdeletContact.Size()>0){
           delete listOfdeletContact;

        }
        
        for(Account account : listAccounts){
            system.debug(mapOfoldAccount);
            if(mapOfoldAccount!= null && (String.isNotBlank(account.Contacts__c) && mapOfoldAccount.get(account.Id).Contacts__c != account.Contacts__c))
            {
                
                List<String> listOfContacts = account.Contacts__c.split('\n');
                Set<String> setOfConatcts = new Set<String>(listOfContacts ) ;
                
                for(String lisofstr  : setOfConatcts){
                    System.debug('contactToBeUpsert');
                    
                    accountIds.add(account.Id);
                    contactEmailStringSet.add(lisofstr.substringAfter('Email=').substringBefore(',').replaceAll('\\s', ''));
                    
                }
            }
        }
        
        Map<String, Contact> mapOfContacts = new Map<String, Contact>();
        System.debug(contactEmailStringSet);
        if(contactEmailStringSet.size()>0)
        {     
            for(Contact contact :  [Select id, FirstName, LastName, Email, MobilePhone FROM Contact WHERE AccountId IN :accountIds AND Email IN :contactEmailStringSet]){  
                System.debug(contact);
                mapOfContacts.put(contact.Email, contact);
                
            }
            
        }
         
        List<Contact> contactToBeUpsert = new List<Contact>();
        
        for(Account account : listAccounts)
        {
            if(String.isNotBlank(account.Contacts__c))
            {
                List<String> listOfContactString = account.Contacts__c.split('\n');
                for(String lstString : listOfContactString)
                {  
                    String email = lstString.substringAfter('Email=').substringBefore(',').replaceAll('\\s', '');
                    System.debug(email);
                    if(mapOfContacts.containsKey(email))
                    {
                        contactToBeUpsert.add(new Contact(Id = mapOfContacts.get(email).Id,
                                                          FirstName = lstString.substringAfter('FirstName=').substringBefore(','), 
                                                          LastName = lstString.substringAfter('LastName=').substringBefore(','),
                                                          MobilePhone =lstString.substringAfter('MobilePhone=').substringBefore(',')));
                        System.debug('contactToBeUpsert');  
                    }
                    else
                    {
                        contactToBeUpsert.add(new Contact(FirstName = lstString.substringAfter('FirstName=').substringBefore(','), 
                                                          LastName = lstString.substringAfter('LastName=').substringBefore(','),
                                                          Email = lstString.substringAfter('Email=').substringBefore(','),
                                                          MobilePhone =lstString.substringAfter('MobilePhone=').substringBefore(','),
                                                          AccountId = account.Id));
                        
                        System.debug('contactToBeUpsert');    
                    }  
                }
            }      
        }
     
        System.debug(contactToBeUpsert);
    
            if(contactToBeUpsert.Size()>0){
            upsert contactToBeUpsert;
        }
    /* for(Account account : listAccounts){
        if(account.Contacts__c != mapOfoldAccount.get(account.ID).Contacts__c && account.Contacts__c.split('\n').size() < 
           mapOfoldAccount.get(account.ID).Contacts__c.split('\n').size()){
               for(Contact con : [Select id, FirstName, LastName, Email, MobilePhone FROM Contact WHERE AccountId IN :accountIds]){
                   if(!account.Contacts__c.contains(con.FirstName)){
                       listOfdeleteContact.add(con);
                   }
                   
               }
           }
    }*/
        
    }
    
    
public static void createContactsv1 (List<Account> listOfAccounts, Map<Id, Account> mapoldAccount){
    
    Set<Id> setOfIds = new Set<Id>();
    Map<Id, List<String>> mapOfAccountIdAndString = new  Map<Id, List<String>>();
   
    List<Account> accountToUpdate = new List<Account>();
    for(Account account : listOfAccounts){
        
        if(String.isNotBlank(account.Move_To_Account__c) && String.isNotBlank(account.Move_To_Contacts__c) && (mapoldAccount == null 
                                               || mapoldAccount.get(account.Id).Move_To_Account__c != account.Move_To_Account__c
                                               || mapoldAccount.get(account.Id).Move_To_Contacts__c != account.Move_To_Contacts__c))
            
        {
             
             List<String> listOfContacts = account.Contacts__c.split('\n');
             List<String> listOfMoveToContacts = account.Move_To_Contacts__c.split('\n');
            
            
            if(listOfContacts.size()>0)
            {
                String moveToContact = '';
                for(String contact : listOfMoveToContacts)
                {
                    if(listOfMoveToContacts.size()>0 && listOfContacts.contains(contact))  {
                        
                        if(!mapOfAccountIdAndString.containsKey(account.Move_To_Account__c)) //false
                            mapOfAccountIdAndString.put(account.Move_To_Account__c, new List<String>());
                        
                        mapOfAccountIdAndString.get(account.Move_To_Account__c).add(contact); //st/ st2 //st3
                        setOfIds.add(account.Id);
                        moveToContact = '\n';//if move to contact value is contains in contact__c value 
                    }
                    else{
                         moveToContact = moveToContact+contact+'\n'; //if not contains then add contact to movettocontact
                    }
                   
                }
                moveToContact = String.isNotBlank(moveToContact)?moveToContact:moveToContact.replaceAll('\\s', '');
                accountToUpdate.add(new Account(Id = account.Id, Move_To_Contacts__c = moveToContact));
            }
            
        }
    }
    
    if(mapOfAccountIdAndString.size() > 0)
    {    
        for(Id accountId : mapOfAccountIdAndString.keySet()) 
        {
            String contactValue = '';
            for(String contact : mapOfAccountIdAndString.get(accountId))
            {
                contactValue = contactValue+contact+'\n';
            }
            accountToUpdate.add(new Account(Id = accountId, Contacts__c = contactValue));
        }
        
        if(accountToUpdate.size()>0) update accountToUpdate; 
    }
    
    if(setOfIds.size()>0)
    {
        
        List<Contact> contacts = [SELECT Id, Email, FirstName, LastName, Account.Move_To_Account__c, AccountId FROM Contact WHERE AccountId  IN :setOfIds];
        
        list<Contact> contactsTomoved = new List<Contact>();
        if(contacts.size()>0)
        {
            for(Contact contact : contacts)
            {
                for(String contString : mapOfAccountIdAndString.get(contact.Account.Move_To_Account__c))
                { 
                    
                    if(contact.FirstName == contString.substringAfter('FirstName=').substringBefore(',')
                       && contact.LastName == contString.substringAfter('LastName=').substringBefore(',')
                       && contact.Email == contString.substringAfter('Email=').substringBefore(','))
                    {
                        contact.AccountId = contact.Account.Move_To_Account__c;
                        contactsTomoved.add(contact);
                    }
                }
                
            }
        }
        
        if(contactsTomoved.size() > 0) update contactsTomoved;  
    }
 }
}


this is my trigger --

trigger AccountTrigger1 on Account (after insert , after update , after delete ) {
if(trigger.isAfter &&(Trigger.isInsert || Trigger.isUpdate)){
        AccountTriggerHandler1.createContactsv2(trigger.new, trigger.oldMap);
        AccountTriggerHandler1.createContactsv1(trigger.new, trigger.oldMap);
    }
    if(trigger.isAfter &&Trigger.isDelete){
        AccountTriggerHandler1.createContactsv1(null , trigger.oldMap);
        AccountTriggerHandler1.createContactsv2(null, trigger.oldMap);
        
    }
}
///Trigger Handler
public static void createContactsv1 (List<Account> listOfAccounts, Map<Id, Account> mapoldAccount){
    
    Set<Id> setOfIds = new Set<Id>();
    Map<Id, List<String>> mapOfAccountIdAndString = new  Map<Id, List<String>>();
   
    List<Account> accountToUpdate = new List<Account>();
    for(Account account : listOfAccounts){
        
        if(String.isNotBlank(account.Move_To_Account__c) && String.isNotBlank(account.Move_To_Contacts__c) && (mapoldAccount == null 
                                               || mapoldAccount.get(account.Id).Move_To_Account__c != account.Move_To_Account__c
                                               || mapoldAccount.get(account.Id).Move_To_Contacts__c != account.Move_To_Contacts__c))
            
        {
             
             List<String> listOfContacts = account.Contacts__c.split('\n');
             List<String> listOfMoveToContacts = account.Move_To_Contacts__c.split('\n');
            
            
            if(listOfContacts.size()>0)
            {
                String moveToContact = '';
                for(String contact : listOfMoveToContacts)
                {
                    if(listOfMoveToContacts.size()>0 && listOfContacts.contains(contact))  {
                        
                        if(!mapOfAccountIdAndString.containsKey(account.Move_To_Account__c)) //false
                            mapOfAccountIdAndString.put(account.Move_To_Account__c, new List<String>());
                        
                        mapOfAccountIdAndString.get(account.Move_To_Account__c).add(contact); //st/ st2 //st3
                        setOfIds.add(account.Id);
                        moveToContact = '\n';//if move to contact value is contains in contact__c value 
                    }
                    else{
                         moveToContact = moveToContact+contact+'\n'; //if not contains then add contact to movettocontact
                    }
                   
                }
                moveToContact = String.isNotBlank(moveToContact)?moveToContact:moveToContact.replaceAll('\\s', '');
                accountToUpdate.add(new Account(Id = account.Id, Move_To_Contacts__c = moveToContact));
            }
            
        }
    }
    
    if(mapOfAccountIdAndString.size() > 0)
    {    
        for(Id accountId : mapOfAccountIdAndString.keySet()) 
        {
            String contactValue = '';
            for(String contact : mapOfAccountIdAndString.get(accountId))
            {
                contactValue = contactValue+contact+'\n';
            }
            accountToUpdate.add(new Account(Id = accountId, Contacts__c = contactValue));
        }
        
        if(accountToUpdate.size()>0) update accountToUpdate; 
    }
    
    if(setOfIds.size()>0)
    {
        
        List<Contact> contacts = [SELECT Id, Email, FirstName, LastName, Account.Move_To_Account__c, AccountId FROM Contact WHERE AccountId  IN :setOfIds];
        
        list<Contact> contactsTomoved = new List<Contact>();
        if(contacts.size()>0)
        {
            for(Contact contact : contacts)
            {
                for(String contString : mapOfAccountIdAndString.get(contact.Account.Move_To_Account__c))
                { 
                    
                    if(contact.FirstName == contString.substringAfter('FirstName=').substringBefore(',')
                       && contact.LastName == contString.substringAfter('LastName=').substringBefore(',')
                       && contact.Email == contString.substringAfter('Email=').substringBefore(','))
                    {
                        contact.AccountId = contact.Account.Move_To_Account__c;
                        contactsTomoved.add(contact);
                    }
                }
                
            }
        }
        
        if(contactsTomoved.size() > 0) update contactsTomoved;  
    }
 }


///test class--

@isTest
public class AccountTriggerHandlerTest {
    @isTest
    public static void createContactsv2Test()
    {

List<Account>accounts = new List<Account>();
  String str = 'FirstName=A,LastName=A,MobilePhone=1,Email=aa@unknown.com' +'\r\n' + 'FirstName=B,LastName=B,MobilePhone=2,Email=bb@unknown.com';
        Account lookUpAccount = new Account(Name = 'LookUp');
            insert lookUpAccount;
            accounts[0].Move_To_Account__c = lookUpAccount.Id;
            accounts[0].Move_To_Contacts__c = 'FirstName=A,LastName=A,MobilePhone=1,Email=aa@unknown.com';
            update accounts;
            List<Contact> totalContactsAfterMovingContact = [SELECT AccountId, FirstName ,LastName , MobilePhone,Email FROM Contact WHERE AccountId = :accounts[0].Id];
            //System.debug('totalContactsAfterMovingContact: '+ totalContactsAfterMovingContact.size());
            System.assertEquals(2 , totalContactsAfterMovingContact.size());
            
            accounts[0].Contacts__c = '';
            update accounts;
            
            accounts[0].Contacts__c = str;
            update accounts;
            
            List<Contact> totalContactsOnInsertingAndMovingContact = [SELECT AccountId, FirstName ,LastName , MobilePhone, Email FROM Contact WHERE AccountId = :accounts[0].Id];
            //System.debug('totalContactsOnInsertingAndMovingContact: '+ totalContactsOnInsertingAndMovingContact.size());
            System.assertEquals(1 , totalContactsOnInsertingAndMovingContact.size());
            
            accounts[0].Contacts__c = str + '\r\n' + 'FirstName=D,LastName=D,MobilePhone=4,Email=dd@unknown.com' + '\r\n' + 'FirstName=F,LastName=F,MobilePhone=6,Email=ff@unknown.com';
            update accounts;
List<Contact> totalContactsOnInsertingAndMovingContact_1 = [SELECT AccountId, FirstName ,LastName , MobilePhone, Email FROM Contact WHERE AccountId = :accounts[0].Id];
            System.assertEquals(3 , totalContactsOnInsertingAndMovingContact_1.size());
            
            accounts[0].Contacts__c = str;
            update accounts;
            List<Contact> totalContactsOnDeleting = [SELECT AccountId, FirstName ,LastName , MobilePhone, Email FROM Contact WHERE AccountId = :accounts[0].Id];
            //System.debug('totalContactsOnDeleting: '+ totalContactsOnDeleting.size());
            System.assertEquals(1 , totalContactsOnDeleting.size());
            
            accounts[0].Contacts__c = str + '\r\n' + 'FirstName=D,LastName=D,MobilePhone=4,Email=dd@unknown.com' + '\r\n' + 'FirstName=F,LastName=F,MobilePhone=6,Email=ff@unknown.com';
            update accounts;
            List<Contact> totalContactsOnInsertingAndMovingContact_2 = [SELECT AccountId, FirstName ,LastName , MobilePhone, Email FROM Contact WHERE AccountId = :accounts[0].Id];
            System.assertEquals(3 , totalContactsOnInsertingAndMovingContact_2.size());
            
            accounts[0].Move_To_Contacts__c = 'FirstName=A,LastName=A,MobilePhone=1,Email=aa@unknown.com' + '\r\n' + 'FirstName=D,LastName=D,MobilePhone=4,Email=dd@unknown.com';
            update accounts;
            List<Contact> totalContactsAfterMovingContact_1 = [SELECT AccountId, FirstName ,LastName , MobilePhone, Email FROM Contact WHERE AccountId = :accounts[0].Id];
            System.assertEquals(2 , totalContactsAfterMovingContact_1.size());
            
            String str_2 = str + '\r\n' + 'FirstName=D,LastName=D,MobilePhone=4,Email=dd@unknown.com' + '\r\n' + 'FirstName=F,LastName=F,MobilePhone=6,Email=ff@unknown.com';
            accounts[0].Contacts__c = str_2 + '\r\n' + 'FirstName=G,LastName=G,MobilePhone=7,Email=gg@unknown.com';
            accounts[0].Move_To_Contacts__c = 'FirstName=A,LastName=A,MobilePhone=1,Email=aa@unknown.com' + '\r\n' + 'FirstName=D,LastName=D,MobilePhone=4,Email=dd@unknown.com' + '\r\n' + 'FirstName=G,LastName=G,MobilePhone=7,Email=gg@unknown.com';
            update accounts;
List<Contact> totalContactsOnInsertingAndMovingContact_3 = [SELECT AccountId, FirstName ,LastName , MobilePhone, Email FROM Contact WHERE AccountId = :accounts[0].Id];
            System.assertEquals(2 , totalContactsOnInsertingAndMovingContact_3.size());
            
            accounts[0].Contacts__c = '';
            update accounts;
            accounts[0].Contacts__c = str_2 + '\r\n' + 'FirstName=G,LastName=G,MobilePhone=7,Email=gg@unknown.com' + '\r\n' + 'FirstName=H,LastName=H,MobilePhone=8,Email=hh@unknown.com';
            accounts[0].Move_To_Contacts__c = 'FirstName=A,LastName=A,MobilePhone=1,Email=aa@unknown.com' + '\r\n' + 'FirstName=D,LastName=D,MobilePhone=4,Email=dd@unknown.com' + '\r\n' + 'FirstName=G,LastName=G,MobilePhone=7,Email=gg@unknown.com' + '\r\n' + 'FirstName=H,LastName=H,MobilePhone=8,Email=hh@unknown.com';
            update accounts;
            List<Contact> totalContactsOnInsertingAndMovingContact_4 = [SELECT AccountId, FirstName ,LastName , MobilePhone, Email FROM Contact WHERE AccountId = :accounts[0].Id];
            System.assertEquals(2 , totalContactsOnInsertingAndMovingContact_4.size());
            
            accounts[1].Move_To_Contacts__c = 'FirstName=A,LastName=A,MobilePhone=1,Email=aa@unknown.com';
            update accounts;
            accounts[1].Move_To_Contacts__c = str;
            update accounts;
            List<Contact> totalContactsOnInsertingAndMovingContact_5 = [SELECT AccountId, FirstName ,LastName , MobilePhone, Email FROM Contact WHERE AccountId = :accounts[1].Id];
            System.assertEquals(1 , totalContactsOnInsertingAndMovingContact_5.size());
            
            
            Account lookUpAccount_1 = new Account(Name = 'TestLookUp_1');
            insert lookUpAccount_1;
            accounts[2].Move_To_Account__c = lookUpAccount_1.Id;
            accounts[2].Move_To_Contacts__c = 'FirstName=A,LastName=A,MobilePhone=1,Email=aa@unknown.com';
            update accounts;
            
            
        }


///Please someone tell me where i am getting wrong
public static void createContactsv2 (List<Account>listAccounts, Map<Id, Account>mapOfoldAccount){
        
        Set<Id> accountIds = new Set<Id>();
        Set<String> contactEmailStringSet = new  Set<String>();
        Set<Account> accIDs = new Set<Account>();
 
        for (Account acc: listAccounts){
            accIDs.add(acc);
        }
    
        List<Contact> listOfdeletContact = [SELECT AccountId FROM Contact WHERE AccountId IN : accIDs];
        if(listOfdeletContact.Size()>0){
           delete listOfdeletContact;

        }
        
        for(Account account : listAccounts){
            system.debug(mapOfoldAccount);
            if(mapOfoldAccount!= null && (String.isNotBlank(account.Contacts__c) && mapOfoldAccount.get(account.Id).Contacts__c != account.Contacts__c))
            {
                
                List<String> listOfContacts = account.Contacts__c.split('\n');
                Set<String> setOfConatcts = new Set<String>(listOfContacts ) ;
                
                for(String lisofstr  : setOfConatcts){
                    System.debug('contactToBeUpsert');
                    
                    accountIds.add(account.Id);
                    contactEmailStringSet.add(lisofstr.substringAfter('Email=').substringBefore(',').replaceAll('\\s', ''));
                    
                }
            }
        }
        
        Map<String, Contact> mapOfContacts = new Map<String, Contact>();
        System.debug(contactEmailStringSet);
        if(contactEmailStringSet.size()>0)
        {     
            for(Contact contact :  [Select id, FirstName, LastName, Email, MobilePhone FROM Contact WHERE AccountId IN :accountIds AND Email IN :contactEmailStringSet]){  
                System.debug(contact);
                mapOfContacts.put(contact.Email, contact);
                
            }
            
        }
         
        List<Contact> contactToBeUpsert = new List<Contact>();
        
        for(Account account : listAccounts)
        {
            if(String.isNotBlank(account.Contacts__c))
            {
                List<String> listOfContactString = account.Contacts__c.split('\n');
                for(String lstString : listOfContactString)
                {  
                    String email = lstString.substringAfter('Email=').substringBefore(',').replaceAll('\\s', '');
                    System.debug(email);
                    if(mapOfContacts.containsKey(email))
                    {
                        contactToBeUpsert.add(new Contact(Id = mapOfContacts.get(email).Id,
                                                          FirstName = lstString.substringAfter('FirstName=').substringBefore(','), 
                                                          LastName = lstString.substringAfter('LastName=').substringBefore(','),
                                                          MobilePhone =lstString.substringAfter('MobilePhone=').substringBefore(',')));
                        System.debug('contactToBeUpsert');  
                    }
                    else
                    {
                        contactToBeUpsert.add(new Contact(FirstName = lstString.substringAfter('FirstName=').substringBefore(','), 
                                                          LastName = lstString.substringAfter('LastName=').substringBefore(','),
                                                          Email = lstString.substringAfter('Email=').substringBefore(','),
                                                          MobilePhone =lstString.substringAfter('MobilePhone=').substringBefore(','),
                                                          AccountId = account.Id));
                        
                        System.debug('contactToBeUpsert');    
                    }  
                }
            }      
        }
     
        System.debug(contactToBeUpsert);
    
            if(contactToBeUpsert.Size()>0){
            upsert contactToBeUpsert;
        }
        
    }
    
    
public static void createContactsv1 (List<Account> listOfAccounts, Map<Id, Account> mapoldAccount){
    
    Set<Id> setOfIds = new Set<Id>();
    Map<Id, List<String>> mapOfAccountIdAndString = new  Map<Id, List<String>>();
   
    List<Account> accountToUpdate = new List<Account>();
    for(Account account : listOfAccounts){
        
        if(String.isNotBlank(account.Move_To_Account__c) && String.isNotBlank(account.Move_To_Contacts__c) && (mapoldAccount == null 
                                               || mapoldAccount.get(account.Id).Move_To_Account__c != account.Move_To_Account__c
                                               || mapoldAccount.get(account.Id).Move_To_Contacts__c != account.Move_To_Contacts__c))
            
        {
             
             List<String> listOfContacts = account.Contacts__c.split('\n');
             List<String> listOfMoveToContacts = account.Move_To_Contacts__c.split('\n');
            
            
            if(listOfContacts.size()>0)
            {
                String moveToContact = '';
                for(String contact : listOfMoveToContacts)
                {
                    if(listOfMoveToContacts.size()>0 && listOfContacts.contains(contact))  {
                        
                        if(!mapOfAccountIdAndString.containsKey(account.Move_To_Account__c)) //false
                            mapOfAccountIdAndString.put(account.Move_To_Account__c, new List<String>());
                        
                        mapOfAccountIdAndString.get(account.Move_To_Account__c).add(contact); //st/ st2 //st3
                        setOfIds.add(account.Id);
                        moveToContact = '\n';//if move to contact value is contains in contact__c value 
                    }
                    else{
                         moveToContact = moveToContact+contact+'\n'; //if not contains then add contact to movettocontact
                    }
                   
                }
                moveToContact = String.isNotBlank(moveToContact)?moveToContact:moveToContact.replaceAll('\\s', '');
                accountToUpdate.add(new Account(Id = account.Id, Move_To_Contacts__c = moveToContact));
            }
            
        }
    }
    
    if(mapOfAccountIdAndString.size() > 0)
    {    
        for(Id accountId : mapOfAccountIdAndString.keySet()) 
        {
            String contactValue = '';
            for(String contact : mapOfAccountIdAndString.get(accountId))
            {
                contactValue = contactValue+contact+'\n';
            }
            accountToUpdate.add(new Account(Id = accountId, Contacts__c = contactValue));
        }
        
        if(accountToUpdate.size()>0) update accountToUpdate; 
    }
    
    if(setOfIds.size()>0)
    {
        
        List<Contact> contacts = [SELECT Id, Email, FirstName, LastName, Account.Move_To_Account__c, AccountId FROM Contact WHERE AccountId  IN :setOfIds];
        
        list<Contact> contactsTomoved = new List<Contact>();
        if(contacts.size()>0)
        {
            for(Contact contact : contacts)
            {
                for(String contString : mapOfAccountIdAndString.get(contact.Account.Move_To_Account__c))
                { 
                    
                    if(contact.FirstName == contString.substringAfter('FirstName=').substringBefore(',')
                       && contact.LastName == contString.substringAfter('LastName=').substringBefore(',')
                       && contact.Email == contString.substringAfter('Email=').substringBefore(','))
                    {
                        contact.AccountId = contact.Account.Move_To_Account__c;
                        contactsTomoved.add(contact);
                    }
                }
                
            }
        }
        
        if(contactsTomoved.size() > 0) update contactsTomoved;  
    }
 }
}
public static void countContactDetails(List<Contact> listContacts, Map<Id,Contact> mapOldContacts){
     Set<Id> setAccountId = new Set<Id>();
     Map<Id,Account> mapOfAccount = new Map<Id,Account>();
        if( mapOldContacts == null || mapOldContacts.isEmpty() ) {
            for( Contact objCont : listContacts ) {
                if( objCont.AccountId != null ) {
                    setAccountId.add( objCont.AccountId );
                }
            }
        }
        else if( mapOldContacts != null && !mapOldContacts.isEmpty()) {
            for( Contact objCont : listContacts ) { 
                if( objCont.AccountId != null 
                && mapOldContacts.get( objCont.Id ).AccountId != objCont.AccountId ) {
                    setAccountId.add( objCont.AccountId );
                    if( mapOldContacts.get( objCont.Id ).AccountId != null ) {
                        setAccountId.add( mapOldContacts.get( objCont.Id ).AccountId );
                    }
                }
                else if( objCont.AccountId == null && mapOldContacts.get( objCont.Id ).AccountId != objCont.AccountId ) {
                    setAccountId.add( mapOldContacts.get( objCont.Id ).AccountId );
                }
            }
        }
        if( !setAccountId.isEmpty() ) {
            List<Account> listAccount = new List<Account>();
            for (AggregateResult ar : [SELECT AccountId AcctId, Count(id) ContactCount 
                                       FROM Contact
                                       WHERE AccountId in: setAccountId 
                                       GROUP BY AccountId]){
                                           Account a = new Account();
                                           a.Id = (Id) ar.get('AcctId');
                                           a.Total_Contacts__c = (Integer) ar.get('ContactCount');
                                           listAccount.add(a);

            
        }
   if( !listAccount.isEmpty() ) {
                update listAccount;
            }  
 }
    
             if( !setAccountId.isEmpty() ) {
                  List<Account> listAccount1 = new List<Account>();
            List<AggregateResult> results = [Select AccountId ,Count(Id) ContactCount, Contact_Status__c str from Contact  WHERE AccountId in: setAccountId GROUP BY AccountId, Contact_Status__c];
                  Integer activecount = 0;
                  Integer inactivecount = 0;
                 for (AggregateResult ar : results)  {
                    if(ar.get('str')=='Active'){
                           
                        activecount += (Integer)ar.get('ContactCount');
                     }
                      if(ar.get('str')=='Inactive'){
                          inactivecount = (Integer)ar.get('ContactCount');  
                     }
                     //a.Total_Contacts__c = (Integer) ar.get('ContactCount');
                    // mapOfAccount.put((ID)ar.get('AccountId') , new Account(Id = (Id)ar.get('AccountId'),Total_Active_Contacts__c = activecount ,Total_Inactive_Contacts__c = inactivecount));
                      Account a1 = new Account();
                       a1.Id = (Id) ar.get('AccountId');
                       a1.Total_Active_Contacts__c = activecount;
                     a1.Total_Inactive_Contacts__c = inactivecount;
                  listAccount1.add(a1);
                 }

system.debug('Mapofaccount=='+ listAccount1);
    
 }
    } 
public static void createContactsv1 (List<Account> listOfAccounts, Map<Id, Account> mapoldAccount){
    
    
    Map<Id, List<String>> mapOfAccountIdAndString = new  Map<Id, List<String>>();
    List<Account> accountToUpdate = new List<Account>();
    for(Account account : listOfAccounts){
        
        if(String.isNotBlank(account.Move_To_Account__c) && String.isNotBlank(account.Move_To_Contacts__c) && (mapoldAccount == null 
                                               || mapoldAccount.get(account.Id).Move_To_Account__c != account.Move_To_Account__c
                                               || mapoldAccount.get(account.Id).Move_To_Contacts__c != account.Move_To_Contacts__c))
            
        {
             
             List<String> listOfContacts = account.Contacts__c.split('\n');
             List<String> listOfMoveToContacts = account.Move_To_Contacts__c.split('\n');

            
            if(listOfContacts.size()>0)
            {
                String moveToContact = '';
                for(String contact : listOfMoveToContacts)
                {
                    if(listOfMoveToContacts.size()>0 && listOfContacts.contains(contact))  {
                        
                        if(!mapOfAccountIdAndString.containsKey(account.Move_To_Account__c)) //false
                            mapOfAccountIdAndString.put(account.Move_To_Account__c, new List<String>());
                        
                        mapOfAccountIdAndString.get(account.Move_To_Account__c).add(contact); //st/ st2 //st3
                        moveToContact = '\n';
                    }
                    else{
                         moveToContact = moveToContact+contact+'\n';
                    }
                   
                }
                moveToContact = String.isNotBlank(moveToContact)?moveToContact:moveToContact.replaceAll('\\s', '');
                accountToUpdate.add(new Account(Id = account.Id, Move_To_Contacts__c = moveToContact));
            }
            
        }
    }
    
    if(mapOfAccountIdAndString.size() > 0)
    {    
        for(Id accountId : mapOfAccountIdAndString.keySet()) 
        {
            String contactValue = '';
            for(String contact : mapOfAccountIdAndString.get(accountId))
            {
                contactValue = contactValue+contact+'\n';
            }
            accountToUpdate.add(new Account(Id = accountId, Contacts__c = contactValue));
        }
        
        if(accountToUpdate.size()>0) update accountToUpdate; 
    }
    
}
 

this is my code but it is not working properly ...i want to move contacts from account1 to account2 when my condtion is true...my condtion is that move_to_account__c field is not blank and contact__c == move_to__contacts__c then move all contacts from account1 to lookup account2...like i have 2 contacts in account1 and if my condtions which i mention is true..then these 2 contacts move to lookup account2.

now i want account1 = 0 contact and account2 = 2 contacts

Please someone help me ..its urgent
I have three fields in account object :-
1.Details -textarea long
2. move details -long textarea
3. move accounts - lookup with account

i want to insert contact through the detail field in this format
FirstName = test1, LastName =world, Email=test@gmail.com,Mobile No = 142432423
and same for the move details 
but i want that if my 'move account ' field is not blank: then move all the contacts those are mentioned in the move details field from Original Account to Move  Account 

help me to write trigger for insert,update and delete..
Thanku in advance
 
I have to count Number of contact according to a picklist field value.
i have a picklist field in contact object which has two value - yes and No ,..i have to count those number of contact which ha yes and no and popultate the counting to account's two custom fields --  total_no_yes__c = count no of contact has yes......
total_no__c = count no of contact has no.....
Using SOQl aggregate
#accounthandler.
public without sharing class AccountTriggerHandler1 {
    
    public static void createContacts (List<Account> listAccounts, Map<Id, Account> mapOfoldAccount){
        
        List<Contact> listcontacts = new List<Contact>();
        for(Account account  : listAccounts)
        {
            if(String.isNotBlank(account.Contacts__c) && (mapOfoldAccount == null 
                                                          || mapOfoldAccount.get(account.Id).Contacts__c != account.Contacts__c)){
                                                              
                                                              
                                                              
List<String> listOfContacts = account.Contacts__c.split('\r\n');
for(String lisofstr  : listOfContacts){
                                                                  
    Contact con = new Contact(FirstName = lisofstr.substringAfter('FirstName=').substringBefore(','), 
                              LastName = lisofstr.substringAfter('LastName=').substringBefore(','),
                              MobilePhone =lisofstr.substringAfter('MobilePhone=').substringBefore(','),
                              Email =lisofstr.substringAfter('email=').substringBefore(',') ,
                              AccountId=account.id);
    listcontacts.add(con);  
                                                                  
                                                              }
                                                              if(listcontacts.size() >0){
                                                                  insert listcontacts;    
                                                              }  
                                                              
                                                          }
            
        }
        
    }
}

******Trigger
trigger AccountTrigger1 on Account (after insert , after update ) {

    If(trigger.isAfter &&(Trigger.isInsert || Trigger.isUpdate)){
       AccountTriggerHandler1.createContacts(trigger.new,trigger.oldMap);
    }
}

 
#trigger code
trigger AccountTrigger1 on Account (after insert ) {
    if(trigger.isAfter && trigger.isInsert){
        AccountTriggerHandler1.accountDetails(trigger.new);
    }
}


#triggerhandlercode
public without sharing class AccountTriggerHandler1 {
    public static void accountDetails(list<Account> lstAccount)
    {
        list<Contact> lstContact = new list<Contact>();
       // list<Account> lstAccount = new list<Account>();
        set<Id> setAccountIds = new set<Id>();
        for(account acc : lstAccount){
            setAccountIds.add(acc.Id);  
            }
        if(setAccountIds.size() > 0){
            for(account acc : [SELECT Id , Name ,Contacts__c From Account Where Id In : setAccountIds]){
                    List<String> listofcon = acc.Contacts__c.split('\r\n');
           
                for(String con : listofcon){
                  Contact con1 = new Contact();
                     con1.firstname = con.substringBetween('=',',');
                    con1.LastName =con.substringBetween('=',',');
                        
                con1.MobilePhone = con.substringBetween('=',',');
             con1.Email = con.substringAfter('Email=').substringBefore(',');
             con1.AccountId = acc.Id;
              lstContact.add(con1);
             
                
            }
        }
        if(lstContact.size() > 0){ 
            insert lstContact;    
        }
        
  
    }
}
}

#please help me in this i am newbie to salesforce
 
#like i want to add more than one contact from the custom field of account then how can i add it
 for(account acc : trigger.new){
            setAccountIds.add(acc.Id);  
            }
        if(setAccountIds.size() > 0){
            for(account acc : [SELECT Id , Name ,Contacts__c From Account Where Id In : setAccountIds]){

                String addressFull  = acc.Contacts__c;
                String[] address     = addressFull.split(',');
                String f         =     address[0]; 
                String L          =    address[1];
                String m         =     address[2]; 
                String E          =    address[3];
                String f1 = f.substringAfter('='); 
                String f2 = L.substringAfter('=');
                String f3 = m.substringAfter('=');
                String f4 = E.substringAfter('=');
                
                     contact con = new contact();
                    con.firstname = f1;
                    con.LastName = f2;
                        
                con.MobilePhone = f3;
              con.Email = f4;
             con.AccountId = acc.Id;
               
             acc.Contacts__c ='FirstName'+  ' = ' + con.firstname + ' ,' + 'LastName' + ' = ' +  con.LastName +' ,' + 'MobilePhone' + ' = ' +  con.MobilePhone
                   +' ,'  + 'Email' + ' = ' +  con.Email;
              
            lstAccount.add(acc);  
            lstContact.add(con);
          
custom field in account object = Contact_detail
In this custom field i add firtsname = 'test' Lastname ='test2'
then this contact detail add t contact object by aplying trigger on account
public class ContactTriggerHandler {
   
     public static void getContactDetails(List<Contact> listOfContacts ,Map<Id,Contact> mapOfContact)
     {
      Set<Id> setAccIds = new Set<Id>();
         for(Contact con: listOfContacts != null ? listOfContacts :mapOfContact.values()){
             if(mapOfContact == null && con.AccountId != null){
                 setAccIds.add(con.AccountId);
             }
            if(listOfContacts  != null && mapOfContact != null 
                     && (con.AccountId != mapOfContact.get(con.Id).AccountId || con.FirstName!=mapOfContact.get(con.Id).FirstName
                         || con.LastName != mapOfContact.get(con.Id).LastName)){            
                if(con.AccountId != null)
            {
                setAccIds.add(con.AccountId);
                
            }
             if(mapOfContact.get(con.Id).AccountId != null)
             {
              setAccIds.add(mapOfContact.get(con.Id).AccountId);   
             }
                         }
             if(listOfContacts == null && con.AccountId != null){
                   setAccIds.add(con.AccountId);
             }
         }   
             if(setAccIds.size() > 0){
                 Map<Id , Account> mapOfAccount = new Map<Id , Account>();
                 for(Contact con1: [SELECT id, AccountId , Name FROM Contact WHERE AccountId IN : setAccIds]){
                     if(!mapOfAccount.containskey(con1.AccountId)){
                         mapOfAccount.put(con1.AccountId, new Account (Id = con1.AccountId , Contact_Details__c =''));
                     }
                         mapOfAccount.get(con1.AccountId).Contact_Details__c += con1.Name + '\n';
                     
                     if(mapOfAccount.size() > 0){
                        update mapOfAccount.values();
                     }
                        
                 }
             }
         
          }
}
    
         

         
TriggerHAndlerClass code-

public class BasicAssignemtTriggerHandler {
    
    public void beforeInsert (List<Trigger_Basic_Assignment__c> listOfTrigger){
        
     for(Trigger_Basic_Assignment__c cob : listOfTrigger)
         {
             if (cob.Operator__c == 'Addition'){
                 cob.Field_C__c = cob.Field_A__c+cob.Field_B__c; 
             }
             else if(cob.Operator__c == 'Subtract')
            {
                cob.Field_C__c = cob.Field_A__c - cob.Field_B__c; 
            }
              else if(cob.Operator__c == 'Divide')
            {
                cob.Field_C__c = cob.Field_A__c / cob.Field_B__c; 
            }
             else if (cob.Operator__c == 'Multiply')
            {
                cob.Field_C__c = cob.Field_A__c * cob.Field_B__c; 
            }
             
             
         }
    }
      public void beforeUpdate (List<Trigger_Basic_Assignment__c> listOfTrigger){
        
        for(Trigger_Basic_Assignment__c cob : listOfTrigger)
         {
             if (cob.Operator__c == 'Addition'){
                 cob.Field_C__c = cob.Field_A__c+cob.Field_B__c; 
             }
             else if(cob.Operator__c == 'Subtract')
            {
                cob.Field_C__c = cob.Field_A__c - cob.Field_B__c; 
            }
              else if(cob.Operator__c == 'Divide')
            {
                cob.Field_C__c = cob.Field_A__c / cob.Field_B__c; 
            }
             else if (cob.Operator__c == 'Multiply')
            {
                cob.Field_C__c = cob.Field_A__c * cob.Field_B__c; 
            }
   
         }
                    
    }
  
}


Trigger Code-
trigger BasicAssignmentTrigger on Trigger_Basic_Assignment__c (before insert, before Update) {
    
    
  BasicAssignemtTriggerHandler AssignmentHandler = new BasicAssignemtTriggerHandler();
    if (Trigger.isInsert && Trigger.isBefore){
      
        AssignmentHandler.BeforeInsert(Trigger.new);
    }
    
      if (Trigger.isUpdate && Trigger.isBefore){
      
        AssignmentHandler.BeforeUpdate(Trigger.new);
    }
}
when a contact is inserted or updated then my trigger run on contact and fetch the contact name to that related account..
Like i add two contacts to account 'abc' then in the field of account naemed as 'about_contact__c' details of the contact attached to it.for example my contacts are xyz and kkr then thes two contact details add to my account abc field about_contact__c
I have a trigger in which addition aand subtractionis going for both before insert and update.

public with sharing class HelloFirst {

  
    public static void  demo1 (Integer intNum) {

        List<Account> listOfAccount = new List<Account>();
        for(integer i=1; i<=intNum; i++){
        Account acct = new account();

        acct.name ='sha'+i;

          listOfAccount.add(acct);
        }
        insert listOfAccount;
        system.debug(listOfAccount);
        }


        public static void demo2 (Integer numAccInsert , Map<Integer,Integer> mapOfContact){
   
            list<Account> listOfAcc = new list<Account>();
            list<Contact> listOfCon = new list<Contact>();
    
            for(Integer i = 1; i<=numAccInsert; i++){
               
                Account objAcc = new Account();
                objAcc.name = 'Anjana' +i;
                listOfAcc.add(objAcc);
            }
            insert listOfAcc;
           
            system.debug(listOfAcc);
      
           
            for(Integer j = 1; j< listOfAcc.size(); j++){

                if(mapOfContact.containsKey(j))
          {
             Id accId = listOfAcc[j].id;
             for(Integer k=1; k<=mapOfContact.get(j); k++)
         {
          Contact objCon = new Contact();
          objCon.AccountId = accId ;
          objCon.lastName = 'Sharma'+k;
          listOfCon.add(objCon);    
            }
        }
    }
            insert listOfCon;
            system.debug(listOfCon);
    
           
        }
     public static void demo3(List<Account>listOfAccount , List<Contact>conc){
         
             List<Contact>listOfContact = new List<Contact>();      
            Database.SaveResult[] srList = Database.insert(listOfAccount, false);
                 for (Database.SaveResult sr : srList) {
            if (sr.isSuccess()) {
               
               for(Contact objconc :conc){                   
                   objconc.AccountId = sr.id;    
               }
              // system.debug('conc---'+conc);
                Database.upsert(conc, false);
            } 
               else 
               {
                for(Database.Error err : sr.getErrors()) {
                    System.debug('The following error has occurred.');
                    System.debug(err.getStatusCode() + ': ' + err.getMessage());
                    System.debug('Contact fields that affected this error: ' + err.getFields());                    
                    Error_Log__c a1 = new Error_Log__c(Parent_Record_Name__c = '' , Parent_Record_Id__c = '' ,Error_Details__c = err.getStatusCode() + ': ' + err.getMessage());
                    database.upsert(a1 , false);
             }
               }
                 }
                   system.debug(listOfContact);
     }

}
public class SOQLquery {

  public static void searchForAccount (){
      
       List<Account> acctOfList = [SELECT Name,Website,Offer__c FROM Account ] ;
      System.debug(acctOfList);
     
       List<Account> acctOfList1 = [SELECT Name,Website,Offer__c FROM Account WHERE Name = 'Test' OR Name ='Testing'] ;
      System.debug(acctOfList1);
        
       List<Account> notAccts = [SELECT Name,Website,Offer__c FROM Account WHERE (Name != 'Test' OR Name !='Testing') AND Website != Null ] ;
      System.debug(notAccts);   
    }
    
    /**
     * 
     *   @description    :   Description of the childToParentSOQL
     *
     *   @args           :   
     *
     *   @return         :   void
     *
     *   @revision Log   :   V1.0 - Created  - 2021/06/22 - Anjana Sharma 
     *             
     * 
     **/
    public static void childToParentSOQL(){
        
       List<Contact> objContact =[SELECT Id, FirstName , LastName, Email,Phone, Account.Id, Account.Name , Account.Website FROM Contact] ;
      System.debug(objContact);
       
        List<Contact> objContacts =[SELECT Id, FirstName , LastName, Email,Phone, Account.Id, Account.Name , Account.Website FROM Contact WHERE Email != Null OR Phone != Null] ;
      System.debug(objContacts);
        
        List<Contact> listOfAccount =[SELECT Id, FirstName , LastName, Email,Phone, Account.Id, Account.Name , Account.Website FROM Contact WHERE Account.Id != Null OR Account.Name != 'Test'] ;
      System.debug(listOfAccount);
        
         List<Contact> listOfAccount1 =[SELECT Id, FirstName , LastName, Email,Phone, Account.Id, Account.Name , Account.Website FROM Contact WHERE LastName != Null OR Account.Name != 'Testing'] ;
      System.debug(listOfAccount1);
     
    }
    
  
   public static void parentToChildSOQL(){
        List<Account> accountList =[SELECT Id,Name, (SELECT Id, Name FROM Account_Contact_Childs__r) FROM Account];
         for(Account account : accountList){
        System.debug(account);
         }
         
        List<Contact> contactList =[SELECT Id, (SELECT Id, Name FROM Account_Contact_Childs__r) FROM Contact];
       for(Contact contact : contactList){
        System.debug(contact);
         }
     
    }
      
}

  public static Map<Id, List<Contact>> getContactInformationUsingInlineSOQL(){
        
        Map<Id, List<Contact>> contactMap = new Map<Id, List<Contact>>(); 
       List<Account> lstContact =[SELECT Id ,(SELECT Name FROM Contacts) FROM Account];         
        
        for(Account objContact : lstContact ){   
            contactMap.put(objContact.id, objContact.Contacts);
           System.debug(contactMap);  
        }     
        return contactMap;   
    }

 public static Map<Id, List<Contact>> getContactInformationUsingSOQL(){
     
       List<Account> lstAccount =[SELECT Id FROM Account ];
        List<Contact> lstContact =[SELECT Id , Name FROM Contact WHERE AccountID IN :lstAccount];         
        Map<Id, List<Contact>> contactMap = new Map<Id, List<Contact>>(); 
        for(Contact objContact : lstContact ){
            
            contactMap.put(objContact.Id, new List<Contact>{objContact});
           System.debug(contactMap);  
        }     
        return contactMap;   
    }

 public static Map<Id, List<Contact>> getContactInformationForSpecificAccount(List<Account> acct){
         
         List<Account> lstOfAccount = [SELECT Name FROM Account WHERE ID IN:acct];
         List<Contact> lstOfContact = [SELECT Name FROM Contact WHERE AccountID IN :lstOfAccount]; 
         Map<Id, List<Contact>> contactMap1 = new Map<Id, List<Contact>>(); 
         
         for(Contact objContact : lstOfContact ){
             contactMap1.put(objContact.ID, new List<Contact>{objContact});
           System.debug(contactMap1);  
        }     
        return contactMap1;  
     }
    
 public static void searchForAccount (List<Account>listOfAccount , List<Contact>listOfContact){
         
                // List<Account>listOfAccount = new List<Account>();
               //  List<Contact>listOfContact = new List<Contact>();      
              
         
            Database.SaveResult[] srList = Database.insert(listOfAccount, false);
                 for (Database.SaveResult sr : srList) {
            if (sr.isSuccess()) {
                
               //listOfContact.add(sr.AccountId);  
                Database.insert(listOfContact , false);
                
            } 
               else 
               {
                for(Database.Error err : sr.getErrors()) {
                    System.debug('The following error has occurred.');
                    System.debug(err.getStatusCode() + ': ' + err.getMessage());
                    System.debug('Contact fields that affected this error: ' + err.getFields());                    
                    Error_Log__c a1 = new Error_Log__c(Parent_Record_Name__c = '' , Parent_Record_Id__c = '' ,Error_Details__c = err.getStatusCode() + ': ' + err.getMessage());
                    database.upsert(a1 , false);
             }
               }
                 }
                   system.debug(listOfContact);
     }
}
HEllo everyone ,
I am new to salesforce , i want to know that how can i insert parent object and its field value dynamically and then insert child objects records to it dynamically.

Note :-  i want to pass argument by which i have to pass objects and its field and records

For eg :- I have two args
Map<String, List<String>> mapOfsobject:
In this i pass parent object and list of child objects 

EX:- 'Account'=>{'Contact' ,'Opportunity'}

Map<String, Map<String, String>> mapOfsobjectField

then in this arguments i pass the field and values which i have to insert in objects 

Ex:-'Account'=>new map{'Name'=>'Test'},'Contact'=>new map{'LastName'=>'Test1'}


I have to use dynamic apex in this



I write some code but by my code i only able to insert account i am not able to insert child contact record in the account whicjh i made recently..


Here is my code:--

public class dynamicInsertFieldsRecords {  
    public static void getSobjectRecords(Map<String, List<String>> mapOfsobject ,Map<String, Map<String, String>> mapOfsobjectField ,Map<String, Integer> mapofrecord) {
        
        List<Sobject> listOfParent = new List<Sobject>();
        List<Sobject> listOfChild = new List<Sobject>();
        
        List<Sobject> sObjects = new List<Sobject>();
        List<Sobject> childsObjects = new List<Sobject>();
        
        List<Sobject> litOfsObjects = new List<Sobject>();
        
       // Map< List<Sobject>, List<Sobject>> MapParentChild = new  Map< List<Sobject>, List<Sobject>>();
        
        
        for(String sobj : mapOfsobject.keySet()){
            sObject sObj1 = Schema.getGlobalDescribe().get(sobj).newSObject() ;
            sObjects.add(sObj1);
            
            system.debug(sObjects);
        }
        
        
        for(List<String> objname1 : mapOfsobject.Values()){
            //system.debug(objname1);
            for(String str : objname1)    
            {
                sObject childsObj1 = Schema.getGlobalDescribe().get(str).newSObject() ;
                childsObjects.add(childsObj1);     
            }
        }
        
        
        String objType = String.valueOf(sObjects);
        String ChildobjType = String.valueOf(childsObjects);
        system.debug(objType);
        
        for(String str : mapOfsobjectField.Keyset()){
            system.debug(str);
            
            if(objType.contains(str)){
                //System.debug('str: ' + str);
                for(Integer i = 0; i < mapofrecord.get(str); i++){
                    //System.debug('i: ' + i);
                    sObject sObj = Schema.getGlobalDescribe().get(str).newSObject() ;
                    
                    //System.debug('sObj: ' + sObj);
                    for (String K : mapOfsobjectField.get(str).keyset()){
                        // System.debug('k  '+k);
                        sObj.put(k, (mapOfsobjectField.get(str).get(k) + i));
                        // System.debug('SObject: ' + sObj);
                    }
                    listOfParent.add(sObj);
                    System.debug('SObject: ' + sObj);
                }
                System.debug('listOfParent: ' + listOfParent);
            }  
        }
        insert listOfParent;
        // 
        Map<Id, Sobject> recordsMap = new Map<Id, Sobject>();
        recordsMap.putAll(listOfParent);
        Set<Id> recordIds = recordsMap.keySet();
        system.debug(recordIds);
        
        
        
        for(Id accId : recordIds ){
            String sObjName = accId.getSObjectType().getDescribe().getName();
             SObjectType objToken = Schema.getGlobalDescribe().get(sObjName); 
            DescribeSObjectResult objDef = objToken.getDescribe();
             Map<String, SObjectField> fields = objDef.fields.getMap();
            system.debug(sObjName);
            system.debug(objToken);
            system.debug(objDef);
            system.debug(fields);
            
            for(String str : mapOfsobjectField.Keyset()){
                system.debug(str);
                
                if(ChildobjType.contains(str)){
                    //System.debug('str: ' + str);
                    for(Integer i = 0; i < mapofrecord.get(str); i++){
                        //System.debug('i: ' + i);
                        sObject sObj = Schema.getGlobalDescribe().get(str).newSObject() ;
                        
                        //System.debug('sObj: ' + sObj);
                        for (String K : mapOfsobjectField.get(str).keyset()){
                            // System.debug('k  '+k);
                            sObj.put(k, (mapOfsobjectField.get(str).get(k) + i));
                            System.debug('SObject: ' + sObj);
                        }
                        
                        // listOfChild.add(sObjName);
                        listOfChild.add(sObj);
                        System.debug('SObject: ' + sObj);
                       // MapParentChild.put(listOfParent,listOfChild);  
                     //    System.debug('listOfParent: ' + MapParentChild);
                    }
                    System.debug('listOfParent: ' + listOfChild);
                
                    
                    
                }  
            } 
            
        }
       // insert listOfChild;
      // update MapParentChild.values();
    }
}

Can someone please help me to resolve this
 
///Trigger Handler
public static void createContactsv1 (List<Account> listOfAccounts, Map<Id, Account> mapoldAccount){
    
    Set<Id> setOfIds = new Set<Id>();
    Map<Id, List<String>> mapOfAccountIdAndString = new  Map<Id, List<String>>();
   
    List<Account> accountToUpdate = new List<Account>();
    for(Account account : listOfAccounts){
        
        if(String.isNotBlank(account.Move_To_Account__c) && String.isNotBlank(account.Move_To_Contacts__c) && (mapoldAccount == null 
                                               || mapoldAccount.get(account.Id).Move_To_Account__c != account.Move_To_Account__c
                                               || mapoldAccount.get(account.Id).Move_To_Contacts__c != account.Move_To_Contacts__c))
            
        {
             
             List<String> listOfContacts = account.Contacts__c.split('\n');
             List<String> listOfMoveToContacts = account.Move_To_Contacts__c.split('\n');
            
            
            if(listOfContacts.size()>0)
            {
                String moveToContact = '';
                for(String contact : listOfMoveToContacts)
                {
                    if(listOfMoveToContacts.size()>0 && listOfContacts.contains(contact))  {
                        
                        if(!mapOfAccountIdAndString.containsKey(account.Move_To_Account__c)) //false
                            mapOfAccountIdAndString.put(account.Move_To_Account__c, new List<String>());
                        
                        mapOfAccountIdAndString.get(account.Move_To_Account__c).add(contact); //st/ st2 //st3
                        setOfIds.add(account.Id);
                        moveToContact = '\n';//if move to contact value is contains in contact__c value 
                    }
                    else{
                         moveToContact = moveToContact+contact+'\n'; //if not contains then add contact to movettocontact
                    }
                   
                }
                moveToContact = String.isNotBlank(moveToContact)?moveToContact:moveToContact.replaceAll('\\s', '');
                accountToUpdate.add(new Account(Id = account.Id, Move_To_Contacts__c = moveToContact));
            }
            
        }
    }
    
    if(mapOfAccountIdAndString.size() > 0)
    {    
        for(Id accountId : mapOfAccountIdAndString.keySet()) 
        {
            String contactValue = '';
            for(String contact : mapOfAccountIdAndString.get(accountId))
            {
                contactValue = contactValue+contact+'\n';
            }
            accountToUpdate.add(new Account(Id = accountId, Contacts__c = contactValue));
        }
        
        if(accountToUpdate.size()>0) update accountToUpdate; 
    }
    
    if(setOfIds.size()>0)
    {
        
        List<Contact> contacts = [SELECT Id, Email, FirstName, LastName, Account.Move_To_Account__c, AccountId FROM Contact WHERE AccountId  IN :setOfIds];
        
        list<Contact> contactsTomoved = new List<Contact>();
        if(contacts.size()>0)
        {
            for(Contact contact : contacts)
            {
                for(String contString : mapOfAccountIdAndString.get(contact.Account.Move_To_Account__c))
                { 
                    
                    if(contact.FirstName == contString.substringAfter('FirstName=').substringBefore(',')
                       && contact.LastName == contString.substringAfter('LastName=').substringBefore(',')
                       && contact.Email == contString.substringAfter('Email=').substringBefore(','))
                    {
                        contact.AccountId = contact.Account.Move_To_Account__c;
                        contactsTomoved.add(contact);
                    }
                }
                
            }
        }
        
        if(contactsTomoved.size() > 0) update contactsTomoved;  
    }
 }


///test class--

@isTest
public class AccountTriggerHandlerTest {
    @isTest
    public static void createContactsv2Test()
    {

List<Account>accounts = new List<Account>();
  String str = 'FirstName=A,LastName=A,MobilePhone=1,Email=aa@unknown.com' +'\r\n' + 'FirstName=B,LastName=B,MobilePhone=2,Email=bb@unknown.com';
        Account lookUpAccount = new Account(Name = 'LookUp');
            insert lookUpAccount;
            accounts[0].Move_To_Account__c = lookUpAccount.Id;
            accounts[0].Move_To_Contacts__c = 'FirstName=A,LastName=A,MobilePhone=1,Email=aa@unknown.com';
            update accounts;
            List<Contact> totalContactsAfterMovingContact = [SELECT AccountId, FirstName ,LastName , MobilePhone,Email FROM Contact WHERE AccountId = :accounts[0].Id];
            //System.debug('totalContactsAfterMovingContact: '+ totalContactsAfterMovingContact.size());
            System.assertEquals(2 , totalContactsAfterMovingContact.size());
            
            accounts[0].Contacts__c = '';
            update accounts;
            
            accounts[0].Contacts__c = str;
            update accounts;
            
            List<Contact> totalContactsOnInsertingAndMovingContact = [SELECT AccountId, FirstName ,LastName , MobilePhone, Email FROM Contact WHERE AccountId = :accounts[0].Id];
            //System.debug('totalContactsOnInsertingAndMovingContact: '+ totalContactsOnInsertingAndMovingContact.size());
            System.assertEquals(1 , totalContactsOnInsertingAndMovingContact.size());
            
            accounts[0].Contacts__c = str + '\r\n' + 'FirstName=D,LastName=D,MobilePhone=4,Email=dd@unknown.com' + '\r\n' + 'FirstName=F,LastName=F,MobilePhone=6,Email=ff@unknown.com';
            update accounts;
List<Contact> totalContactsOnInsertingAndMovingContact_1 = [SELECT AccountId, FirstName ,LastName , MobilePhone, Email FROM Contact WHERE AccountId = :accounts[0].Id];
            System.assertEquals(3 , totalContactsOnInsertingAndMovingContact_1.size());
            
            accounts[0].Contacts__c = str;
            update accounts;
            List<Contact> totalContactsOnDeleting = [SELECT AccountId, FirstName ,LastName , MobilePhone, Email FROM Contact WHERE AccountId = :accounts[0].Id];
            //System.debug('totalContactsOnDeleting: '+ totalContactsOnDeleting.size());
            System.assertEquals(1 , totalContactsOnDeleting.size());
            
            accounts[0].Contacts__c = str + '\r\n' + 'FirstName=D,LastName=D,MobilePhone=4,Email=dd@unknown.com' + '\r\n' + 'FirstName=F,LastName=F,MobilePhone=6,Email=ff@unknown.com';
            update accounts;
            List<Contact> totalContactsOnInsertingAndMovingContact_2 = [SELECT AccountId, FirstName ,LastName , MobilePhone, Email FROM Contact WHERE AccountId = :accounts[0].Id];
            System.assertEquals(3 , totalContactsOnInsertingAndMovingContact_2.size());
            
            accounts[0].Move_To_Contacts__c = 'FirstName=A,LastName=A,MobilePhone=1,Email=aa@unknown.com' + '\r\n' + 'FirstName=D,LastName=D,MobilePhone=4,Email=dd@unknown.com';
            update accounts;
            List<Contact> totalContactsAfterMovingContact_1 = [SELECT AccountId, FirstName ,LastName , MobilePhone, Email FROM Contact WHERE AccountId = :accounts[0].Id];
            System.assertEquals(2 , totalContactsAfterMovingContact_1.size());
            
            String str_2 = str + '\r\n' + 'FirstName=D,LastName=D,MobilePhone=4,Email=dd@unknown.com' + '\r\n' + 'FirstName=F,LastName=F,MobilePhone=6,Email=ff@unknown.com';
            accounts[0].Contacts__c = str_2 + '\r\n' + 'FirstName=G,LastName=G,MobilePhone=7,Email=gg@unknown.com';
            accounts[0].Move_To_Contacts__c = 'FirstName=A,LastName=A,MobilePhone=1,Email=aa@unknown.com' + '\r\n' + 'FirstName=D,LastName=D,MobilePhone=4,Email=dd@unknown.com' + '\r\n' + 'FirstName=G,LastName=G,MobilePhone=7,Email=gg@unknown.com';
            update accounts;
List<Contact> totalContactsOnInsertingAndMovingContact_3 = [SELECT AccountId, FirstName ,LastName , MobilePhone, Email FROM Contact WHERE AccountId = :accounts[0].Id];
            System.assertEquals(2 , totalContactsOnInsertingAndMovingContact_3.size());
            
            accounts[0].Contacts__c = '';
            update accounts;
            accounts[0].Contacts__c = str_2 + '\r\n' + 'FirstName=G,LastName=G,MobilePhone=7,Email=gg@unknown.com' + '\r\n' + 'FirstName=H,LastName=H,MobilePhone=8,Email=hh@unknown.com';
            accounts[0].Move_To_Contacts__c = 'FirstName=A,LastName=A,MobilePhone=1,Email=aa@unknown.com' + '\r\n' + 'FirstName=D,LastName=D,MobilePhone=4,Email=dd@unknown.com' + '\r\n' + 'FirstName=G,LastName=G,MobilePhone=7,Email=gg@unknown.com' + '\r\n' + 'FirstName=H,LastName=H,MobilePhone=8,Email=hh@unknown.com';
            update accounts;
            List<Contact> totalContactsOnInsertingAndMovingContact_4 = [SELECT AccountId, FirstName ,LastName , MobilePhone, Email FROM Contact WHERE AccountId = :accounts[0].Id];
            System.assertEquals(2 , totalContactsOnInsertingAndMovingContact_4.size());
            
            accounts[1].Move_To_Contacts__c = 'FirstName=A,LastName=A,MobilePhone=1,Email=aa@unknown.com';
            update accounts;
            accounts[1].Move_To_Contacts__c = str;
            update accounts;
            List<Contact> totalContactsOnInsertingAndMovingContact_5 = [SELECT AccountId, FirstName ,LastName , MobilePhone, Email FROM Contact WHERE AccountId = :accounts[1].Id];
            System.assertEquals(1 , totalContactsOnInsertingAndMovingContact_5.size());
            
            
            Account lookUpAccount_1 = new Account(Name = 'TestLookUp_1');
            insert lookUpAccount_1;
            accounts[2].Move_To_Account__c = lookUpAccount_1.Id;
            accounts[2].Move_To_Contacts__c = 'FirstName=A,LastName=A,MobilePhone=1,Email=aa@unknown.com';
            update accounts;
            
            
        }


///Please someone tell me where i am getting wrong
public static void countContactDetails(List<Contact> listContacts, Map<Id,Contact> mapOldContacts){
     Set<Id> setAccountId = new Set<Id>();
     Map<Id,Account> mapOfAccount = new Map<Id,Account>();
        if( mapOldContacts == null || mapOldContacts.isEmpty() ) {
            for( Contact objCont : listContacts ) {
                if( objCont.AccountId != null ) {
                    setAccountId.add( objCont.AccountId );
                }
            }
        }
        else if( mapOldContacts != null && !mapOldContacts.isEmpty()) {
            for( Contact objCont : listContacts ) { 
                if( objCont.AccountId != null 
                && mapOldContacts.get( objCont.Id ).AccountId != objCont.AccountId ) {
                    setAccountId.add( objCont.AccountId );
                    if( mapOldContacts.get( objCont.Id ).AccountId != null ) {
                        setAccountId.add( mapOldContacts.get( objCont.Id ).AccountId );
                    }
                }
                else if( objCont.AccountId == null && mapOldContacts.get( objCont.Id ).AccountId != objCont.AccountId ) {
                    setAccountId.add( mapOldContacts.get( objCont.Id ).AccountId );
                }
            }
        }
        if( !setAccountId.isEmpty() ) {
            List<Account> listAccount = new List<Account>();
            for (AggregateResult ar : [SELECT AccountId AcctId, Count(id) ContactCount 
                                       FROM Contact
                                       WHERE AccountId in: setAccountId 
                                       GROUP BY AccountId]){
                                           Account a = new Account();
                                           a.Id = (Id) ar.get('AcctId');
                                           a.Total_Contacts__c = (Integer) ar.get('ContactCount');
                                           listAccount.add(a);

            
        }
   if( !listAccount.isEmpty() ) {
                update listAccount;
            }  
 }
    
             if( !setAccountId.isEmpty() ) {
                  List<Account> listAccount1 = new List<Account>();
            List<AggregateResult> results = [Select AccountId ,Count(Id) ContactCount, Contact_Status__c str from Contact  WHERE AccountId in: setAccountId GROUP BY AccountId, Contact_Status__c];
                  Integer activecount = 0;
                  Integer inactivecount = 0;
                 for (AggregateResult ar : results)  {
                    if(ar.get('str')=='Active'){
                           
                        activecount += (Integer)ar.get('ContactCount');
                     }
                      if(ar.get('str')=='Inactive'){
                          inactivecount = (Integer)ar.get('ContactCount');  
                     }
                     //a.Total_Contacts__c = (Integer) ar.get('ContactCount');
                    // mapOfAccount.put((ID)ar.get('AccountId') , new Account(Id = (Id)ar.get('AccountId'),Total_Active_Contacts__c = activecount ,Total_Inactive_Contacts__c = inactivecount));
                      Account a1 = new Account();
                       a1.Id = (Id) ar.get('AccountId');
                       a1.Total_Active_Contacts__c = activecount;
                     a1.Total_Inactive_Contacts__c = inactivecount;
                  listAccount1.add(a1);
                 }

system.debug('Mapofaccount=='+ listAccount1);
    
 }
    } 
I have to count Number of contact according to a picklist field value.
i have a picklist field in contact object which has two value - yes and No ,..i have to count those number of contact which ha yes and no and popultate the counting to account's two custom fields --  total_no_yes__c = count no of contact has yes......
total_no__c = count no of contact has no.....
Using SOQl aggregate
custom field in account object = Contact_detail
In this custom field i add firtsname = 'test' Lastname ='test2'
then this contact detail add t contact object by aplying trigger on account
public class ContactTriggerHandler {
   
     public static void getContactDetails(List<Contact> listOfContacts ,Map<Id,Contact> mapOfContact)
     {
      Set<Id> setAccIds = new Set<Id>();
         for(Contact con: listOfContacts != null ? listOfContacts :mapOfContact.values()){
             if(mapOfContact == null && con.AccountId != null){
                 setAccIds.add(con.AccountId);
             }
            if(listOfContacts  != null && mapOfContact != null 
                     && (con.AccountId != mapOfContact.get(con.Id).AccountId || con.FirstName!=mapOfContact.get(con.Id).FirstName
                         || con.LastName != mapOfContact.get(con.Id).LastName)){            
                if(con.AccountId != null)
            {
                setAccIds.add(con.AccountId);
                
            }
             if(mapOfContact.get(con.Id).AccountId != null)
             {
              setAccIds.add(mapOfContact.get(con.Id).AccountId);   
             }
                         }
             if(listOfContacts == null && con.AccountId != null){
                   setAccIds.add(con.AccountId);
             }
         }   
             if(setAccIds.size() > 0){
                 Map<Id , Account> mapOfAccount = new Map<Id , Account>();
                 for(Contact con1: [SELECT id, AccountId , Name FROM Contact WHERE AccountId IN : setAccIds]){
                     if(!mapOfAccount.containskey(con1.AccountId)){
                         mapOfAccount.put(con1.AccountId, new Account (Id = con1.AccountId , Contact_Details__c =''));
                     }
                         mapOfAccount.get(con1.AccountId).Contact_Details__c += con1.Name + '\n';
                     
                     if(mapOfAccount.size() > 0){
                        update mapOfAccount.values();
                     }
                        
                 }
             }
         
          }
}
    
         

         
when a contact is inserted or updated then my trigger run on contact and fetch the contact name to that related account..
Like i add two contacts to account 'abc' then in the field of account naemed as 'about_contact__c' details of the contact attached to it.for example my contacts are xyz and kkr then thes two contact details add to my account abc field about_contact__c

public with sharing class HelloFirst {

  
    public static void  demo1 (Integer intNum) {

        List<Account> listOfAccount = new List<Account>();
        for(integer i=1; i<=intNum; i++){
        Account acct = new account();

        acct.name ='sha'+i;

          listOfAccount.add(acct);
        }
        insert listOfAccount;
        system.debug(listOfAccount);
        }


        public static void demo2 (Integer numAccInsert , Map<Integer,Integer> mapOfContact){
   
            list<Account> listOfAcc = new list<Account>();
            list<Contact> listOfCon = new list<Contact>();
    
            for(Integer i = 1; i<=numAccInsert; i++){
               
                Account objAcc = new Account();
                objAcc.name = 'Anjana' +i;
                listOfAcc.add(objAcc);
            }
            insert listOfAcc;
           
            system.debug(listOfAcc);
      
           
            for(Integer j = 1; j< listOfAcc.size(); j++){

                if(mapOfContact.containsKey(j))
          {
             Id accId = listOfAcc[j].id;
             for(Integer k=1; k<=mapOfContact.get(j); k++)
         {
          Contact objCon = new Contact();
          objCon.AccountId = accId ;
          objCon.lastName = 'Sharma'+k;
          listOfCon.add(objCon);    
            }
        }
    }
            insert listOfCon;
            system.debug(listOfCon);
    
           
        }
     public static void demo3(List<Account>listOfAccount , List<Contact>conc){
         
             List<Contact>listOfContact = new List<Contact>();      
            Database.SaveResult[] srList = Database.insert(listOfAccount, false);
                 for (Database.SaveResult sr : srList) {
            if (sr.isSuccess()) {
               
               for(Contact objconc :conc){                   
                   objconc.AccountId = sr.id;    
               }
              // system.debug('conc---'+conc);
                Database.upsert(conc, false);
            } 
               else 
               {
                for(Database.Error err : sr.getErrors()) {
                    System.debug('The following error has occurred.');
                    System.debug(err.getStatusCode() + ': ' + err.getMessage());
                    System.debug('Contact fields that affected this error: ' + err.getFields());                    
                    Error_Log__c a1 = new Error_Log__c(Parent_Record_Name__c = '' , Parent_Record_Id__c = '' ,Error_Details__c = err.getStatusCode() + ': ' + err.getMessage());
                    database.upsert(a1 , false);
             }
               }
                 }
                   system.debug(listOfContact);
     }

}
public class SOQLquery {

  public static void searchForAccount (){
      
       List<Account> acctOfList = [SELECT Name,Website,Offer__c FROM Account ] ;
      System.debug(acctOfList);
     
       List<Account> acctOfList1 = [SELECT Name,Website,Offer__c FROM Account WHERE Name = 'Test' OR Name ='Testing'] ;
      System.debug(acctOfList1);
        
       List<Account> notAccts = [SELECT Name,Website,Offer__c FROM Account WHERE (Name != 'Test' OR Name !='Testing') AND Website != Null ] ;
      System.debug(notAccts);   
    }
    
    /**
     * 
     *   @description    :   Description of the childToParentSOQL
     *
     *   @args           :   
     *
     *   @return         :   void
     *
     *   @revision Log   :   V1.0 - Created  - 2021/06/22 - Anjana Sharma 
     *             
     * 
     **/
    public static void childToParentSOQL(){
        
       List<Contact> objContact =[SELECT Id, FirstName , LastName, Email,Phone, Account.Id, Account.Name , Account.Website FROM Contact] ;
      System.debug(objContact);
       
        List<Contact> objContacts =[SELECT Id, FirstName , LastName, Email,Phone, Account.Id, Account.Name , Account.Website FROM Contact WHERE Email != Null OR Phone != Null] ;
      System.debug(objContacts);
        
        List<Contact> listOfAccount =[SELECT Id, FirstName , LastName, Email,Phone, Account.Id, Account.Name , Account.Website FROM Contact WHERE Account.Id != Null OR Account.Name != 'Test'] ;
      System.debug(listOfAccount);
        
         List<Contact> listOfAccount1 =[SELECT Id, FirstName , LastName, Email,Phone, Account.Id, Account.Name , Account.Website FROM Contact WHERE LastName != Null OR Account.Name != 'Testing'] ;
      System.debug(listOfAccount1);
     
    }
    
  
   public static void parentToChildSOQL(){
        List<Account> accountList =[SELECT Id,Name, (SELECT Id, Name FROM Account_Contact_Childs__r) FROM Account];
         for(Account account : accountList){
        System.debug(account);
         }
         
        List<Contact> contactList =[SELECT Id, (SELECT Id, Name FROM Account_Contact_Childs__r) FROM Contact];
       for(Contact contact : contactList){
        System.debug(contact);
         }
     
    }
      
}

  public static Map<Id, List<Contact>> getContactInformationUsingInlineSOQL(){
        
        Map<Id, List<Contact>> contactMap = new Map<Id, List<Contact>>(); 
       List<Account> lstContact =[SELECT Id ,(SELECT Name FROM Contacts) FROM Account];         
        
        for(Account objContact : lstContact ){   
            contactMap.put(objContact.id, objContact.Contacts);
           System.debug(contactMap);  
        }     
        return contactMap;   
    }

 public static Map<Id, List<Contact>> getContactInformationUsingSOQL(){
     
       List<Account> lstAccount =[SELECT Id FROM Account ];
        List<Contact> lstContact =[SELECT Id , Name FROM Contact WHERE AccountID IN :lstAccount];         
        Map<Id, List<Contact>> contactMap = new Map<Id, List<Contact>>(); 
        for(Contact objContact : lstContact ){
            
            contactMap.put(objContact.Id, new List<Contact>{objContact});
           System.debug(contactMap);  
        }     
        return contactMap;   
    }

 public static Map<Id, List<Contact>> getContactInformationForSpecificAccount(List<Account> acct){
         
         List<Account> lstOfAccount = [SELECT Name FROM Account WHERE ID IN:acct];
         List<Contact> lstOfContact = [SELECT Name FROM Contact WHERE AccountID IN :lstOfAccount]; 
         Map<Id, List<Contact>> contactMap1 = new Map<Id, List<Contact>>(); 
         
         for(Contact objContact : lstOfContact ){
             contactMap1.put(objContact.ID, new List<Contact>{objContact});
           System.debug(contactMap1);  
        }     
        return contactMap1;  
     }
    
 public static void searchForAccount (List<Account>listOfAccount , List<Contact>listOfContact){
         
                // List<Account>listOfAccount = new List<Account>();
               //  List<Contact>listOfContact = new List<Contact>();      
              
         
            Database.SaveResult[] srList = Database.insert(listOfAccount, false);
                 for (Database.SaveResult sr : srList) {
            if (sr.isSuccess()) {
                
               //listOfContact.add(sr.AccountId);  
                Database.insert(listOfContact , false);
                
            } 
               else 
               {
                for(Database.Error err : sr.getErrors()) {
                    System.debug('The following error has occurred.');
                    System.debug(err.getStatusCode() + ': ' + err.getMessage());
                    System.debug('Contact fields that affected this error: ' + err.getFields());                    
                    Error_Log__c a1 = new Error_Log__c(Parent_Record_Name__c = '' , Parent_Record_Id__c = '' ,Error_Details__c = err.getStatusCode() + ': ' + err.getMessage());
                    database.upsert(a1 , false);
             }
               }
                 }
                   system.debug(listOfContact);
     }
}
Send an email using triggers to contacts related to the accounts when account is updated. If 2 contacts has same email than send only 1 mail to that contacts having similar emails. In the email body mention the name of contacts having similar emails in a tabular format. For example if the Account A1 has 5 contacts c1, c2, c3, c4, c5 and c1, c2, c3 has similar emails and other having unique email than the names of the contact should be show in the table in the email body of the contacts having similar emails.