• SF Beginner 2019
  • NEWBIE
  • 90 Points
  • Member since 2018

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 37
    Questions
  • 31
    Replies
I am experiencing DML Error 10001 ,

can you spot on which is needed to be optimize more in here.


public with sharing class UpdateStatus {
    public static final String ClsName  = 'UpdateStatus';
    public static boolean isExecuting=false;
    public static boolean isInvoked = false;
    public static boolean isCnclGSChkd = false;
    public static final String UpdateActiveStatus  = 'ActiveStatus' ;
    public static final String UpdateCancelStatus  = 'CancelStatus' ;
    public static final String UpdateRecType = 'RecTypeStat' ;
    public static final String UpdateCancelBff = 'CancelStats';
    public static final String  UpdateEndDate = 'UpdateEndDate';
    public static final string acctClient =Schema.SObjectType.Account.getRecordTypeInfosByName().get('Account - Client').getRecordTypeId();
    public static final string acctClientInt =  Schema.SObjectType.Account.getRecordTypeInfosByName().get('Account - InactiveClient').getRecordTypeId();
    public static final String  actv='Active';
    public static final String  cancl='Canceled';
    public static final String pendng =  'Pending';
    public static final String  accntCst= 'Account_Client';
    public static final String  cncled= 'Canceled';
    public static final String  inactv= 'Inactive';
    public static final Date enddateFuture = Date.newInstance(2100, 12, 31);
    public static  List<Id> cnclgmList = new List<Id>();
    public static final string profIntUser='Integration User';
    public static final string categNet='Verizon';
    

    public static void ActiveStatus(List<Group_Members> gmList)
    {

            Date EndDateFr;
            map<id,integer> prcOpn=new map<id,integer>();
            list<id> gpToProc=new list<id>();
            String profileName = [Select Name from Profile where Id = :UserInfo.getProfileId() limit 1].Name;
            for(Group_Members objGM : gmList){
                
                if(objGM.Status__c==pendng ){
                    gpToProc.add(objGM.Id);
                }
            }
            
            list<aggregateResult> PrcssLst=[select GM_ID,count(Id) OpenGM from WF_GM__c where GM_ID in:gpToProc 
                                              and (GA_Status__c='Closed') and GM_NS__c=null and GM_Sid__c !=null  group by GM_ID  limit 2000];
            for(aggregateResult agRst:PrcssLst)
            {
                prcOpn.put(string.valueof(agRst.get('GM_ID')),integer.valueof(agRst.get('OpenGM')));   
            }
            
            for(Group_Members objGM : gmList){
                if(objGM.EffDate__c<=system.today() && 
                   objGM.cancelDate__c==null){
                       EndDateFr = enddateFuture;
                   }
                else{
                    EndDateFr = objGM.cancelDate__c;
                }
                if(objGM.Status__c==pendng  && objGM.Network__c==categNet){
                    if(prcOpn.get(objGM.Id)>0)
                        objGM.Status__c=actv;
                }
                if(objGM.Status__c==pendng  && (objGM.Trans__c || objGM.Post__c)){
                    if(prcOpn.get(objGM.Id)>0)
                        objGM.Status__c=actv;
                }  
                if(profileName==profIntUser){
                    if(objGM.Status__c==cncled && EndDateFr>system.today() 
                       && objGM.EffDate__c<=system.today())
                    {
                        objGM.Status__c=actv;
                    }   
                }  
            }

    }

    public static void RecTypeStat(List<Group_Members> gmList)
    {
            set<id> accIds=new set<id>();
            Date gmEndDateFr;
            boolean isChnge=false;
            String profileName = [Select Name from Profile where Id = :UserInfo.getProfileId() limit 1].Name;
            Map<Id, Date> gmACCMap = new Map<Id, Date>();
            for(Group_Members objGM : gmList){
                gmACCMap.put(objGM.Account_c,objGM.EffDate__c);
                if(objGM.Status__c==actv && objGM.Network__c==categNet)
                {
                    accIds.add(objGM.Account_c);
                }
                if(objGM.Status__c==actv && (objGM.Trans__c || objGM.Post__c))
                {
                    accIds.add(objGM.Account_c);
                }
                
                if(profileName==profIntUser){
                    if(objGM.Status__c==cncled && gmEndDateFr>system.today() 
                       && objGM.EffDate__c<=system.today())
                    {
                        accIds.add(objGM.Account_c);
                    }
                }
                
            } 
            List<Account>  accLst =[Select id,RecordType.DeveloperName from Account WHERE ID IN :accIds Limit 50000] ;
            List<Account>  updtAccLst = New   List<Account>();
            
            if(!accIds.isEmpty()){
                for(Account objAcc : accLst){
                    if(objAcc.RecordType.DeveloperName != accntCst){
                        objAcc.RecordTypeId = acctClient;
                        objAcc.Account_Status__c=actv;
                        objAcc.CovCancelDate__c=null;
                        objAcc.EnrollDate__c = gmACCMap.get(objAcc.Id);
                        updtAccLst.add(objAcc);
                    }
                }
            }  
            
            if(!updtAccLst.isEmpty()){
                Database.update(updtAccLst);
            }
            isInvoked= true; 
        }
        
    }

    public static void CancelStats(List<Group_Members> grpmemList,map<id,Group_Members> grpmemListOld)
    {
            for(Group_Members grp:grpmemList)
            {
                boolean CnclChk=false;
                boolean CnclDteChk=false;
                if(grpmemListOld!=null)
                {
                    Group_Members grpOld=grpmemListOld.get(grp.Id);  
                    if(grp.cancelDate__c <> grpOld.cancelDate__c)
                        CnclChk=true;
                    if((grp.Status__c <> grpOld.Status__c) && grp.Status__c==cancl)
                    {
                        CnclDteChk=true;
                    }
                }
                else
                {
                    CnclChk=true;
                    if(grp.Status__c==cancl)
                    {
                        CnclDteChk=true; 
                    }
                }
                
                if(grp.cancelDate__c<=system.today() && CnclChk)
                {
                    grp.Status__c=cancl;
                    cnclgmList.add(grp.Id);
                    
                }
            }
            isCnclGSChkd = true;
        }
        
    }

    public static void CancelStatus(List<Group_Members> grpmemList,Map<ID,Group_Members> grpOldMap)
    {
            set<id> cnclAccIdsToPrcss=new set<id>();
            boolean isChnge=false;
            for(Group_Members grp:grpmemList)
            {
                if(grpOldMap !=null)
                {
                    Group_Members grpOld=grpOldMap.get(grp.Id);
                    if(grpOld.cancelDate__c !=grp.cancelDate__c  
                       || grpOld.Status__c !=grp.Status__c){
                           isChnge=true;     
                       }
                }
                
                else
                {
                    isChnge=true;
                }
                if(grp.cancelDate__c<=system.today() && isChnge)
                {
                    cnclAccIdsToPrcss.add(grp.Account_c);
                }
            }

            if(cnclAccIdsToPrcss.size() > 0){
                
                List<Account> accLst = [Select Id,Account_Status__c,RecordType.DeveloperName ,CovCancelDate__c,
                                        (select Status__c,cancelDate__c from Group_Member__r ORDER BY LastModifiedDate ASC)
                                        from Account where id in:cnclAccIdsToPrcss Limit 50000];
                List<Account>  acntIdsToPrcs = new List<Account>();
                List<Account>  finalacntIdsToPrcs = new List<Account>();
                Set<Id> processAccIds = New Set<Id>();
                boolean flag = false;
                Set<Id> accActv = New Set<Id> ();
                
                for(Account objAcc :accLst){
                    
                    if(!objAcc.Group_Member__r.isEmpty()){
                        for(Group_Members objGM : objAcc.Group_Member__r){
                            if(objGM.Status__c.equals(actv)){
                                flag = true;   
                                accActv.add(objAcc.id);
                                break;
                            }
                            else{
                                if(cnclgmList.contains(objGM.Id) && !processAccIds.contains(objAcc.id)  ){
                                    objAcc.CovCancelDate__c=objGM.cancelDate__c;
                                    objAcc.RecordTypeId =acctClientInt;
                                    objAcc.Account_Status__c=inactv;
                                    objAcc.EnrollDate__c=null;
                                    acntIdsToPrcs.add(objAcc); 
                                    processAccIds.add(objAcc.id);
                                }
                            }
                        }
                    }
                } 

                if(accActv.size() > 0){
                    processAccIds.removeAll(accActv);
                }

                for(Account accCus : acntIdsToPrcs){
                    if(processAccIds.contains(accCus.id)){
                        finalacntIdsToPrcs.add(accCus);
                    }
                }
                
                if(finalacntIdsToPrcs.size()>0 ){
                    
                    Database.update(acntIdsToPrcs);
                }
                
            }
            
            isExecuting=true;
      
    }
  
    public static void UpdateEndDate(List<Group_Members> grpmemList,map<id,Group_Members> grpmemListOld){
            List<id> gsIdLst = new List<id>();
            List<History__c> TCList = new List<History__c>(); 
            for(Group_Members grp:grpmemList)
            {
                if(grpmemListOld!=null)
                {
                    Group_Members grpOld=grpmemListOld.get(grp.Id);
                    
                    if(grp.History__c <> grpOld.History__c){
                        gsIdLst.add(grpOld.History__c);
                        
                    }
                } 
            }
            if(!gsIdLst.isEmpty()){
                for(History__c tp : [select id,EndDateTC__c,GA_TPB_Start_Date__c from History__c
                                                           where ID IN : gsIdLst Limit 50000]){
                                                               tp.EndDateTC__c = system.today()-1;
                                                               TCList.add(tp);                                                      
                                                           }
                Database.update(TCList);
            }
        }   
        
    }
}

 
global class UnlockRecordBatchJob implements Database.batchable<sObject> {
    //Start of this batch job
    global Database.QueryLocator start(Database.BatchableContext BC) {
        String query = 'SELECT Id FROM Case LIMIT 50000000 '; //50 Million records
        return Database.getQueryLocator(query);
    }
    //Exeution of batch job
    global void execute(Database.BatchableContext BC, List<Case> scope) { //Scope max = 2000
        //List<Case> caseList = [SELECT Id From CaseLimit 2]; case already in scope varible
        //Check locked records
        List<Case> caseLockList = new List<Case>();
        for(Case c : scope)
        {
            if(Approval.isLocked(c.id)){
                caseLockList.add(c);
            }
        }
        
        if(!caseLockList.isEmpty()){
            //Unlock records
            List<Approval.UnlockResult> ulrList = Approval.unlock(caseLockList, false);
            
            // Iterate through each returned result
            for(Approval.UnlockResult  ulr : ulrList) {
                if (ulr.isSuccess()) {
                    //Operation was successful, so get the ID of the record that was processed
                    System.debug('Successfully locked account with ID: ' + ulr.getId());
                }
                else {
                    //Operation failed, so get all errors                
                    for(Database.Error err : ulr.getErrors()) {
                        System.debug('The following error has occurred.');                    
                        System.debug(err.getStatusCode() + ': ' + err.getMessage());
                        System.debug('Case fields that affected this error: ' + err.getFields());
                    }
                }
            }
        }
    }
    //finish job
    global void finish(Database.BatchableContext BC) {
    }
}

I am stuck at 22% the Execute is not being covered
 
Hi can you revise my code if it is not correct wherein I want to update all case records wherein I will unlock all of them. I tested one record and its updating but I think when its all or bulk its not updating.
 
global class UnlockRecordBatchJob implements Database.batchable<sObject> {
    //Start of this batch job
    global Database.QueryLocator start(Database.BatchableContext BC) {
        String query = 'SELECT Id from Case Limit 2';
        return Database.getQueryLocator(query);
    }
    //Exeution of batch job
    global void execute(Database.BatchableContext BC, List<Case> scope) {
        List<Case> caseList = [SELECT Id From CaseLimit 2];
        //Check locked records
        List<Case> caseLockList = new List<Case>();
        for(Case c : caseList)
        {
            if(Approval.isLocked(c.id)){
                caseLockList.add(c);
            }
        }
        
        if(!caseLockList.isEmpty()){
            //Unlock records
            List<Approval.UnlockResult> ulrList = Approval.unlock(caseLockList, false);
            
            // Iterate through each returned result
            for(Approval.UnlockResult  ulr : ulrList) {
                if (ulr.isSuccess()) {
                    //Operation was successful, so get the ID of the record that was processed
                    System.debug('Successfully locked account with ID: ' + ulr.getId());
                }
                else {
                    //Operation failed, so get all errors                
                    for(Database.Error err : ulr.getErrors()) {
                        System.debug('The following error has occurred.');                    
                        System.debug(err.getStatusCode() + ': ' + err.getMessage());
                        System.debug('Case fields that affected this error: ' + err.getFields());
                    }
                }
            }
        }
    }
    //finish job
    global void finish(Database.BatchableContext BC) {
    }
}

 
public static void removeold(Set<Id> oldRecords){

    try{       
       ShareListoAgent = New List<SObject> ();
        ObjectName=new List<Id>(oldRecords).get(0).getSObjectType().getDescribe().getName();
        String queryStr ='select id,UserOrGroupId,parentid,RowCause  from';
        
        if(ObjectName == MemberUpper){
            queryStr = queryStr + ' MemberUpper_Share ';
        }
        if(ObjectName == MemberLower){
            queryStr = queryStr + ' MemberLower_Share ';
        }
        if(ObjectName == 'Account'){
            queryStr = 'select id,UserOrGroupId,AccountId,RowCause  from' + ' AccountShare where AccountId in:oldRecords and RowCause = \'Manual\'';
        }
        if(ObjectName == MemberLower || ObjectName == MemberUpper){
            queryStr = queryStr+'where ParentId in:oldRecords and RowCause = \'Manual\'';
        }
        ShareListoAgent.addAll(Database.query(queryStr));
        //ShareListoAgent = [select id,UserOrGroupId,parentid,RowCause  from MemberUpper_Share where parentid in: oldRecords and RowCause = 'Manual' ];
        system.debug('*******ShareListoAgent*******'+ShareListoAgent);
        if(ShareListoAgent !=null && ShareListoAgent.size()>0){
            delete ShareListoAgent;
        }
      }

 
public static void insertSharedRecord(Map<Id,Set<Id>>conRepMap, Map<Id,Set<ID>> conCovMemIDS){

     try{  
        createShareRecords = New List<Sobject>();
         for(id agentConId: conCovMemIDS.keyset()){
               if(conRepMap.containsKey(agentConId)){
                  for(id covRecID: conCovMemIDS.get(agentConId)){
                     for(id covUsrID: conRepMap.get(agentConId)){
                         SObject shareOBJ;
                         if(ObjectName == coverageMem){
                            shareOBJ = Schema.getGlobalDescribe().get('Coverage_Member__share').newSObject();  
                          }
                         if(ObjectName == coverage){
                         shareOBJ = Schema.getGlobalDescribe().get('Coverage__share').newSObject();  
                          } 
                         shareOBJ.put('ParentId', covRecId);
                         shareOBJ.put('UserOrGroupId', covUsrID);
                         shareOBJ.put('AccessLevel', 'Read');
                         shareOBJ.put('RowCause', 'Manual');
                         createShareRecords.add(shareOBJ);
                     }                    
                  }             
               }
         }             
        
      }

 
global class ChangingCapsLock{
    global static void Change( Account [] acc){
        for(Account a :acc){
            
            if(a.BillingPostalCode !=null )
                a.BillingPostalCode = allUpper(a.BillingPostalCode);
            
            if(a.BillingCountry !=null )
                a.BillingCountry= formatToUpper(a.BillingCountry);
            a.BillingCountry= formatToUpperLower(a.BillingCountry);
            
            if(a.BillingCountry ==null )
           String.isEmpty(a.BillingCountry);
            
            if(a.ShippingPostalCode !=null )
                a.ShippingPostalCode = allUpper(a.ShippingPostalCode);
            
            if(a.ShippingCountry !=null )
                a.ShippingCountry= formatToUpper(a.ShippingCountry);
            a.ShippingCountry= formatToUpperLower(a.ShippingCountry);
            
        }
    }
    public static String formatToUpper (String Str) {
        String result = '';
        for (String iter : Str.split('[ ]+')) {
            if (iter != null  && iter != '') {
                if (iter.length() > 1) {
                    result += iter.substring(0,1).toUpperCase() + iter.substring(1,iter.length()) + ' ';
                }
                else
                    result += iter.substring(0,1).toUpperCase() + ' ';
            }
        }
        return result;
    }
    public static String allUpper (String Str) {
        String result = '';
        for (String iter : Str.split('[ ]+')) {
            if (iter != null && iter != '') {
                if (iter.length() > 1) {
                    result += iter.substring(0,1).toUpperCase() + iter.substring(1,iter.length()).toUpperCase() + ' ';
                }
                else
                    result += iter.substring(0,1).toUpperCase() + ' ';
            }
        }
        return result;
    }
    public static String formatToUpperLower (String Str) {
        String result = '';
        for (String iter : Str.split('[ ]+')) {
            if (iter != null && iter != '') {
                if (iter.length() > 1) {
                    result += iter.substring(0,1).toUpperCase() + iter.substring(1,iter.length()).toLowerCase() + ' ';
                }
                else
                    result += iter.substring(0,1).toLowercase() + ' ';
            }
        }
        return result;
    }
}
 
trigger AccountChangerFirstLetter on Account (before insert, before update) {
 ChangingCapsLock.Change(trigger.new);
      if(trigger.isBefore )
         if(trigger.IsInsert ||trigger.IsUpdate )
           ChangingCapsLock.Change(trigger.new);    
}

 
I have this code, wherein it deletes the record when there is a value, how can I achieve to update if the values like UserIdforCsr is just the same?
public static void NewSharing(Set<Id> oldRecords){
        try{       
            CSRShareList = New List<SObject> ();
            ObjectName=new List<Id>(oldRecords).get(0).getSObjectType().getDescribe().getName();
            String strqy ='select id,UserIdforCSR,parentid,RowCause  from';
            
            if(ObjectName == assMember){
                strqy = strqy + ' Assistant_Sharing ';
            }
            if(ObjectName == secMember){
                strqy = strqy + ' Secretary_Sharing ';
            }
            if(ObjectName == 'Account'){
                strqy = 'select id,UserIdforCSR,AccountId,RowCause  from' + ' AccountShare where AccountId in:oldRecords';
            }
            if(ObjectName == secMember || ObjectName == assMember){
                strqy = strqy+'where ParentId in:oldRecords ';
            }
            CSRShareList.addAll(Database.query(strqy));

            if(CSRShareList !=null && CSRShareList.size()>0){
                delete CSRShareList;
            }
        }

 
is there a way we can optimize these more?
 
public static void checkOpenActivities(List<Case> caseList,Map<Id,Case> caseOldMap) {
        
       List<Case> casedList = New List<Case>();
       List<Task> tskList = new List<Task>();
       integer openActivitiesCount = 0;

       Set<Id> cId = new Set<Id>();
       for(Case cs : caseList) {
            cId.add(cs.Id);
       }
       tskList = [SELECT Id,Status FROM Task Where Status != 'Completed' AND WhatId IN :cId];
        for(Case csNew : caseList) {
            if(tskList.size() != 0 && (csNew.Type__c == 'Question' || csNew.Type__c == 'Information') && csNew.Status == 'Closed') {
                csNew.addError('Can not be closed this');
            }
        }
        
    }

 
how can I update the permission set wherein if it exist nothing will changes to the record. and if not exist create that permission set
I am Encountering this error

Unable to Access Page
The value of a parameter contains a character that is not allowed or the value exceeds the maximum allowed length. Remove the character from the parameter value or reduce the value length and resubmit. If the error still persists, report it to our Customer Support team. Provide the URL of the page you were requesting as well as any other related information. 

wherein I just followed this one

https://automationchampion.com/tag/auto-remove-permission-sets-in-salesforce/

so I created a process builder wherein upon edit or create, it will assigne a permission set. the create works perfectly, but when I tried to do blank update/update of a field, it returns tha above error
How to call this apex class to make it a batch job?
 
public class ApplicationYearsinService{

    public static void YearsinService(List<Application__c> appList){
        //Declares the Variables, List, ID to be used
        Date dat = System.today();
        Integer yr = dat.year();   
        Map<Id, Set<Integer>> setofYear = new Map<Id, Set<Integer>>();
        Set<Id> accountIdSet = new set<Id>();
        
        //Gets the values of the Account(Account__c from the Application
        for(Application__c cs: appList ){
            accountIdSet.add(cs.Account__c);            
        }
        
        //Query in the Application to get the value from the Account
        for(Application__c p : [SELECT ID, Account__c, Received_Date__c from Application__c where Account__c IN : accountIdSet ]){
            if(p.Received_Date__c != null){
                if(setofYear.containskey(p.Account__c)){
                    if(p.Received_Date__c != NULL) {
                        setofYear.get(p.Account__c).add(p.Received_Date__c.Year());
                    }
                }
                else {
                    setofYear.put(p.Account__c, new Set<Integer>{p.Received_Date__c.Year()});
                }     
            }
        }
        
        Map<String, List<Application__c>> appMap = new Map<String ,List<Application__c>>();
        Map<String, Account> lisAcct = new  Map<String, Account>();
        List<Account> acctToUpdate = new  List<Account>();
        List<Account> accountListToLoop = [Select Id, YearsinService__c, (Select Id FROM Applications__r LIMIT 1) from Account where Id=:accountIdSet];
        for(Account acc: accountListToLoop){
            lisAcct.put(acc.Id+'', acc);
        }       
        for(Account act : accountListToLoop ){
            if(setofYear.containskey(act.id)){
                act.YearsinService__c = setofYear.get(act.id).size();
                acctToUpdate.add(act);
                lisAcct.remove(act.Id+'');
            }
            else {
                act.YearsinService__c = 0;
                acctToUpdate.add(act);
            }
        }
        Database.upsert(acctToUpdate, false); 
    }
}

 
How do I assign a permission set on  newly created partner user?
 
public class AssignPermissionSet {
    
    public static void assignperm(List<user> userlist){
        Set<ID> usersId = new Set<Id>();
        Set<Id> contactIdsSet = new Set<Id>();
        List<PermissionSetAssignment> permissionSetList = new List<PermissionSetAssignment>();
        
        
        for (User u : [Select Id, Name, ProfileId FROM User Where Id IN : userlist]){ // Add fields as per your requirement...
            if(u.ProfileId == '00e360003429432'){
            PermissionSetAssignment psa = new PermissionSetAssignment (PermissionSetId = '0PS33609skjojsae', AssigneeId = u.Id);
            permissionSetList.add(psa);
                }
        }
        insert permissionSetList;
    }
}

 
I have this code wherein it seems that even when run into small bulk like 50 updating it causing apex cpu limit is there a way I can remove that cpu limit
 
public class depToAccount {
    public static void deptpAccountV1(List<Dependent__c> depmem) {
        Set<Id> accountIdSet = new Set<Id>();
        Set<Id> coverIdSet = new Set<Id>();
        Map<Id, List<Dependent__c>> atoDep = new Map<Id, List<Dependent__c>>();
        Map<Id, List<Dependent__c>> ctomeddep = new Map<Id, List<Dependent__c>>();
        Map<Id, List<Dependent__c>> cto19belowdep = new Map<Id, List<Dependent__c>>();
        Map<Id, List<Dependent__c>> ato19belowdep = new Map<Id, List<Dependent__c>>();
        Map<Id, List<Dependent__c>> cto20belowdep = new Map<Id, List<Dependent__c>>();
        Map<Id, List<Dependent__c>> ato20updep = new Map<Id, List<Dependent__c>>();//
        List<CampaignMember> cmList = new List<CampaignMember>();
        
        Map<Id, Account> accountToUpdateMap = new Map<Id, Account>();
        
        
        for(Dependent__c depm : depmem){
            if(depm.status__c == 'ACTIVE' && depm.Catg__c == 'Vision'){
                if(depm.Account__c != null){
                    accountIdSet.add(depm.Account__c);
                }
                if(depm.Cover__c != null){
                    coverIdSet.add(depm.Cover__c); 
                }
            }
        }
        
        List<Dependent__c> existingDependent = [SELECT Id, Account__c, Account__r.Name, Cover__c, Cover__r.Comply__c,Rel__c, status__c, Catg__c, Age_Today__c 
                                                            FROM Dependent__c 
                                                            WHERE ((Cover__c IN: coverIdSet AND Cover__c != null)
                                                                   OR (Account__c IN: accountIdSet AND Account__c != null))
                                                            AND status__c ='ACTIVE' AND Plan_Name__c != NULL aND Catg__c != NULL];
        for(Dependent__c depM : existingDependent){
            if(depM.Age_Today__c < 19){
                if(cto19belowdep.containsKey(depM.Cover__c)){
                    cto19belowdep.get(depM.Cover__c).add(depM);
                }
                else {
                    cto19belowdep.put(depM.Cover__c, new List<Dependent__c>{ depM });
                }
                
                if(ato19belowdep.containsKey(depM.Account__c)){
                    ato19belowdep.get(depM.Account__c).add(depM);
                }
                else {
                    ato19belowdep.put(depM.Account__c, new List<Dependent__c>{ depM });
                }
            }
            if(depM.Age_Today__c >= 19){
                if(cto20belowdep.containsKey(depM.Cover__c)){
                    cto20belowdep.get(depM.Cover__c).add(depM);
                }
                else {
                    cto20belowdep.put(depM.Cover__c, new List<Dependent__c>{ depM });
                }
                
                if(ato20updep.containsKey(depM.Account__c)){
                    ato20updep.get(depM.Account__c).add(depM);
                }
                else {
                    ato20updep.put(depM.Account__c, new List<Dependent__c>{ depM });
                }
            }
            if(depM.Catg__c == 'Vision'){
                if(ctomeddep.containsKey(depM.Cover__c)){
                    ctomeddep.get(depM.Cover__c).add(depM);
                }
                else {
                    ctomeddep.put(depM.Cover__c, new List<Dependent__c>{ depM });
                }
            }
            
            if(depM.Catg__c == 'Dental'){
                if(atoDep.containsKey(depM.Account__c)){
                    atoDep.get(depM.Account__c).add(depM);
                }
                else {
                    atoDep.put(depM.Account__c, new List<Dependent__c>{ depM });
                }
            }
        }
        Map<Id, Account> acctAttesAppMap = new Map<Id, Account>([Select ID,Good__c,Age_in_Numbers__pc,PersonContactId,Phone__c ,NumberofYears__c  FROM Account where ID IN : accountIdSet ]);
        
        for(Id acctId : accountIdSet){
            for(Dependent__c depM : existingDependent){
                for(Id covId : coverIdSet){
                    if(cto19belowdep.containsKey(covId) && depM.Cover__c==covId){ 
                        for(Dependent__c depU19 : cto19belowdep.get(covId)){
                            if(depU19.Age_Today__c < 19){ 
 
                                if((atoDep.containsKey(acctId)) || (acctAttesAppMap.get(acctId).Good__c == true) || (acctAttesAppMap.get(acctId ).NumberofYears__c > 0 )){ 
                                    if(ctomeddep.containsKey(covId)){
                                        for(Dependent__c depMemMedi : ctomeddep.get(covId)){ 
                                            accountToUpdateMap.put(depMemMedi.Account__c, new Account(Id=depMemMedi.Account__c, Compliant__c=true, Comply__c=false));
                                        }
                                    }
                                    
                                }
                                else {
                                    if((!atoDep.containsKey(acctId)) || (acctAttesAppMap.get(acctId).Good__c == false) || (acctAttesAppMap.get(acctId ).NumberofYears__c == 0 )){ 
                                        if(ctomeddep.containsKey(covId)){
                                            for(Dependent__c depMemMedi : ctomeddep.get(covId)){
                                                accountToUpdateMap.put(depMemMedi.Account__c, new Account(Id=depMemMedi.Account__c, Compliant__c=false, Comply__c=false));
                                            }
                                        }
                                        
                                    }
                                    IF(acctAttesAppMap.get(acctId).Phone__c != NULL ){
                                        {
                                           
                                            cmList.add( new CampaignMember(
                                                CampaignId  = System.Label.Doctor_Campaign,
                                                ContactId = acctAttesAppMap.get(acctId).PersonContactId,
                                                Status = 'Completed'
                                            ));

                                            
                                        }
                                    }
                                    IF(acctAttesAppMap.get(acctId).Phone__c == NULL && acctAttesAppMap.get(acctId).Age_in_Numbers__pc >= 19){
                                        {
                                            cmList.add( new CampaignMember(
                                                CampaignId  = System.Label.Nurse_Campaign,
                                                ContactId = acctAttesAppMap.get(acctId).PersonContactId,
                                                Status = 'Completed'
                                            ));
                                        }
                                    }
                                    IF(acctAttesAppMap.get(acctId).Phone__c == NULL &&  acctAttesAppMap.get(acctId).Age_in_Numbers__pc < 19){
                                        {
                                            cmList.add( new CampaignMember(
                                                CampaignId  = System.Label.Staff_Campaign,
                                                ContactId = acctAttesAppMap.get(acctId).PersonContactId,
                                                Status = 'Completed'
                                            ));
                                        }
                                    }
                                }
                            }
                            
                        }
                    else if(cto20belowdep.containsKey(covId) && depM.Cover__c==covId){
                        for(Dependent__c depU20 : cto20belowdep.get(covId)){
                            if(depU20.Age_Today__c >= 19){ 
                                if(atoDep.containsKey(acctId) ){
                                    if(ctomeddep.containsKey(covId)){
                                        for(Dependent__c depMemMedi : ctomeddep.get(covId)){
                                            accountToUpdateMap.put(depMemMedi.Account__c, new Account(Id=depMemMedi.Account__c, Compliant__c=false, Comply__c=true));
                                        }
                                    }
                                }
                            }
                            
                        }
                    }
                    if(depM.Cover__r.Comply__c==true && depM.Cover__c == covId){
                        if(ctomeddep.containsKey(covId)) 
                            for(Dependent__c CMmed : ctomeddep.get(covId)){
                                accountToUpdateMap.put(CMmed.Account__c, new Account(Id=CMmed.Account__c, Compliant__c=false, Comply__c=true));
                            }
                    } 
                    
                }
            }
        }
        database.insert(cmlist, false);
        update accountToUpdateMap.values();
        
    }
    
}

 
I tried to make an else statement but it seems i doesn't indentify when it has a size of 0
 
List<Task> taskCompletedOrInvalidPhone = [SELECT Id, whatid, CallCustom__c, RecordtypeId 
                                                  FROM Task 
                                                  WHERE Whatid IN :forWhatID 
                                                  AND CallCustom__c = 'Completed' AND WhatID != null];
        for(Task tsk : taskCompletedOrInvalidPhone){
            if(accountIdToListTaskCompletedMap.containsKey(tsk.WhatId)){
                accountIdToListTaskCompletedMap.get(tsk.WhatId).add(tsk);
            }
            else{
                accountIdToListTaskCompletedMap.put(tsk.WhatId, new List<Task>{tsk});
            }
        }


for(Id acctId : forWhatID){
            if(accountIdToListTaskCompletedMap.containsKey(acctId)){
                if(accountIdToListTaskCompletedMap.get(acctId).size() >0){
                    if(accountIdToListDepMap.containsKey(acctId)){
                        for(Dependent__c covMem : accountIdToListDepMap.get(acctId)){
                            if(coverageIdToListDepMap.containsKey(covMem.Coverage__c)){
                                for(Dependent__c depMem2 : coverageIdToListDepMap.get(covMem.Coverage__c)){
                                    accountsToUpdate.put(depMem2.Account__c, new Account(Id=depMem2.Account__c, Good__c=true, Verygood__c=true));
                                }
                            }
                        } 
                    } 
                }
            }
			else{
			if(accountIdToListTaskCompletedMap.containsKey(acctId)){
                if(accountIdToListTaskCompletedMap.get(acctId).size() == 0){
                    if(accountIdToListDepMap.containsKey(acctId)){
                        for(Dependent__c covMem : accountIdToListDepMap.get(acctId)){
                            if(coverageIdToListDepMap.containsKey(covMem.Coverage__c)){
                                for(Dependent__c depMem2 : coverageIdToListDepMap.get(covMem.Coverage__c)){
                                    accountsToUpdate.put(depMem2.Account__c, new Account(Id=depMem2.Account__c, Good__c=false, Verygood__c=false));
                                }
                            }
                        } 
                    } 
                }
            }
			}

 
how can I attain that if there is no task or specific task in will update a field in account, trigger should be account,
HI 

I am encountering and error while doing a data load.

here is my code when dataloading. is there anything that needs to be optimize in here so far?
 
public class depToAccount {
    public static void deptpAccountV1(List<Dependent__c> depmem) {
        Set<Id> accountIdSet = new Set<Id>();
        Set<Id> coverIdSet = new Set<Id>();
        Map<Id, List<Dependent__c>> atoDep = new Map<Id, List<Dependent__c>>();
        Map<Id, List<Dependent__c>> ctomeddep = new Map<Id, List<Dependent__c>>();
        Map<Id, List<Dependent__c>> cto19belowdep = new Map<Id, List<Dependent__c>>();
        Map<Id, List<Dependent__c>> ato19belowdep = new Map<Id, List<Dependent__c>>();
        Map<Id, List<Dependent__c>> cto20belowdep = new Map<Id, List<Dependent__c>>();
        Map<Id, List<Dependent__c>> ato20updep = new Map<Id, List<Dependent__c>>();//
        List<CampaignMember> cmList = new List<CampaignMember>();
        
        Map<Id, Account> accountToUpdateMap = new Map<Id, Account>();
        
        
        for(Dependent__c depm : depmem){
            if(depm.status__c == 'ACTIVE' && depm.Catg__c == 'Vision'){
                if(depm.Account__c != null){
                    accountIdSet.add(depm.Account__c);
                }
                if(depm.Cover__c != null){
                    coverIdSet.add(depm.Cover__c); 
                }
            }
        }
        
        List<Dependent__c> existingDependent = [SELECT Id, Account__c, Account__r.Name, Cover__c, Cover__r.Comply__c,Rel__c, status__c, Catg__c, Age_Today__c 
                                                            FROM Dependent__c 
                                                            WHERE ((Cover__c IN: coverIdSet AND Cover__c != null)
                                                                   OR (Account__c IN: accountIdSet AND Account__c != null))
                                                            AND status__c ='ACTIVE' AND Plan_Name__c != NULL aND Catg__c != NULL];
        for(Dependent__c depM : existingDependent){
            if(depM.Age_Today__c < 19){
                if(cto19belowdep.containsKey(depM.Cover__c)){
                    cto19belowdep.get(depM.Cover__c).add(depM);
                }
                else {
                    cto19belowdep.put(depM.Cover__c, new List<Dependent__c>{ depM });
                }
                
                if(ato19belowdep.containsKey(depM.Account__c)){
                    ato19belowdep.get(depM.Account__c).add(depM);
                }
                else {
                    ato19belowdep.put(depM.Account__c, new List<Dependent__c>{ depM });
                }
            }
            if(depM.Age_Today__c >= 19){
                if(cto20belowdep.containsKey(depM.Cover__c)){
                    cto20belowdep.get(depM.Cover__c).add(depM);
                }
                else {
                    cto20belowdep.put(depM.Cover__c, new List<Dependent__c>{ depM });
                }
                
                if(ato20updep.containsKey(depM.Account__c)){
                    ato20updep.get(depM.Account__c).add(depM);
                }
                else {
                    ato20updep.put(depM.Account__c, new List<Dependent__c>{ depM });
                }
            }
            if(depM.Catg__c == 'Vision'){
                if(ctomeddep.containsKey(depM.Cover__c)){
                    ctomeddep.get(depM.Cover__c).add(depM);
                }
                else {
                    ctomeddep.put(depM.Cover__c, new List<Dependent__c>{ depM });
                }
            }
            
            if(depM.Catg__c == 'Dental'){
                if(atoDep.containsKey(depM.Account__c)){
                    atoDep.get(depM.Account__c).add(depM);
                }
                else {
                    atoDep.put(depM.Account__c, new List<Dependent__c>{ depM });
                }
            }
        }
        Map<Id, Account> acctAttesAppMap = new Map<Id, Account>([Select ID,Good__c,Age_in_Numbers__pc,PersonContactId,Phone__c ,NumberofYears__c  FROM Account where ID IN : accountIdSet ]);
        
        for(Id acctId : accountIdSet){
            for(Dependent__c depM : existingDependent){
                for(Id covId : coverIdSet){
                    if(cto19belowdep.containsKey(covId) && depM.Cover__c==covId){ 
                        for(Dependent__c depU19 : cto19belowdep.get(covId)){
                            if(depU19.Age_Today__c < 19){ 
 
                                if((atoDep.containsKey(acctId)) || (acctAttesAppMap.get(acctId).Good__c == true) || (acctAttesAppMap.get(acctId ).NumberofYears__c > 0 )){ 
                                    if(ctomeddep.containsKey(covId)){
                                        for(Dependent__c depMemMedi : ctomeddep.get(covId)){ 
                                            accountToUpdateMap.put(depMemMedi.Account__c, new Account(Id=depMemMedi.Account__c, Compliant__c=true, Comply__c=false));
                                        }
                                    }
                                    
                                }
                                else {
                                    if((!atoDep.containsKey(acctId)) || (acctAttesAppMap.get(acctId).Good__c == false) || (acctAttesAppMap.get(acctId ).NumberofYears__c == 0 )){ 
                                        if(ctomeddep.containsKey(covId)){
                                            for(Dependent__c depMemMedi : ctomeddep.get(covId)){
                                                accountToUpdateMap.put(depMemMedi.Account__c, new Account(Id=depMemMedi.Account__c, Compliant__c=false, Comply__c=false));
                                            }
                                        }
                                        
                                    }
                                    IF(acctAttesAppMap.get(acctId).Phone__c != NULL ){
                                        {
                                           
                                            cmList.add( new CampaignMember(
                                                CampaignId  = System.Label.Doctor_Campaign,
                                                ContactId = acctAttesAppMap.get(acctId).PersonContactId,
                                                Status = 'Completed'
                                            ));

                                            
                                        }
                                    }
                                    IF(acctAttesAppMap.get(acctId).Phone__c == NULL && acctAttesAppMap.get(acctId).Age_in_Numbers__pc >= 19){
                                        {
                                            cmList.add( new CampaignMember(
                                                CampaignId  = System.Label.Nurse_Campaign,
                                                ContactId = acctAttesAppMap.get(acctId).PersonContactId,
                                                Status = 'Completed'
                                            ));
                                        }
                                    }
                                    IF(acctAttesAppMap.get(acctId).Phone__c == NULL &&  acctAttesAppMap.get(acctId).Age_in_Numbers__pc < 19){
                                        {
                                            cmList.add( new CampaignMember(
                                                CampaignId  = System.Label.Staff_Campaign,
                                                ContactId = acctAttesAppMap.get(acctId).PersonContactId,
                                                Status = 'Completed'
                                            ));
                                        }
                                    }
                                }
                            }
                            
                        }
                    else if(cto20belowdep.containsKey(covId) && depM.Cover__c==covId){
                        for(Dependent__c depU20 : cto20belowdep.get(covId)){
                            if(depU20.Age_Today__c >= 19){ 
                                if(atoDep.containsKey(acctId) ){
                                    if(ctomeddep.containsKey(covId)){
                                        for(Dependent__c depMemMedi : ctomeddep.get(covId)){
                                            accountToUpdateMap.put(depMemMedi.Account__c, new Account(Id=depMemMedi.Account__c, Compliant__c=false, Comply__c=true));
                                        }
                                    }
                                }
                            }
                            
                        }
                    }
                    if(depM.Cover__r.Comply__c==true && depM.Cover__c == covId){
                        if(ctomeddep.containsKey(covId)) 
                            for(Dependent__c CMmed : ctomeddep.get(covId)){
                                accountToUpdateMap.put(CMmed.Account__c, new Account(Id=CMmed.Account__c, Compliant__c=false, Comply__c=true));
                            }
                    } 
                    
                }
            }
        }
        database.insert(cmlist, false);
        update accountToUpdateMap.values();
        
    }
    
}

 
Hi

I am getting this issue to many soql, is there something wrong with my code when try to save a record this error appers that too many soql
public class AccountTask {
    
    
    
    public static void accountTaskCopy(List<Account> acclist){
        Id EmailRT = SObjectType.Task.getRecordTypeInfosByDeveloperName().get('Email').getRecordTypeId();
        Id CallRT = SObjectType.Task.getRecordTypeInfosByDeveloperName().get('Call').getRecordTypeId(); 
        
        Set<Id> forWhatID = new Set<Id>();
        Set<Id> accID = new Set<Id>();
        Set<Id> coverageIds = new Set<Id>();
        Map<ID, List<CM__c>> accountIdToListCMOMap = new Map<Id, List<CM__c>>(); 
        Map<ID, List<CM__c>> coverageIdToListCVMMap = new Map<Id, List<CM__c>>();
        Map<ID, List<Task>> accountIdToListTaskCompletedMap = new Map<Id, List<Task>>();
        Map<ID, List<Task>> accountIdToListTaskNotCompletedMap = new Map<Id, List<Task>>();
        Map<Id, Account> accountsToUpdate = new Map<Id, Account>();
       
        for(Account acc: acclist){
            {
            accID.add(acc.ID);
            }
       }

        
        for(Task tsk : [SELECT ID,whatid FROM TASK where WHATID IN : accID]){
            if(tsk.WhatID != Null && tsk.WhatID.getSObjectType() == Account.SobjectType){
                forWhatID.add(tsk.WhatId);
                System.debug('forWhatID' + forWhatID);
            }
        }
         
        List<CM__c> existingCMs = [SELECT Id, Account__c, Account__r.Name, CVR__c, Coverage__r.Good__c,rel__c, status__c, BusinessType__c, Age_Today__c 
                                                            FROM CM__c 
                                                            WHERE (CVR__c != null AND Account__c IN: forWhatID AND Account__c != null) AND status__c ='ACTIVE' AND BusinessType__c = 'Medical'];
        
        for(CM__c cMo : existingCMs){
            if(accountIdToListCMOMap.containsKey(cMo.Account__c)){
                accountIdToListCMOMap.get(cMo.Account__c).add(cMo);
            }
            else{
                accountIdToListCMOMap.put(cMo.Account__c, new List<CM__c>{cMo});
            }
            
            if(coverageIdToListCVMMap.containsKey(cMo.CVR__c)){
                coverageIdToListCVMMap.get(cMo.CVR__c).add(cMo);
            }
            else{
                coverageIdToListCVMMap.put(cMo.CVR__c, new List<CM__c>{cMo});
            }
            
            coverageIds.add(cMo.CVR__c);
        }
        
        List<CM__c> existingCMFromCov = [SELECT Id, Account__c, Account__r.Name, CVR__c, Coverage__r.Good__c,rel__c, status__c, BusinessType__c, Age_Today__c 
                                                                   FROM CM__c 
                                                                   WHERE (CVR__c != null AND CVR__c IN: coverageIds AND Account__c != null) AND status__c ='ACTIVE' AND BusinessType__c = 'Medical'];
        for(CM__c cMo : existingCMFromCov){
            if(coverageIdToListCVMMap.containsKey(cMo.CVR__c)){
                coverageIdToListCVMMap.get(cMo.CVR__c).add(cMo);
            }
            else{
                coverageIdToListCVMMap.put(cMo.CVR__c, new List<CM__c>{cMo});
            }
        }
        System.debug('accountIdToListCMOMap ' + accountIdToListCMOMap);
        System.debug('coverageIdToListCVMMap ' + coverageIdToListCVMMap);
        
        
        List<Task> taskCompletedOrInvalidPhone = [SELECT Id, whatid, CallCustom__c, RecordtypeId 
                                                  FROM Task 
                                                  WHERE Whatid IN :forWhatID 
                                                  AND (CallCustom__c = 'Completed Campaign Requirements' OR CallCustom__c = 'Invalid Phone') AND WhatID != null];
        for(Task tsk : taskCompletedOrInvalidPhone){
            if(accountIdToListTaskCompletedMap.containsKey(tsk.WhatId)){
                accountIdToListTaskCompletedMap.get(tsk.WhatId).add(tsk);
            }
            else{
                accountIdToListTaskCompletedMap.put(tsk.WhatId, new List<Task>{tsk});
            }
        }
        
        List<Task> taskNotCompleteCampaign = [SELECT Id, whatid,CallCustom__c, RecordtypeId  FROM Task WHERE Whatid IN :forWhatID AND RecordTypeID =: CallRT AND (CallCustom__c = 'Left Message' OR  CallCustom__c = 'Unable to Reach') AND WhatID != null ];
        for(Task tsk : taskNotCompleteCampaign){
            if(accountIdToListTaskNotCompletedMap.containsKey(tsk.WhatId)){
                accountIdToListTaskNotCompletedMap.get(tsk.WhatId).add(tsk);
            }
            else{
                accountIdToListTaskNotCompletedMap.put(tsk.WhatId, new List<Task>{tsk});
            }
        }
        
        System.debug('accountIdToListTaskCompletedMap ' + accountIdToListTaskCompletedMap);
        System.debug('accountIdToListTaskNotCompletedMap ' + accountIdToListTaskNotCompletedMap);
        
        for(Id acctId : forWhatID){
            System.debug('acctId ' + acctId);
            if(accountIdToListTaskCompletedMap.containsKey(acctId)){
            system.debug('acctIdlist' + accountIdToListTaskCompletedMap);
                if(accountIdToListCMOMap.containsKey(acctId)){
                    for(CM__c cMo : accountIdToListCMOMap.get(acctId)){
                        System.debug('cMo ' + cMo);
                        if(coverageIdToListCVMMap.containsKey(cMo.CVR__c)){
                            for(CM__c covMem2 : coverageIdToListCVMMap.get(cMo.CVR__c)){
                                System.debug('covMem2 ' + covMem2);
                                accountsToUpdate.put(covMem2.Account__c, new Account(Id=covMem2.Account__c, PDC__c=true));
                            }
                        }
                        
                    } 
                } 
            }
        
        }
        
        System.debug('accountsToUpdate ' + accountsToUpdate);
        update accountsToUpdate.values();
        
    }
}

 
HI 

I am trying to parse this 

<advertisers type="array">
  <advertiser>
    <id type="integer">7</id>
    <name>ABC Telecom</name>
  </advertiser>
  <advertiser>
    <id type="integer">106</id>
    <name>ABC_Ozone</name>
  </advertiser><advertiser>
    <id type="integer">13</id>
    <name>Acme Corp</name>
  </advertiser>
</advertisers>


with this code
 
public with sharing class xmltosobject{
    public string s='';
    public void readxml(ID TestObjectID){
        XMLParsing__c TObj = [SELECT xml__c FROM XMLParsing__c where id= : TestObjectID];
        s= TObj.Event_Message_XML__c ;
        List<ParsedXML__c> newaccounts = new List<ParsedXML__c> ();
        
        Dom.Document docx = new Dom.Document();
        docx.load(s);
        dom.XmlNode xroot = docx.getrootelement() ;
        
        dom.XmlNode [] xrec = xroot.getchildelements() ; //Get all Record Elements
        
        for(Dom.XMLNode child : xrec) //Loop Through Records
        {
            ParsedXML__c a = new ParsedXML__c();
            
            for (dom.XmlNode awr : child.getchildren() ) {
                if (awr.getname() == 'id') {
                    system.debug('Id' + awr.gettext());
                    a.accountnumber__c = awr.gettext();
                }  
                
                if (awr.getname() == 'name') {
                    system.debug('name' + awr.gettext());
                    a.name__c = awr.gettext();
                }  
                
                
            }
            newaccounts.add(a);
        }
        system.debug(newaccounts);//you could insert here or upsert based on ID with an external Id field
    }
}


I got an invalid type when running this in execute anonymous
 
String str = '<advertisers type="array"><advertiser><id type="integer">7</id><name>ABC Telecom</name></advertiser><advertiser><id type="integer">106</id><name>ABC_Ozone</name></advertiser><advertiser><id type="integer">13</id><name>Acme Corp</name></advertiser></advertisers>';
xmltosobject.readxml objPartnerCreds = new xmltosobject.readxml();
system.debug(objPartnerCreds);


 
I have this Custom Object Named Stored XML.

and one of the field stores an XML strings.

<?xml version="1.0" encoding="UTF-8"?><consumers xmlns="http://test.com/feed/">
<SupplyResult>
 <MarketId>xxxxxxxx</MarketId>
 <SupplyList>
    <member>
        <Quantity>9</Quantity>
        <InStock>5</InStock>
        <SellerSKU>Test- 1111</SellerSKU>
    </member>
  </SupplyList>
  </SupplyResult>


How do I parse this and store all the field on on a new Custom Object Named XML Parsed?

Thank you!
How do i fix this issue?

({
    doInit : function(component,event,helper){
        var action = component.get("c.UserCheck");
        action.setParams({
            "currentRecordId" : component.get("v.recordId"),
            "currentUserId" : $A.get("$SObjectType.CurrentUser.Id")
        });
        action.setCallback(this,function(response){
            if(response.getState() == "SUCCESS"){
                //alert("hello there!" + response.getReturnValue()); 
                console.log(response.getReturnValue());
                if(response.getReturnValue()==true){
                    document.getElementById("Modal").setAttribute("style","height:640px;display:block;");
                    console.log(response.getReturnValue());
                }
                else{
                     document.getElementById("Modal").setAttribute("style","height:640px;display:none;");
                }
            }
        })
        $A.enqueueAction(action);
        
          var action2 = component.get("c.getAccount");
         action2.setParams({
            "currentRecordId" : component.get("v.recordId")
        });
        action2.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
               // alert("hello there!" + response.getReturnValue());
                component.set("v.account", response.getReturnValue());
                console.log(response.getReturnValue());
                /*if(response.getReturnValue()==true){
                    document.getElementById("Modal").setAttribute("style","height:640px;display:block;");
                    console.log(response.getReturnValue());
                }
                else{
                     document.getElementById("Modal_Parent").setAttribute("style","height:640px;display:none;");
                }*/
            }
         });
         $A.enqueueAction(action2); 
    
    },

 
I am experiencing DML Error 10001 ,

can you spot on which is needed to be optimize more in here.


public with sharing class UpdateStatus {
    public static final String ClsName  = 'UpdateStatus';
    public static boolean isExecuting=false;
    public static boolean isInvoked = false;
    public static boolean isCnclGSChkd = false;
    public static final String UpdateActiveStatus  = 'ActiveStatus' ;
    public static final String UpdateCancelStatus  = 'CancelStatus' ;
    public static final String UpdateRecType = 'RecTypeStat' ;
    public static final String UpdateCancelBff = 'CancelStats';
    public static final String  UpdateEndDate = 'UpdateEndDate';
    public static final string acctClient =Schema.SObjectType.Account.getRecordTypeInfosByName().get('Account - Client').getRecordTypeId();
    public static final string acctClientInt =  Schema.SObjectType.Account.getRecordTypeInfosByName().get('Account - InactiveClient').getRecordTypeId();
    public static final String  actv='Active';
    public static final String  cancl='Canceled';
    public static final String pendng =  'Pending';
    public static final String  accntCst= 'Account_Client';
    public static final String  cncled= 'Canceled';
    public static final String  inactv= 'Inactive';
    public static final Date enddateFuture = Date.newInstance(2100, 12, 31);
    public static  List<Id> cnclgmList = new List<Id>();
    public static final string profIntUser='Integration User';
    public static final string categNet='Verizon';
    

    public static void ActiveStatus(List<Group_Members> gmList)
    {

            Date EndDateFr;
            map<id,integer> prcOpn=new map<id,integer>();
            list<id> gpToProc=new list<id>();
            String profileName = [Select Name from Profile where Id = :UserInfo.getProfileId() limit 1].Name;
            for(Group_Members objGM : gmList){
                
                if(objGM.Status__c==pendng ){
                    gpToProc.add(objGM.Id);
                }
            }
            
            list<aggregateResult> PrcssLst=[select GM_ID,count(Id) OpenGM from WF_GM__c where GM_ID in:gpToProc 
                                              and (GA_Status__c='Closed') and GM_NS__c=null and GM_Sid__c !=null  group by GM_ID  limit 2000];
            for(aggregateResult agRst:PrcssLst)
            {
                prcOpn.put(string.valueof(agRst.get('GM_ID')),integer.valueof(agRst.get('OpenGM')));   
            }
            
            for(Group_Members objGM : gmList){
                if(objGM.EffDate__c<=system.today() && 
                   objGM.cancelDate__c==null){
                       EndDateFr = enddateFuture;
                   }
                else{
                    EndDateFr = objGM.cancelDate__c;
                }
                if(objGM.Status__c==pendng  && objGM.Network__c==categNet){
                    if(prcOpn.get(objGM.Id)>0)
                        objGM.Status__c=actv;
                }
                if(objGM.Status__c==pendng  && (objGM.Trans__c || objGM.Post__c)){
                    if(prcOpn.get(objGM.Id)>0)
                        objGM.Status__c=actv;
                }  
                if(profileName==profIntUser){
                    if(objGM.Status__c==cncled && EndDateFr>system.today() 
                       && objGM.EffDate__c<=system.today())
                    {
                        objGM.Status__c=actv;
                    }   
                }  
            }

    }

    public static void RecTypeStat(List<Group_Members> gmList)
    {
            set<id> accIds=new set<id>();
            Date gmEndDateFr;
            boolean isChnge=false;
            String profileName = [Select Name from Profile where Id = :UserInfo.getProfileId() limit 1].Name;
            Map<Id, Date> gmACCMap = new Map<Id, Date>();
            for(Group_Members objGM : gmList){
                gmACCMap.put(objGM.Account_c,objGM.EffDate__c);
                if(objGM.Status__c==actv && objGM.Network__c==categNet)
                {
                    accIds.add(objGM.Account_c);
                }
                if(objGM.Status__c==actv && (objGM.Trans__c || objGM.Post__c))
                {
                    accIds.add(objGM.Account_c);
                }
                
                if(profileName==profIntUser){
                    if(objGM.Status__c==cncled && gmEndDateFr>system.today() 
                       && objGM.EffDate__c<=system.today())
                    {
                        accIds.add(objGM.Account_c);
                    }
                }
                
            } 
            List<Account>  accLst =[Select id,RecordType.DeveloperName from Account WHERE ID IN :accIds Limit 50000] ;
            List<Account>  updtAccLst = New   List<Account>();
            
            if(!accIds.isEmpty()){
                for(Account objAcc : accLst){
                    if(objAcc.RecordType.DeveloperName != accntCst){
                        objAcc.RecordTypeId = acctClient;
                        objAcc.Account_Status__c=actv;
                        objAcc.CovCancelDate__c=null;
                        objAcc.EnrollDate__c = gmACCMap.get(objAcc.Id);
                        updtAccLst.add(objAcc);
                    }
                }
            }  
            
            if(!updtAccLst.isEmpty()){
                Database.update(updtAccLst);
            }
            isInvoked= true; 
        }
        
    }

    public static void CancelStats(List<Group_Members> grpmemList,map<id,Group_Members> grpmemListOld)
    {
            for(Group_Members grp:grpmemList)
            {
                boolean CnclChk=false;
                boolean CnclDteChk=false;
                if(grpmemListOld!=null)
                {
                    Group_Members grpOld=grpmemListOld.get(grp.Id);  
                    if(grp.cancelDate__c <> grpOld.cancelDate__c)
                        CnclChk=true;
                    if((grp.Status__c <> grpOld.Status__c) && grp.Status__c==cancl)
                    {
                        CnclDteChk=true;
                    }
                }
                else
                {
                    CnclChk=true;
                    if(grp.Status__c==cancl)
                    {
                        CnclDteChk=true; 
                    }
                }
                
                if(grp.cancelDate__c<=system.today() && CnclChk)
                {
                    grp.Status__c=cancl;
                    cnclgmList.add(grp.Id);
                    
                }
            }
            isCnclGSChkd = true;
        }
        
    }

    public static void CancelStatus(List<Group_Members> grpmemList,Map<ID,Group_Members> grpOldMap)
    {
            set<id> cnclAccIdsToPrcss=new set<id>();
            boolean isChnge=false;
            for(Group_Members grp:grpmemList)
            {
                if(grpOldMap !=null)
                {
                    Group_Members grpOld=grpOldMap.get(grp.Id);
                    if(grpOld.cancelDate__c !=grp.cancelDate__c  
                       || grpOld.Status__c !=grp.Status__c){
                           isChnge=true;     
                       }
                }
                
                else
                {
                    isChnge=true;
                }
                if(grp.cancelDate__c<=system.today() && isChnge)
                {
                    cnclAccIdsToPrcss.add(grp.Account_c);
                }
            }

            if(cnclAccIdsToPrcss.size() > 0){
                
                List<Account> accLst = [Select Id,Account_Status__c,RecordType.DeveloperName ,CovCancelDate__c,
                                        (select Status__c,cancelDate__c from Group_Member__r ORDER BY LastModifiedDate ASC)
                                        from Account where id in:cnclAccIdsToPrcss Limit 50000];
                List<Account>  acntIdsToPrcs = new List<Account>();
                List<Account>  finalacntIdsToPrcs = new List<Account>();
                Set<Id> processAccIds = New Set<Id>();
                boolean flag = false;
                Set<Id> accActv = New Set<Id> ();
                
                for(Account objAcc :accLst){
                    
                    if(!objAcc.Group_Member__r.isEmpty()){
                        for(Group_Members objGM : objAcc.Group_Member__r){
                            if(objGM.Status__c.equals(actv)){
                                flag = true;   
                                accActv.add(objAcc.id);
                                break;
                            }
                            else{
                                if(cnclgmList.contains(objGM.Id) && !processAccIds.contains(objAcc.id)  ){
                                    objAcc.CovCancelDate__c=objGM.cancelDate__c;
                                    objAcc.RecordTypeId =acctClientInt;
                                    objAcc.Account_Status__c=inactv;
                                    objAcc.EnrollDate__c=null;
                                    acntIdsToPrcs.add(objAcc); 
                                    processAccIds.add(objAcc.id);
                                }
                            }
                        }
                    }
                } 

                if(accActv.size() > 0){
                    processAccIds.removeAll(accActv);
                }

                for(Account accCus : acntIdsToPrcs){
                    if(processAccIds.contains(accCus.id)){
                        finalacntIdsToPrcs.add(accCus);
                    }
                }
                
                if(finalacntIdsToPrcs.size()>0 ){
                    
                    Database.update(acntIdsToPrcs);
                }
                
            }
            
            isExecuting=true;
      
    }
  
    public static void UpdateEndDate(List<Group_Members> grpmemList,map<id,Group_Members> grpmemListOld){
            List<id> gsIdLst = new List<id>();
            List<History__c> TCList = new List<History__c>(); 
            for(Group_Members grp:grpmemList)
            {
                if(grpmemListOld!=null)
                {
                    Group_Members grpOld=grpmemListOld.get(grp.Id);
                    
                    if(grp.History__c <> grpOld.History__c){
                        gsIdLst.add(grpOld.History__c);
                        
                    }
                } 
            }
            if(!gsIdLst.isEmpty()){
                for(History__c tp : [select id,EndDateTC__c,GA_TPB_Start_Date__c from History__c
                                                           where ID IN : gsIdLst Limit 50000]){
                                                               tp.EndDateTC__c = system.today()-1;
                                                               TCList.add(tp);                                                      
                                                           }
                Database.update(TCList);
            }
        }   
        
    }
}

 
Hi can you revise my code if it is not correct wherein I want to update all case records wherein I will unlock all of them. I tested one record and its updating but I think when its all or bulk its not updating.
 
global class UnlockRecordBatchJob implements Database.batchable<sObject> {
    //Start of this batch job
    global Database.QueryLocator start(Database.BatchableContext BC) {
        String query = 'SELECT Id from Case Limit 2';
        return Database.getQueryLocator(query);
    }
    //Exeution of batch job
    global void execute(Database.BatchableContext BC, List<Case> scope) {
        List<Case> caseList = [SELECT Id From CaseLimit 2];
        //Check locked records
        List<Case> caseLockList = new List<Case>();
        for(Case c : caseList)
        {
            if(Approval.isLocked(c.id)){
                caseLockList.add(c);
            }
        }
        
        if(!caseLockList.isEmpty()){
            //Unlock records
            List<Approval.UnlockResult> ulrList = Approval.unlock(caseLockList, false);
            
            // Iterate through each returned result
            for(Approval.UnlockResult  ulr : ulrList) {
                if (ulr.isSuccess()) {
                    //Operation was successful, so get the ID of the record that was processed
                    System.debug('Successfully locked account with ID: ' + ulr.getId());
                }
                else {
                    //Operation failed, so get all errors                
                    for(Database.Error err : ulr.getErrors()) {
                        System.debug('The following error has occurred.');                    
                        System.debug(err.getStatusCode() + ': ' + err.getMessage());
                        System.debug('Case fields that affected this error: ' + err.getFields());
                    }
                }
            }
        }
    }
    //finish job
    global void finish(Database.BatchableContext BC) {
    }
}

 
global class ChangingCapsLock{
    global static void Change( Account [] acc){
        for(Account a :acc){
            
            if(a.BillingPostalCode !=null )
                a.BillingPostalCode = allUpper(a.BillingPostalCode);
            
            if(a.BillingCountry !=null )
                a.BillingCountry= formatToUpper(a.BillingCountry);
            a.BillingCountry= formatToUpperLower(a.BillingCountry);
            
            if(a.BillingCountry ==null )
           String.isEmpty(a.BillingCountry);
            
            if(a.ShippingPostalCode !=null )
                a.ShippingPostalCode = allUpper(a.ShippingPostalCode);
            
            if(a.ShippingCountry !=null )
                a.ShippingCountry= formatToUpper(a.ShippingCountry);
            a.ShippingCountry= formatToUpperLower(a.ShippingCountry);
            
        }
    }
    public static String formatToUpper (String Str) {
        String result = '';
        for (String iter : Str.split('[ ]+')) {
            if (iter != null  && iter != '') {
                if (iter.length() > 1) {
                    result += iter.substring(0,1).toUpperCase() + iter.substring(1,iter.length()) + ' ';
                }
                else
                    result += iter.substring(0,1).toUpperCase() + ' ';
            }
        }
        return result;
    }
    public static String allUpper (String Str) {
        String result = '';
        for (String iter : Str.split('[ ]+')) {
            if (iter != null && iter != '') {
                if (iter.length() > 1) {
                    result += iter.substring(0,1).toUpperCase() + iter.substring(1,iter.length()).toUpperCase() + ' ';
                }
                else
                    result += iter.substring(0,1).toUpperCase() + ' ';
            }
        }
        return result;
    }
    public static String formatToUpperLower (String Str) {
        String result = '';
        for (String iter : Str.split('[ ]+')) {
            if (iter != null && iter != '') {
                if (iter.length() > 1) {
                    result += iter.substring(0,1).toUpperCase() + iter.substring(1,iter.length()).toLowerCase() + ' ';
                }
                else
                    result += iter.substring(0,1).toLowercase() + ' ';
            }
        }
        return result;
    }
}
 
trigger AccountChangerFirstLetter on Account (before insert, before update) {
 ChangingCapsLock.Change(trigger.new);
      if(trigger.isBefore )
         if(trigger.IsInsert ||trigger.IsUpdate )
           ChangingCapsLock.Change(trigger.new);    
}

 
How to call this apex class to make it a batch job?
 
public class ApplicationYearsinService{

    public static void YearsinService(List<Application__c> appList){
        //Declares the Variables, List, ID to be used
        Date dat = System.today();
        Integer yr = dat.year();   
        Map<Id, Set<Integer>> setofYear = new Map<Id, Set<Integer>>();
        Set<Id> accountIdSet = new set<Id>();
        
        //Gets the values of the Account(Account__c from the Application
        for(Application__c cs: appList ){
            accountIdSet.add(cs.Account__c);            
        }
        
        //Query in the Application to get the value from the Account
        for(Application__c p : [SELECT ID, Account__c, Received_Date__c from Application__c where Account__c IN : accountIdSet ]){
            if(p.Received_Date__c != null){
                if(setofYear.containskey(p.Account__c)){
                    if(p.Received_Date__c != NULL) {
                        setofYear.get(p.Account__c).add(p.Received_Date__c.Year());
                    }
                }
                else {
                    setofYear.put(p.Account__c, new Set<Integer>{p.Received_Date__c.Year()});
                }     
            }
        }
        
        Map<String, List<Application__c>> appMap = new Map<String ,List<Application__c>>();
        Map<String, Account> lisAcct = new  Map<String, Account>();
        List<Account> acctToUpdate = new  List<Account>();
        List<Account> accountListToLoop = [Select Id, YearsinService__c, (Select Id FROM Applications__r LIMIT 1) from Account where Id=:accountIdSet];
        for(Account acc: accountListToLoop){
            lisAcct.put(acc.Id+'', acc);
        }       
        for(Account act : accountListToLoop ){
            if(setofYear.containskey(act.id)){
                act.YearsinService__c = setofYear.get(act.id).size();
                acctToUpdate.add(act);
                lisAcct.remove(act.Id+'');
            }
            else {
                act.YearsinService__c = 0;
                acctToUpdate.add(act);
            }
        }
        Database.upsert(acctToUpdate, false); 
    }
}

 
How do I assign a permission set on  newly created partner user?
 
public class AssignPermissionSet {
    
    public static void assignperm(List<user> userlist){
        Set<ID> usersId = new Set<Id>();
        Set<Id> contactIdsSet = new Set<Id>();
        List<PermissionSetAssignment> permissionSetList = new List<PermissionSetAssignment>();
        
        
        for (User u : [Select Id, Name, ProfileId FROM User Where Id IN : userlist]){ // Add fields as per your requirement...
            if(u.ProfileId == '00e360003429432'){
            PermissionSetAssignment psa = new PermissionSetAssignment (PermissionSetId = '0PS33609skjojsae', AssigneeId = u.Id);
            permissionSetList.add(psa);
                }
        }
        insert permissionSetList;
    }
}

 
HI 

I am encountering and error while doing a data load.

here is my code when dataloading. is there anything that needs to be optimize in here so far?
 
public class depToAccount {
    public static void deptpAccountV1(List<Dependent__c> depmem) {
        Set<Id> accountIdSet = new Set<Id>();
        Set<Id> coverIdSet = new Set<Id>();
        Map<Id, List<Dependent__c>> atoDep = new Map<Id, List<Dependent__c>>();
        Map<Id, List<Dependent__c>> ctomeddep = new Map<Id, List<Dependent__c>>();
        Map<Id, List<Dependent__c>> cto19belowdep = new Map<Id, List<Dependent__c>>();
        Map<Id, List<Dependent__c>> ato19belowdep = new Map<Id, List<Dependent__c>>();
        Map<Id, List<Dependent__c>> cto20belowdep = new Map<Id, List<Dependent__c>>();
        Map<Id, List<Dependent__c>> ato20updep = new Map<Id, List<Dependent__c>>();//
        List<CampaignMember> cmList = new List<CampaignMember>();
        
        Map<Id, Account> accountToUpdateMap = new Map<Id, Account>();
        
        
        for(Dependent__c depm : depmem){
            if(depm.status__c == 'ACTIVE' && depm.Catg__c == 'Vision'){
                if(depm.Account__c != null){
                    accountIdSet.add(depm.Account__c);
                }
                if(depm.Cover__c != null){
                    coverIdSet.add(depm.Cover__c); 
                }
            }
        }
        
        List<Dependent__c> existingDependent = [SELECT Id, Account__c, Account__r.Name, Cover__c, Cover__r.Comply__c,Rel__c, status__c, Catg__c, Age_Today__c 
                                                            FROM Dependent__c 
                                                            WHERE ((Cover__c IN: coverIdSet AND Cover__c != null)
                                                                   OR (Account__c IN: accountIdSet AND Account__c != null))
                                                            AND status__c ='ACTIVE' AND Plan_Name__c != NULL aND Catg__c != NULL];
        for(Dependent__c depM : existingDependent){
            if(depM.Age_Today__c < 19){
                if(cto19belowdep.containsKey(depM.Cover__c)){
                    cto19belowdep.get(depM.Cover__c).add(depM);
                }
                else {
                    cto19belowdep.put(depM.Cover__c, new List<Dependent__c>{ depM });
                }
                
                if(ato19belowdep.containsKey(depM.Account__c)){
                    ato19belowdep.get(depM.Account__c).add(depM);
                }
                else {
                    ato19belowdep.put(depM.Account__c, new List<Dependent__c>{ depM });
                }
            }
            if(depM.Age_Today__c >= 19){
                if(cto20belowdep.containsKey(depM.Cover__c)){
                    cto20belowdep.get(depM.Cover__c).add(depM);
                }
                else {
                    cto20belowdep.put(depM.Cover__c, new List<Dependent__c>{ depM });
                }
                
                if(ato20updep.containsKey(depM.Account__c)){
                    ato20updep.get(depM.Account__c).add(depM);
                }
                else {
                    ato20updep.put(depM.Account__c, new List<Dependent__c>{ depM });
                }
            }
            if(depM.Catg__c == 'Vision'){
                if(ctomeddep.containsKey(depM.Cover__c)){
                    ctomeddep.get(depM.Cover__c).add(depM);
                }
                else {
                    ctomeddep.put(depM.Cover__c, new List<Dependent__c>{ depM });
                }
            }
            
            if(depM.Catg__c == 'Dental'){
                if(atoDep.containsKey(depM.Account__c)){
                    atoDep.get(depM.Account__c).add(depM);
                }
                else {
                    atoDep.put(depM.Account__c, new List<Dependent__c>{ depM });
                }
            }
        }
        Map<Id, Account> acctAttesAppMap = new Map<Id, Account>([Select ID,Good__c,Age_in_Numbers__pc,PersonContactId,Phone__c ,NumberofYears__c  FROM Account where ID IN : accountIdSet ]);
        
        for(Id acctId : accountIdSet){
            for(Dependent__c depM : existingDependent){
                for(Id covId : coverIdSet){
                    if(cto19belowdep.containsKey(covId) && depM.Cover__c==covId){ 
                        for(Dependent__c depU19 : cto19belowdep.get(covId)){
                            if(depU19.Age_Today__c < 19){ 
 
                                if((atoDep.containsKey(acctId)) || (acctAttesAppMap.get(acctId).Good__c == true) || (acctAttesAppMap.get(acctId ).NumberofYears__c > 0 )){ 
                                    if(ctomeddep.containsKey(covId)){
                                        for(Dependent__c depMemMedi : ctomeddep.get(covId)){ 
                                            accountToUpdateMap.put(depMemMedi.Account__c, new Account(Id=depMemMedi.Account__c, Compliant__c=true, Comply__c=false));
                                        }
                                    }
                                    
                                }
                                else {
                                    if((!atoDep.containsKey(acctId)) || (acctAttesAppMap.get(acctId).Good__c == false) || (acctAttesAppMap.get(acctId ).NumberofYears__c == 0 )){ 
                                        if(ctomeddep.containsKey(covId)){
                                            for(Dependent__c depMemMedi : ctomeddep.get(covId)){
                                                accountToUpdateMap.put(depMemMedi.Account__c, new Account(Id=depMemMedi.Account__c, Compliant__c=false, Comply__c=false));
                                            }
                                        }
                                        
                                    }
                                    IF(acctAttesAppMap.get(acctId).Phone__c != NULL ){
                                        {
                                           
                                            cmList.add( new CampaignMember(
                                                CampaignId  = System.Label.Doctor_Campaign,
                                                ContactId = acctAttesAppMap.get(acctId).PersonContactId,
                                                Status = 'Completed'
                                            ));

                                            
                                        }
                                    }
                                    IF(acctAttesAppMap.get(acctId).Phone__c == NULL && acctAttesAppMap.get(acctId).Age_in_Numbers__pc >= 19){
                                        {
                                            cmList.add( new CampaignMember(
                                                CampaignId  = System.Label.Nurse_Campaign,
                                                ContactId = acctAttesAppMap.get(acctId).PersonContactId,
                                                Status = 'Completed'
                                            ));
                                        }
                                    }
                                    IF(acctAttesAppMap.get(acctId).Phone__c == NULL &&  acctAttesAppMap.get(acctId).Age_in_Numbers__pc < 19){
                                        {
                                            cmList.add( new CampaignMember(
                                                CampaignId  = System.Label.Staff_Campaign,
                                                ContactId = acctAttesAppMap.get(acctId).PersonContactId,
                                                Status = 'Completed'
                                            ));
                                        }
                                    }
                                }
                            }
                            
                        }
                    else if(cto20belowdep.containsKey(covId) && depM.Cover__c==covId){
                        for(Dependent__c depU20 : cto20belowdep.get(covId)){
                            if(depU20.Age_Today__c >= 19){ 
                                if(atoDep.containsKey(acctId) ){
                                    if(ctomeddep.containsKey(covId)){
                                        for(Dependent__c depMemMedi : ctomeddep.get(covId)){
                                            accountToUpdateMap.put(depMemMedi.Account__c, new Account(Id=depMemMedi.Account__c, Compliant__c=false, Comply__c=true));
                                        }
                                    }
                                }
                            }
                            
                        }
                    }
                    if(depM.Cover__r.Comply__c==true && depM.Cover__c == covId){
                        if(ctomeddep.containsKey(covId)) 
                            for(Dependent__c CMmed : ctomeddep.get(covId)){
                                accountToUpdateMap.put(CMmed.Account__c, new Account(Id=CMmed.Account__c, Compliant__c=false, Comply__c=true));
                            }
                    } 
                    
                }
            }
        }
        database.insert(cmlist, false);
        update accountToUpdateMap.values();
        
    }
    
}

 
Hi

I am getting this issue to many soql, is there something wrong with my code when try to save a record this error appers that too many soql
public class AccountTask {
    
    
    
    public static void accountTaskCopy(List<Account> acclist){
        Id EmailRT = SObjectType.Task.getRecordTypeInfosByDeveloperName().get('Email').getRecordTypeId();
        Id CallRT = SObjectType.Task.getRecordTypeInfosByDeveloperName().get('Call').getRecordTypeId(); 
        
        Set<Id> forWhatID = new Set<Id>();
        Set<Id> accID = new Set<Id>();
        Set<Id> coverageIds = new Set<Id>();
        Map<ID, List<CM__c>> accountIdToListCMOMap = new Map<Id, List<CM__c>>(); 
        Map<ID, List<CM__c>> coverageIdToListCVMMap = new Map<Id, List<CM__c>>();
        Map<ID, List<Task>> accountIdToListTaskCompletedMap = new Map<Id, List<Task>>();
        Map<ID, List<Task>> accountIdToListTaskNotCompletedMap = new Map<Id, List<Task>>();
        Map<Id, Account> accountsToUpdate = new Map<Id, Account>();
       
        for(Account acc: acclist){
            {
            accID.add(acc.ID);
            }
       }

        
        for(Task tsk : [SELECT ID,whatid FROM TASK where WHATID IN : accID]){
            if(tsk.WhatID != Null && tsk.WhatID.getSObjectType() == Account.SobjectType){
                forWhatID.add(tsk.WhatId);
                System.debug('forWhatID' + forWhatID);
            }
        }
         
        List<CM__c> existingCMs = [SELECT Id, Account__c, Account__r.Name, CVR__c, Coverage__r.Good__c,rel__c, status__c, BusinessType__c, Age_Today__c 
                                                            FROM CM__c 
                                                            WHERE (CVR__c != null AND Account__c IN: forWhatID AND Account__c != null) AND status__c ='ACTIVE' AND BusinessType__c = 'Medical'];
        
        for(CM__c cMo : existingCMs){
            if(accountIdToListCMOMap.containsKey(cMo.Account__c)){
                accountIdToListCMOMap.get(cMo.Account__c).add(cMo);
            }
            else{
                accountIdToListCMOMap.put(cMo.Account__c, new List<CM__c>{cMo});
            }
            
            if(coverageIdToListCVMMap.containsKey(cMo.CVR__c)){
                coverageIdToListCVMMap.get(cMo.CVR__c).add(cMo);
            }
            else{
                coverageIdToListCVMMap.put(cMo.CVR__c, new List<CM__c>{cMo});
            }
            
            coverageIds.add(cMo.CVR__c);
        }
        
        List<CM__c> existingCMFromCov = [SELECT Id, Account__c, Account__r.Name, CVR__c, Coverage__r.Good__c,rel__c, status__c, BusinessType__c, Age_Today__c 
                                                                   FROM CM__c 
                                                                   WHERE (CVR__c != null AND CVR__c IN: coverageIds AND Account__c != null) AND status__c ='ACTIVE' AND BusinessType__c = 'Medical'];
        for(CM__c cMo : existingCMFromCov){
            if(coverageIdToListCVMMap.containsKey(cMo.CVR__c)){
                coverageIdToListCVMMap.get(cMo.CVR__c).add(cMo);
            }
            else{
                coverageIdToListCVMMap.put(cMo.CVR__c, new List<CM__c>{cMo});
            }
        }
        System.debug('accountIdToListCMOMap ' + accountIdToListCMOMap);
        System.debug('coverageIdToListCVMMap ' + coverageIdToListCVMMap);
        
        
        List<Task> taskCompletedOrInvalidPhone = [SELECT Id, whatid, CallCustom__c, RecordtypeId 
                                                  FROM Task 
                                                  WHERE Whatid IN :forWhatID 
                                                  AND (CallCustom__c = 'Completed Campaign Requirements' OR CallCustom__c = 'Invalid Phone') AND WhatID != null];
        for(Task tsk : taskCompletedOrInvalidPhone){
            if(accountIdToListTaskCompletedMap.containsKey(tsk.WhatId)){
                accountIdToListTaskCompletedMap.get(tsk.WhatId).add(tsk);
            }
            else{
                accountIdToListTaskCompletedMap.put(tsk.WhatId, new List<Task>{tsk});
            }
        }
        
        List<Task> taskNotCompleteCampaign = [SELECT Id, whatid,CallCustom__c, RecordtypeId  FROM Task WHERE Whatid IN :forWhatID AND RecordTypeID =: CallRT AND (CallCustom__c = 'Left Message' OR  CallCustom__c = 'Unable to Reach') AND WhatID != null ];
        for(Task tsk : taskNotCompleteCampaign){
            if(accountIdToListTaskNotCompletedMap.containsKey(tsk.WhatId)){
                accountIdToListTaskNotCompletedMap.get(tsk.WhatId).add(tsk);
            }
            else{
                accountIdToListTaskNotCompletedMap.put(tsk.WhatId, new List<Task>{tsk});
            }
        }
        
        System.debug('accountIdToListTaskCompletedMap ' + accountIdToListTaskCompletedMap);
        System.debug('accountIdToListTaskNotCompletedMap ' + accountIdToListTaskNotCompletedMap);
        
        for(Id acctId : forWhatID){
            System.debug('acctId ' + acctId);
            if(accountIdToListTaskCompletedMap.containsKey(acctId)){
            system.debug('acctIdlist' + accountIdToListTaskCompletedMap);
                if(accountIdToListCMOMap.containsKey(acctId)){
                    for(CM__c cMo : accountIdToListCMOMap.get(acctId)){
                        System.debug('cMo ' + cMo);
                        if(coverageIdToListCVMMap.containsKey(cMo.CVR__c)){
                            for(CM__c covMem2 : coverageIdToListCVMMap.get(cMo.CVR__c)){
                                System.debug('covMem2 ' + covMem2);
                                accountsToUpdate.put(covMem2.Account__c, new Account(Id=covMem2.Account__c, PDC__c=true));
                            }
                        }
                        
                    } 
                } 
            }
        
        }
        
        System.debug('accountsToUpdate ' + accountsToUpdate);
        update accountsToUpdate.values();
        
    }
}

 
I have this Custom Object Named Stored XML.

and one of the field stores an XML strings.

<?xml version="1.0" encoding="UTF-8"?><consumers xmlns="http://test.com/feed/">
<SupplyResult>
 <MarketId>xxxxxxxx</MarketId>
 <SupplyList>
    <member>
        <Quantity>9</Quantity>
        <InStock>5</InStock>
        <SellerSKU>Test- 1111</SellerSKU>
    </member>
  </SupplyList>
  </SupplyResult>


How do I parse this and store all the field on on a new Custom Object Named XML Parsed?

Thank you!
How do i fix this issue?

({
    doInit : function(component,event,helper){
        var action = component.get("c.UserCheck");
        action.setParams({
            "currentRecordId" : component.get("v.recordId"),
            "currentUserId" : $A.get("$SObjectType.CurrentUser.Id")
        });
        action.setCallback(this,function(response){
            if(response.getState() == "SUCCESS"){
                //alert("hello there!" + response.getReturnValue()); 
                console.log(response.getReturnValue());
                if(response.getReturnValue()==true){
                    document.getElementById("Modal").setAttribute("style","height:640px;display:block;");
                    console.log(response.getReturnValue());
                }
                else{
                     document.getElementById("Modal").setAttribute("style","height:640px;display:none;");
                }
            }
        })
        $A.enqueueAction(action);
        
          var action2 = component.get("c.getAccount");
         action2.setParams({
            "currentRecordId" : component.get("v.recordId")
        });
        action2.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
               // alert("hello there!" + response.getReturnValue());
                component.set("v.account", response.getReturnValue());
                console.log(response.getReturnValue());
                /*if(response.getReturnValue()==true){
                    document.getElementById("Modal").setAttribute("style","height:640px;display:block;");
                    console.log(response.getReturnValue());
                }
                else{
                     document.getElementById("Modal_Parent").setAttribute("style","height:640px;display:none;");
                }*/
            }
         });
         $A.enqueueAction(action2); 
    
    },

 
var action2 = component.get("c.getAccount");
        action2.setParams({
            "currentRecordId" : component.get("v.recordId")
        });
        action2.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set("v.account", response.getReturnValue());
                console.log(response.getReturnValue());
            }
        });
        $A.enqueueAction(action2);
 
<aura:attribute name="account" type="Account" 
                    default="{ 'sobjectType': 'Account' }"/>
    <aura:attribute name="recordId" type="Id" />

    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    
    <div id="Modal_Parent" style="height:640px; width:1500px;">
        <section role="dialog" tabindex="-1" aria-labelledby="modal-heading-01" aria-modal="true" aria-describedby="modal-content-id-1" class="slds-modal slds-fade-in-open">
            <div class="slds-modal__container">
                <header class="slds-modal__header">
                    <h2 id="modal-heading-01" class="slds-text-heading_medium slds-hyphenate">Modal Test</h2>
                </header>
                <div class="slds-modal__content slds-p-around_medium" id="modal-content-id-1">
                    <p>Display the Name </p>
                    <force:outputField value="{!v.account.Name}"/>
                    {!v.account.Name}
                    <p></p>
                </div>

            </div>
 
@AuraEnabled
    public static List<Account> getAccount(String currentRecordId) {
        System.debug('AccountRecord' + currentRecordId);
        return [select Id, Name from Account where Id =: currentRecordId];
    }

 

Hey Guys,

 

Im struggling abit with figuring out how to parse some xml into a custom object. Ive been working with the xmlstreamreader example, but I cant quite wrap my head around how step through the xml elements values that I want to insert into my custom object....

 

The xml response Im getting back from my webcallout looks like this:

 

<advertisers type="array">
  <advertiser>
    <id type="integer">7</id>
    <name>ABC Telecom</name>
  </advertiser>
  <advertiser>
    <id type="integer">106</id>
    <name>ABC_Ozone</name>
  </advertiser><advertiser>
    <id type="integer">13</id>
    <name>Acme Corp</name>
  </advertiser>
</advertisers>

 

My goal is loop through this and extract the value of id and name of each advertiser. I would then like to insert the id and name of each advertiser into a custom object. I would use the name field for the name of the advertiser and I have a custom field realationship setup to store the id value.

 

Any help is much appreciated.

  • August 05, 2011
  • Like
  • 0