• Nagarjuna Reddy.P
  • NEWBIE
  • 45 Points
  • Member since 2017

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 28
    Questions
  • 31
    Replies
Hi Everyone,

I have a requirement as follows
When Case ownership is updated
1.update case related Account and account related contact ownership with new owner of Case.
2. update case related contact ownership with new owner of case

Here is my code..
public class caseTriggerExamples {

  public static void caseOwner(Map<id,Case> oldMap, Map<id,Case> newMap){

      List<id> accids=new List<id>();
      List<id> conids= new List<id>();
      List<Case> cases = new List<Case>();
       for(id key:oldMap.keyset()){
            Case oldCase = oldMap.get(key);
            Case newCase = newMap.get(key);
            if(oldCase.ownerid!=newCase.Ownerid){
            accids.add(newCase.AccountId);
                conids.add(newCase.ContactId);
            cases.add(newCase);
         }
      }
  List<Account> accounts = [select id,name,ownerid,(select id, Ownerid from contacts) from Account where id in:accids];
  List<Contact> contacts= [select id,ownerid from contact where id in:conids];
       List<Contact> cons= new List<Contact>();
       for(Account a:accounts){
           for(contact con:a.contacts){
               for(Case c: cases){
                 a.ownerid=c.ownerid;
                   con.OwnerId = c.OwnerId;
                   cons.add(con);
               }                   
        }

     }
      for(Contact con:contacts){
          for(Case ca:cases){
              con.OwnerId=ca.OwnerId;
          }
      }
         update accounts;
         update contacts;
         update cons;
       }
   }

trigger caseTriggerExamples on Case (after update) {
   if(trigger.isUpdate && trigger.isAfter){
      caseTriggerExamples.caseOwner(trigger.oldMap,trigger.newMap);
   }
}

My code is working fine, but my question here is, Is there any possibility of reducing using multiple for loops and achieve my requirement. This is the question asked in a recent interview and he asked me not to include multiple for loops.

Any help is appreciated. Thank you!!
 
Hello Everyone,

I just need to send email from finish method 
ple see my example code

global class batchExample implements Database.Batchable<sObject> {
    global Database.QueryLocator start( Database.BatchableContext BC ) {
 
        String query = 'SELECT Id,Name,email FROM contact';
        return Database.getQueryLocator( query );
    }
    global void execute( Database.BatchableContext BC, List< Contact> scope ) {
         for ( Contact c : scope ){
            if(c.mailingCountry = = 'US')
         {
             c.Name = c.Name + 'from US';            
         }
  }
         update scope;
    }   
    
    global void finish( Database.BatchableContext BC ) {
      Messaging.SingleEmailMessage mail = new         Messaging.SingleEmailMessage();
-------------------------------------------------
      mail.setToAddresses(email);
    }
 
}

Here I need to send email to contacts owner and email field of contacts  processed in execute()
So how do i get these email ids 
Do i need to write SOQL query to get email ids, any guidance is much appreciated.
Thank you all
Hi All,

I overriden standard new button of Account with lightning component.. since last 5 days it has been giving error message as "cannot specify id in an insert call"..
The problem is when a new record is created and try to create another record the previous record values remains (pre populated) in the input fields and not allowing to create another record.

Error Message : invalid_field_for_insert_update cannot specify id in an insert call


Here is my code
Apex class :
@AuraEnabled
     public static Account saveAccount(account acc){
              insert acc;
            return acc;
     }

Component : 

<aura:component implements="lightning:actionOverride" access="global" controller="apexHandler">
    <aura:attribute name="newAcc" type="Account" default="{'sobjectType': 'Account'}" />    
<aura:attribute name="accountType" type="String[]" default="Insurance,MSO,IPA,PCP,SNF,ALF,Hospital,Home Health,Other"/>
<lightning:input name="accountName" label="Account Name"         required="true" value="{!v.newAcc.Name}" class="slds-size--1-of-2 slds-p-horizontal_x-small"/>
<lightning:select aura:id="accType" name="accType" label="Account Type"  value="{!v.newAcc.Account_Type__c}" onchange=" {!c.conditionalDisplay}" class="slds-size--1-of-2 slds-p-horizontal_x-small" required="true" messageWhenValueMissing="Please Select a Value">
          <option value="">--None--</option>
           <aura:iteration items="{!v.accountType}" var="item">
                  <option value="{!item}">{!item}</option>
               </aura:iteration>
    </lightning:select>
       <lightning:button variant="neutral" label="Cancel" onclick="{!c.cancelDialog}" />
                <lightning:button variant="brand" label="Save" onclick="{!c.saveRecord}" />
</aura:component>

Controller : 
          
 saveRecord : function(component,event,helper){
var accRec = component.get("v.newAcc");
 var action = component.get("c.saveAccount");
         action.setParams({
                 "acc" : accRec
             });        
        action.setCallback(this,function(response){
             var state = response.getState();
             var resultsToast = $A.get("e.force:showToast");
             if(state == "SUCCESS"){
                resultsToast.setParams({
                    "title": "Saved",
                    "message": "The Account Record is saved.",
                    "type" : "success"
              });
              
                 component.set("v.newAcc",response.getReturnValue());
                 var recId = component.get("v.newAcc.Id");
                 console.log('Account Record Id== >> '+recId);
                 resultsToast.fire(); 
                 helper.navigateTo(component,recId);
                }else if(state == "ERROR"){
               console.log('Error: ' + JSON.stringify(response.getError()));
                 resultsToast.setParams({
                     "title": "Error",
                     "type" :"error",
                     "message": "Please Enter Account Name: " + JSON.stringify(response.getError())
                 });
                 resultsToast.fire();
                 console.log('Unknown problem, state: ' + response.getState() + ', error: ' + JSON.stringify(response.getError()));
            }
        });
         $A.enqueueAction(action);
       }
I'm not sure what's wrong with the code, Could you pls help me with this.
 
Hi All,

I have a requirement that i need to auto upload data from snowflake to one of the custom object so that i can avoid using data loader for uploading.Is this possible? I'm totally unaware of this module, Could any one please guide me throgh this.

Thank you All.
Hi All,

I have a batch process which is scheduled to run on daily basis, but the process is failed bcz of required picklist field on Account have null values in bulk number. I'm not required to perform bulk update as we are not sure with right value. So is there any way to bypass this required field to succesfully run the batch process.
Hi All,
 How we can exchange data from EMR system to salesforce through FHIR API, I need to insert records in to custom object when the data is created in EMR.. I need to integrate with FHIR.

 I'm in confusion, could anyone please explain me the flow, how to achieve this.

Thanks. 
Hi All,
my test class for batch apex is not covering the complete code,could you pls help me for complete coverage.
Here is my batch class

 global with sharing class batchHandler implements Database.Batchable<SObject> {
 global Database.QueryLocator start(Database.BatchableContext bc){
      String squery = 'SELECT Id,Referral_Stage__c,Account_Type__c,(SELECT Id,createdDate from child1__r ORDER BY CreatedDate DESC LIMIT 50),(SELECT Id,createdDate from child2__r  ORDER BY CreatedDate DESC LIMIT 50),(SELECT Id,createdDate from child3__r ORDER BY CreatedDate DESC LIMIT 50),(SELECT Id,createdDate from child4__r ORDER BY CreatedDate DESC LIMIT 50) from Account';
      return Database.getQueryLocator(squery);
  }
  global void execute(Database.BatchableContext bc,List<Account> scope){
    Date today = Date.today();
    Date twoMonthsBefore = today.addDays(-10);
    Set<Account> accounts = new Set<Account>();
    List<Account> accToUpdate = new List<Account>();
    // Map<id,Account> accMap=new Map<id,Account>();
    //if(scope.size()>0){
  for(Account acc:scope){
      try{
         if(!acc.child1__r .isEmpty()){
        for(Referral__c insurance:acc.child1__r ){
       // if(insurance.size()>0){
            if(insurance.createdDate > twoMonthsBefore){
            acc.Referral_Stage__c='Currently Referring';
            accounts.add(acc);
            //  accMap.put(acc.Id,acc);
           } else if(insurance.createdDate < twoMonthsBefore){
              acc.Referral_Stage__c='Referred Inactive';
              accounts.add(acc);
              //  accMap.put(acc.Id,acc);
           }
       //  }
           } 
         }else if(!acc.child2__r .isEmpty()){
             for(Referral__c mso:acc.child2__r ){
        if(mso.createdDate > twoMonthsBefore){
          acc.Referral_Stage__c='Currently Referring';
          accounts.add(acc);
          //  accMap.put(acc.Id,acc);
      }else if(mso.createdDate < twoMonthsBefore){
        acc.Referral_Stage__c='Referred Inactive';
        accounts.add(acc);
        //  accMap.put(acc.Id,acc);
       }
     }
      }else if(!acc.child3__r .isEmpty()){
          for(Referral__c ipa:acc.child3__r ){
        if(ipa.createdDate > twoMonthsBefore){
          acc.Referral_Stage__c='Currently Referring';
          accounts.add(acc);
          //  accMap.put(acc.Id,acc);
      }else if(ipa.createdDate < twoMonthsBefore){
        acc.Referral_Stage__c='Referred Inactive';
        accounts.add(acc);
        //  accMap.put(acc.Id,acc);
          }         
       }
      }else if(!acc.child4__r .isEmpty()){
          for(Referral__c pcp:acc.child4__r ){
        if(pcp.createdDate > twoMonthsBefore){
          acc.Referral_Stage__c='Currently Referring';
          accounts.add(acc);
          //  accMap.put(acc.Id,acc);
      }else if(pcp.createdDate < twoMonthsBefore){
        acc.Referral_Stage__c='Referred Inactive';
        accounts.add(acc);
        //  accMap.put(acc.Id,acc);
       }
      }
    }
      else{
          acc.Referral_Stage__c='Never Referred';
          accounts.add(acc);
          //  accMap.put(acc.Id,acc);
        }
      }catch(Exception e){
        }
      }
    
 // }
    if(!accounts.isEmpty()){
        //update accounts;
        accToUpdate.addAll(accounts);
    } 
      if(!accToUpdate.isEmpty()){
           update accToUpdate;
      }
      /*  if(accMap!=null){
            accToUpdate=accMap.values();
            //update accMap.values();
        }
        if(!accToUpdate.isEmpty()){
            update accToUpdate;
        } */ 
  }
  global void finish(Database.BatchableContext bc){
  }
}

My Test class is : 
 @isTest
private class batchHandlerTest {
    static testmethod void testBatch() {
         List<Account> acclist = new List<Account>();
         for(Integer i=0;i<200;i++){
           //  try{
             Account acc=new Account();
             acc.Name = 'Account'+i;
             acc.Account_Type__c = 'IPA';
             acc.Phone = '1234567890';
             acc.Referral_Stage__c = 'Never Referred';
             acclist.add(acc);
        // }catch(Exception e){}
            
           
        }
         insert acclist;
         Test.startTest();
           batchHandler b = new batchHandler();
           Database.executeBatch(b);
         Test.stopTest();
         Account[] updateRefStage = [select id,name,Referral_Stage__c from Account];
         system.assert(updateRefStage[0].Referral_Stage__c.contains('Never Referred'));
    }
}

This giving only 50% of coverage and If --- else if -- conditions are not covered. 
 
Hi All,
I'm little confused to choose  trigger/process builder with my scenario could you please help me with this.
I have parent and child objects with Lookup relationship. I need to auto update parent picklist field with conditions as follows
1.If parent has child records created in last 2 months from todays date update to valueA
2.If parent has child records in the past and there have not been any childs in last 2 months from todays date then ValueB
3.If parent never have any childs update to valueC

I hope we cant  use process builder for this and trigger is preferred to write on child object but which trigger context i should use.
Could any one please give me an idea how to do this.
thank you.
Hi All,
     I have a simple apex method used in ligthing lookup to search name and phone fields.
apex method:
   @AuraEnabled  
     public static List<sObject> getRecordList(String objName,String searchText,String fieldInSearch,String phone){
        string searchKey = '%' + searchText + '%';
        string Query =' select ' +fieldInSearch+ ',' +phone;
        Query+=' from '+objName;
        Query+=' where '+fieldInSearch+ ' like  \''+searchKey+'\' LIMIT 5';
            system.debug('Query == >> '+Query);
        List<sObject> sObjectList = Database.query(Query);
        system.debug(' #### sobjectList ' + sObjectList);
        return sObjectList;
    }
Test class :
 @isTest static void searchAcc(){
        String searchText = 'test';
        string field = 'name';
        string obj = 'Account';
        string phone='12345';
        List<account> a = apexHandler.getRecordList(obj,searchText,field,phone);
        system.debug('Account'+a);
        system.assertEquals(1, a.size());
    }
when i run the test the method gets failed and showing error System.QueryException: unexpected token: '12345' and at line no Database.query(Query) from apex method.
I gone through different solutions but unable to resolve, could any one help me with this to resolve and run test method succesfully.
Hi All,
          I am using a LDS to edit a few fields of record using lightning:recordEditForm in the detail page of a record.I used a separate component to display some fields of record to display using lightning:viewForm and this component has a button named as Edit.So If editing is required for the fields just click on Edit button which opens a form Where I used lightning:recordEditForm here we can edit and submit the changes it navigates to record page.It works well only if i include one lookup field and if I include more than 1 lookup field its giving some unexpected errors like Object Object. see the attached image with error msg.
User-added image
Is it a good practice to use LDS over to Apex controllers??
Does LDS gives any unexpected behaviours.why I am asking is sometimes changes are not reflected immediately need to refresh multiple times and even sometimes i logout and again login to see the changes.this is really hesitating...
Hi,
      I am using lightning:select to make this required I am using attributes reuired = "true" and messageWhenValueMissing = "error message" but either of these attributes are not working & allowing the record to save even without giving any value.
the default value for lightning:select is --None-- is this considered as value and allowing record to save? how to solve this?
any help is greatly appreciated.
Thanks,
Hi All,
             Could any one please provide test class for the following trigger that updates field on account.

apexclass...

  public with sharing class CountofTasks{
    public static void updateAcc(List<Task> tasks){
        set<id> accids = new set<id>();
        for(Task t:tasks){
            if(t.whatid!=null){
                accids.add(t.whatid);
            }
        }
        List<Account> accounts = [select id,Task_Count__c from Account where id in:accids];
       integer count = [select count() from Task where whatid in:accids];
        if(count >0){
            for(Account a:accounts){
                 a.Task_Count__c = count ;
            }
                   } 
              update accounts;
    }
Trigger...

  trigger ExampleTrigger on Task (after insert,after delete) {
    if(Trigger.isInsert && Trigger.isAfter){
        CountofTasks.updateAcc(Trigger.New);
  }
}
Thanks in Advance....
Hi All,
           I have a simple method that inserts record into account object through lightning component.My apex class method is as follows.
 
 @AuraEnabled
     public static Account saveAccount(account acc){
       insert acc;
       return acc;
     }
My test class for this is

@isTest
private class testClassExample {
    @isTest static void createAcc(){
        Account acc=new Account();
        acc.Name = 'Test Account';
        acc.Phone = '12345';
        acc.Account_Type__c = 'Insurance';
        try{
             insert acc;
        }catch(Exception e){
            system.debug(e);
        }
                  
        Account a = example.saveAccount(acc); 
        integer count=[select count() from account];
        system.assertEquals( 1,count);
    }
My Test coverage is 66% and return statement from saveAccount method is not covered for coverage,how to cover this return statement.
Any help is appreciated.

Thank you.
Hi All,
           I am trying to override standard account page(New button) with lightning components and I am using lightning:fileupload to upload multiple files but it is in disabled mode eventhough  I set disbled attribute as false.
   Any help is greatly appreciated.
    Thanks in Advance.
 
Hi All,
          I wrote a simple trigger with before delete event on contact to prevent deletion if either contact field source__c == 'SAPExternal' or its related account.source=='SAPExternal'.my code is as follows.

public class ContactTriggerExamples {
 public static void beforeDelete(List<Contact> cns){
    for(Contact c:cns){
                 if( c.Source__c=='SAPExternal' || c.Account.Source=='SAPExternal'){
                     c.addError('You cant Delete Contact with Source as SAPExternal'); 
                 } 
           } 
}
trigger:
trigger ContactTriggerExamples on Contact (before Delete){
 if(Trigger.isDelete && Trigger.isBefore){
        ContactTriggerExamples.beforeDelete(Trigger.old);
    }
}
  It is perfectly working for first condtition i.e c.source == 'SAPExternal' and it is not working for c.account.source=='SAPExternal',whats wrong with my code.
Thank you all.
Hi All,
            I have a Look up field on Contact to Account ,In VF page i used input field component to refer this relation.
  <apex:inputField  value="{!Contact.AccountId}" /> this field is displayed in page as look up  
    User-added image
      here i dont need to click on look up icon to select existing account,but when I start typing text in the text box the Account records are to be Autohiglighted with the matching text which I entered.Clicking custom button to search records is  not required for me.
Thnak you.
Hi,
    I want to display a input field text in both English and Arabic language in vf page.
ex:  Account Name/ Account name in Arabic 

Thank you.
Hi,
      I need to change the default background color of vf page.
  User-added image
in this image there are two pageblock sections with white backfround , i am using lightning interface.
I used attribute in <apex:form StyleClass="background-color:blue" > but the white background of pageblock sections remains same.I need to apply the color to whole form including pageblock sections also,Is there any other way  please suggest me.
Thank you All.
Hi All,
                I am using a vf page which overrides custom object,Object__A is parent to Object__C and Object__B and Object__A is child to some other object ex:Object__P ,I am overriding Standard New button of Object__C with vf page,Now my requirement is when I select Lookup field Object__A i want to auto populate some fields of Object__A and its parent Object__P and child Object__B fields  also.
Note:   Object__C has no relation with Object__P and Object__B,it has only relation with Object__A.
  
 This is an urgent requirement ,please help me to achieve this requirement.
  Thank you.
Hii All,
            I am using lightning experience and now my client is not satisfied with standard ui look of our lightning experience and  i need to customize the complete ui ,how can i do this in lightning.Any help is greately appreciated.

Thank you.
Hi Everyone,

I have a requirement as follows
When Case ownership is updated
1.update case related Account and account related contact ownership with new owner of Case.
2. update case related contact ownership with new owner of case

Here is my code..
public class caseTriggerExamples {

  public static void caseOwner(Map<id,Case> oldMap, Map<id,Case> newMap){

      List<id> accids=new List<id>();
      List<id> conids= new List<id>();
      List<Case> cases = new List<Case>();
       for(id key:oldMap.keyset()){
            Case oldCase = oldMap.get(key);
            Case newCase = newMap.get(key);
            if(oldCase.ownerid!=newCase.Ownerid){
            accids.add(newCase.AccountId);
                conids.add(newCase.ContactId);
            cases.add(newCase);
         }
      }
  List<Account> accounts = [select id,name,ownerid,(select id, Ownerid from contacts) from Account where id in:accids];
  List<Contact> contacts= [select id,ownerid from contact where id in:conids];
       List<Contact> cons= new List<Contact>();
       for(Account a:accounts){
           for(contact con:a.contacts){
               for(Case c: cases){
                 a.ownerid=c.ownerid;
                   con.OwnerId = c.OwnerId;
                   cons.add(con);
               }                   
        }

     }
      for(Contact con:contacts){
          for(Case ca:cases){
              con.OwnerId=ca.OwnerId;
          }
      }
         update accounts;
         update contacts;
         update cons;
       }
   }

trigger caseTriggerExamples on Case (after update) {
   if(trigger.isUpdate && trigger.isAfter){
      caseTriggerExamples.caseOwner(trigger.oldMap,trigger.newMap);
   }
}

My code is working fine, but my question here is, Is there any possibility of reducing using multiple for loops and achieve my requirement. This is the question asked in a recent interview and he asked me not to include multiple for loops.

Any help is appreciated. Thank you!!
 
Hi All,

I overriden standard new button of Account with lightning component.. since last 5 days it has been giving error message as "cannot specify id in an insert call"..
The problem is when a new record is created and try to create another record the previous record values remains (pre populated) in the input fields and not allowing to create another record.

Error Message : invalid_field_for_insert_update cannot specify id in an insert call


Here is my code
Apex class :
@AuraEnabled
     public static Account saveAccount(account acc){
              insert acc;
            return acc;
     }

Component : 

<aura:component implements="lightning:actionOverride" access="global" controller="apexHandler">
    <aura:attribute name="newAcc" type="Account" default="{'sobjectType': 'Account'}" />    
<aura:attribute name="accountType" type="String[]" default="Insurance,MSO,IPA,PCP,SNF,ALF,Hospital,Home Health,Other"/>
<lightning:input name="accountName" label="Account Name"         required="true" value="{!v.newAcc.Name}" class="slds-size--1-of-2 slds-p-horizontal_x-small"/>
<lightning:select aura:id="accType" name="accType" label="Account Type"  value="{!v.newAcc.Account_Type__c}" onchange=" {!c.conditionalDisplay}" class="slds-size--1-of-2 slds-p-horizontal_x-small" required="true" messageWhenValueMissing="Please Select a Value">
          <option value="">--None--</option>
           <aura:iteration items="{!v.accountType}" var="item">
                  <option value="{!item}">{!item}</option>
               </aura:iteration>
    </lightning:select>
       <lightning:button variant="neutral" label="Cancel" onclick="{!c.cancelDialog}" />
                <lightning:button variant="brand" label="Save" onclick="{!c.saveRecord}" />
</aura:component>

Controller : 
          
 saveRecord : function(component,event,helper){
var accRec = component.get("v.newAcc");
 var action = component.get("c.saveAccount");
         action.setParams({
                 "acc" : accRec
             });        
        action.setCallback(this,function(response){
             var state = response.getState();
             var resultsToast = $A.get("e.force:showToast");
             if(state == "SUCCESS"){
                resultsToast.setParams({
                    "title": "Saved",
                    "message": "The Account Record is saved.",
                    "type" : "success"
              });
              
                 component.set("v.newAcc",response.getReturnValue());
                 var recId = component.get("v.newAcc.Id");
                 console.log('Account Record Id== >> '+recId);
                 resultsToast.fire(); 
                 helper.navigateTo(component,recId);
                }else if(state == "ERROR"){
               console.log('Error: ' + JSON.stringify(response.getError()));
                 resultsToast.setParams({
                     "title": "Error",
                     "type" :"error",
                     "message": "Please Enter Account Name: " + JSON.stringify(response.getError())
                 });
                 resultsToast.fire();
                 console.log('Unknown problem, state: ' + response.getState() + ', error: ' + JSON.stringify(response.getError()));
            }
        });
         $A.enqueueAction(action);
       }
I'm not sure what's wrong with the code, Could you pls help me with this.
 
Hi All,
my test class for batch apex is not covering the complete code,could you pls help me for complete coverage.
Here is my batch class

 global with sharing class batchHandler implements Database.Batchable<SObject> {
 global Database.QueryLocator start(Database.BatchableContext bc){
      String squery = 'SELECT Id,Referral_Stage__c,Account_Type__c,(SELECT Id,createdDate from child1__r ORDER BY CreatedDate DESC LIMIT 50),(SELECT Id,createdDate from child2__r  ORDER BY CreatedDate DESC LIMIT 50),(SELECT Id,createdDate from child3__r ORDER BY CreatedDate DESC LIMIT 50),(SELECT Id,createdDate from child4__r ORDER BY CreatedDate DESC LIMIT 50) from Account';
      return Database.getQueryLocator(squery);
  }
  global void execute(Database.BatchableContext bc,List<Account> scope){
    Date today = Date.today();
    Date twoMonthsBefore = today.addDays(-10);
    Set<Account> accounts = new Set<Account>();
    List<Account> accToUpdate = new List<Account>();
    // Map<id,Account> accMap=new Map<id,Account>();
    //if(scope.size()>0){
  for(Account acc:scope){
      try{
         if(!acc.child1__r .isEmpty()){
        for(Referral__c insurance:acc.child1__r ){
       // if(insurance.size()>0){
            if(insurance.createdDate > twoMonthsBefore){
            acc.Referral_Stage__c='Currently Referring';
            accounts.add(acc);
            //  accMap.put(acc.Id,acc);
           } else if(insurance.createdDate < twoMonthsBefore){
              acc.Referral_Stage__c='Referred Inactive';
              accounts.add(acc);
              //  accMap.put(acc.Id,acc);
           }
       //  }
           } 
         }else if(!acc.child2__r .isEmpty()){
             for(Referral__c mso:acc.child2__r ){
        if(mso.createdDate > twoMonthsBefore){
          acc.Referral_Stage__c='Currently Referring';
          accounts.add(acc);
          //  accMap.put(acc.Id,acc);
      }else if(mso.createdDate < twoMonthsBefore){
        acc.Referral_Stage__c='Referred Inactive';
        accounts.add(acc);
        //  accMap.put(acc.Id,acc);
       }
     }
      }else if(!acc.child3__r .isEmpty()){
          for(Referral__c ipa:acc.child3__r ){
        if(ipa.createdDate > twoMonthsBefore){
          acc.Referral_Stage__c='Currently Referring';
          accounts.add(acc);
          //  accMap.put(acc.Id,acc);
      }else if(ipa.createdDate < twoMonthsBefore){
        acc.Referral_Stage__c='Referred Inactive';
        accounts.add(acc);
        //  accMap.put(acc.Id,acc);
          }         
       }
      }else if(!acc.child4__r .isEmpty()){
          for(Referral__c pcp:acc.child4__r ){
        if(pcp.createdDate > twoMonthsBefore){
          acc.Referral_Stage__c='Currently Referring';
          accounts.add(acc);
          //  accMap.put(acc.Id,acc);
      }else if(pcp.createdDate < twoMonthsBefore){
        acc.Referral_Stage__c='Referred Inactive';
        accounts.add(acc);
        //  accMap.put(acc.Id,acc);
       }
      }
    }
      else{
          acc.Referral_Stage__c='Never Referred';
          accounts.add(acc);
          //  accMap.put(acc.Id,acc);
        }
      }catch(Exception e){
        }
      }
    
 // }
    if(!accounts.isEmpty()){
        //update accounts;
        accToUpdate.addAll(accounts);
    } 
      if(!accToUpdate.isEmpty()){
           update accToUpdate;
      }
      /*  if(accMap!=null){
            accToUpdate=accMap.values();
            //update accMap.values();
        }
        if(!accToUpdate.isEmpty()){
            update accToUpdate;
        } */ 
  }
  global void finish(Database.BatchableContext bc){
  }
}

My Test class is : 
 @isTest
private class batchHandlerTest {
    static testmethod void testBatch() {
         List<Account> acclist = new List<Account>();
         for(Integer i=0;i<200;i++){
           //  try{
             Account acc=new Account();
             acc.Name = 'Account'+i;
             acc.Account_Type__c = 'IPA';
             acc.Phone = '1234567890';
             acc.Referral_Stage__c = 'Never Referred';
             acclist.add(acc);
        // }catch(Exception e){}
            
           
        }
         insert acclist;
         Test.startTest();
           batchHandler b = new batchHandler();
           Database.executeBatch(b);
         Test.stopTest();
         Account[] updateRefStage = [select id,name,Referral_Stage__c from Account];
         system.assert(updateRefStage[0].Referral_Stage__c.contains('Never Referred'));
    }
}

This giving only 50% of coverage and If --- else if -- conditions are not covered. 
 
Hi All,
I'm little confused to choose  trigger/process builder with my scenario could you please help me with this.
I have parent and child objects with Lookup relationship. I need to auto update parent picklist field with conditions as follows
1.If parent has child records created in last 2 months from todays date update to valueA
2.If parent has child records in the past and there have not been any childs in last 2 months from todays date then ValueB
3.If parent never have any childs update to valueC

I hope we cant  use process builder for this and trigger is preferred to write on child object but which trigger context i should use.
Could any one please give me an idea how to do this.
thank you.
Hi All,
     I have a simple apex method used in ligthing lookup to search name and phone fields.
apex method:
   @AuraEnabled  
     public static List<sObject> getRecordList(String objName,String searchText,String fieldInSearch,String phone){
        string searchKey = '%' + searchText + '%';
        string Query =' select ' +fieldInSearch+ ',' +phone;
        Query+=' from '+objName;
        Query+=' where '+fieldInSearch+ ' like  \''+searchKey+'\' LIMIT 5';
            system.debug('Query == >> '+Query);
        List<sObject> sObjectList = Database.query(Query);
        system.debug(' #### sobjectList ' + sObjectList);
        return sObjectList;
    }
Test class :
 @isTest static void searchAcc(){
        String searchText = 'test';
        string field = 'name';
        string obj = 'Account';
        string phone='12345';
        List<account> a = apexHandler.getRecordList(obj,searchText,field,phone);
        system.debug('Account'+a);
        system.assertEquals(1, a.size());
    }
when i run the test the method gets failed and showing error System.QueryException: unexpected token: '12345' and at line no Database.query(Query) from apex method.
I gone through different solutions but unable to resolve, could any one help me with this to resolve and run test method succesfully.
Hi All,
             Could any one please provide test class for the following trigger that updates field on account.

apexclass...

  public with sharing class CountofTasks{
    public static void updateAcc(List<Task> tasks){
        set<id> accids = new set<id>();
        for(Task t:tasks){
            if(t.whatid!=null){
                accids.add(t.whatid);
            }
        }
        List<Account> accounts = [select id,Task_Count__c from Account where id in:accids];
       integer count = [select count() from Task where whatid in:accids];
        if(count >0){
            for(Account a:accounts){
                 a.Task_Count__c = count ;
            }
                   } 
              update accounts;
    }
Trigger...

  trigger ExampleTrigger on Task (after insert,after delete) {
    if(Trigger.isInsert && Trigger.isAfter){
        CountofTasks.updateAcc(Trigger.New);
  }
}
Thanks in Advance....
Hi All,
           I have a simple method that inserts record into account object through lightning component.My apex class method is as follows.
 
 @AuraEnabled
     public static Account saveAccount(account acc){
       insert acc;
       return acc;
     }
My test class for this is

@isTest
private class testClassExample {
    @isTest static void createAcc(){
        Account acc=new Account();
        acc.Name = 'Test Account';
        acc.Phone = '12345';
        acc.Account_Type__c = 'Insurance';
        try{
             insert acc;
        }catch(Exception e){
            system.debug(e);
        }
                  
        Account a = example.saveAccount(acc); 
        integer count=[select count() from account];
        system.assertEquals( 1,count);
    }
My Test coverage is 66% and return statement from saveAccount method is not covered for coverage,how to cover this return statement.
Any help is appreciated.

Thank you.
Hi All,
           I am trying to override standard account page(New button) with lightning components and I am using lightning:fileupload to upload multiple files but it is in disabled mode eventhough  I set disbled attribute as false.
   Any help is greatly appreciated.
    Thanks in Advance.
 
Hi All,
          I wrote a simple trigger with before delete event on contact to prevent deletion if either contact field source__c == 'SAPExternal' or its related account.source=='SAPExternal'.my code is as follows.

public class ContactTriggerExamples {
 public static void beforeDelete(List<Contact> cns){
    for(Contact c:cns){
                 if( c.Source__c=='SAPExternal' || c.Account.Source=='SAPExternal'){
                     c.addError('You cant Delete Contact with Source as SAPExternal'); 
                 } 
           } 
}
trigger:
trigger ContactTriggerExamples on Contact (before Delete){
 if(Trigger.isDelete && Trigger.isBefore){
        ContactTriggerExamples.beforeDelete(Trigger.old);
    }
}
  It is perfectly working for first condtition i.e c.source == 'SAPExternal' and it is not working for c.account.source=='SAPExternal',whats wrong with my code.
Thank you all.