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

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 35
    Questions
  • 32
    Replies
Hi,

I've to populate the saved picklist value on UI for HTML Select, and I'm completely struck with this.
Here is my select 

<tbody>
<template for:each={updatedItemList} for:item="updatedItem" for:index="index">
<td>
 <select name="Time Frames" class="select slds-select" data-label='timeFrames' data-index={index} onchange={itemUpdate}>
                    <option value="" >Select an Option</option>
                    <template for:each={itemList} for:item="item">
                      <option key={item.label} value={item.value} selected={item.selected}>{item.label}</option>
                    </template>
                  </select>
        </td>
   </template>
</tbody>
In Js Controller getting the slected value using event.target.value and passing to apex method where the upsert operation occurs and the picklist value updated successfully but the updated value is not populating at UI.

Here the updatedItemList has the latest updated value and when I tried by replacing value attribut for <option> as   value={updatedItem.value} , I'm getting the current field value from database and same value is passing to apex from event.target.value , but here need to get the current value selected.
Can you people please suggest me how to resolve this.

Thank you. 
Hi Guys,

I need to set a placeholder like "Select an option" for <select> tag in LWC, I found no useful links, Could you pleas guide me on this.
Here is my <select> code
<select name="Time Frames" class="select slds-select" data-label='timeFrames' data-index={index} onchange={onClickUpdate}>
                    <template for:each={itemList} for:item="item">
                      <option key={item.label} value={item.value} selected={item.selected}>{item.label}</option>
                    </template>
        </select>

Here itemList has picklist values from wire property of getpicklistvalues.This code considering the first value as default from the picklist values.
I don't need to have that default value and need to select from the dropdown.

Thank you.
Hello,

I have a batch class which updates Status field based on HistoryRecord Created Date.I'm unable to get the complete code coverage as History Record Field New Value is not writeble. Could any one guide me to get code coverage.
Here is my Batch and Test classes

global class BOSSWaiverStatusUpdateBatch implements Database.Batchable<sObject>  {
  
   global Database.QueryLocator Start(Database.BatchableContext bc){
      String query = 'select id,Name,Status__c from Account where Status__c = \'More Information Required\'';
       return Database.getQueryLocator(query);
   }
   global void execute(Database.BatchableContext bc, List<Account> scope){
       List<Account> records = new List<Account>();
       Map<id,Account> updateWaivers = new Map<id,Account>();
       List<Id> ids = new List<Id>();
       Date currentDate = Date.today();
       for(Account rec:scope){
          // if(rec.BOSS_Waiver_Status__c == 'More Information Required'){
           // today.add(rec.createddate);
               ids.add(rec.id);
          // }
       }
       List<AccountHistory> historyRec = [select id,field,createddate,newvalue,oldvalue,parentid from AccountHistory where field = 'Status__c' and parentid in:ids order by createddate desc];
        Date moreInfoReqDate;
       for(AccountHistory hrec : historyRec){
           moreInfoReqDate = Date.newInstance(hrec.CreatedDate.year(),hrec.CreatedDate.month(),hrec.CreatedDate.day());
           System.debug('Into History loop');
           System.debug('Scope Records=='+scope.size());
            System.debug('History New Value=='+hrec.NewValue);
           if(hrec.NewValue == 'More Information Required' && (moreInfoReqDate.daysBetween(currentDate))>1){
               for(Account wrec : scope){
                   System.debug('Into Status update loop');
                   wrec.Status__c = 'Not Applicable';
                   records.add(wrec);

               }
               
           }
       }
       updateAccs.putAll(records);
       System.debug('Account Records to update=='+updateAccs.size());
       if(updateAccs.size()>0){
           update updateAccs.values();
       }

      // update records;
   }
   global void finish(Database.BatchableContext bc){

   }
}
The highlighted bold lines are not covered any code coverage. following is the test class

Test Class : 

@isTest
public class BOSSWaiverStatusUpdateBatchTest {
  
    @TestSetup
       public static void setup(){
        List<Account> AccRecords = new List<Account>();
        List<Account> updateAccs = new List<Account>();
        for(integer i=0;i<200;i++){
            Account accounts = new Account();
            accounts.Name = 'Test Account'+i;
            accounts.Statuc__c = 'Test';
            AccRecords.add(accounts);
        }
        try{
            insert AccRecords;
            for(Account w : AccRecords){
                w.BOSS_Waiver_Status__c = 'More Information Required';
                updateAccs.add(w);
            }
            update updateAccs;
            
        }
        catch(Exception e){
            System.debug('Exception Message=='+e.getMessage());
        }
    }
   @isTest static void updateWaiverBatchTest(){
         
       List<Account> rec = [select id,Name,Status__c from Account where Status__c = 'More Information Required'];
       AccountHistory history = new AccountHistory();
       history.Field = 'Status__c';
       history.ParentId = rec[0].id;
      // history.NewValue = 'More Information Required';
       insert history;
                Test.startTest();
                 BOSSWaiverStatusUpdateBatchSchedule sbatch = new BOSSWaiverStatusUpdateBatchSchedule();
                    String sch = '0 0 5 * * ?'; 
                    system.schedule('Test Schedule Batch', sch, sbatch);
                Test.stopTest();
      
        List<Account> records = [select id,Status__c from Account where BOSS_Waiver_Status__c = 'Not Applicable'];
       if(records.size()>0){
        system.assertEquals('Not Applicable',records[0].BOSS_Waiver_Status__c);
       } 
    }

Thank you guys!
Hello All,

I have a created a new QucikAction button and invoking LWC component which is performing some DML'S like Insert,update and delete.
 Quick Action button is available on all the child records and parent, the button should be only available for parent but as record type is same for both parent and child records i can't use different page layouts to hide the Quick action for child.
ex : Account A has child Account records 1,2,3 ect.
Account has lookup to another custom object , in my scenario Account A related  parent record type(Custom object) is not same  as child Account related parent.
So on click of Quick Action on child Account record,I need to verify the record type of parent and display error message(toast message) saying this record is not valid to perform DML's.

May I get any help! 

Thank you All.
Hello Everyone,
  Here is my simple soql query
public static List<Account> updateMethod(id Id,List<String> selectedFields) {
   String squery = 'select Name,' +selectedFields+ 'FROM Account where id =:Id';
Account currentRec = database.query(squery);
}

Here selectedFields conatins accountfield API names which are passing from LWC js controller, I'm getting unexpected token issue

For Ex: selectedFields conatins Email__c,phone,name ect, I'm getting System.QueryException : unexpected token Email__c.

I'm not sure what might be the issue. Can any one help me.

Thank you.
Hello Everyone,

I have a requirement that on click of a button on record page need to show a lightning dual list box with available fields of a custom objectA, now the requirement is to select fields as needed and onclick of a button need to update the selected field values to the child record fields(Self look up records).
As recommended using LWC lightning-dual-listbox and i stuck with updation part, how to store the selected fields and how to update child records with current record selected fields.

Can i get any help.

Thank you!
Hello All,

I have a requirement that On click of a button from Account record page need to generate a pdf with all related contacts and opportunities of that account. and need to send that pdf to account's email address and attach to account record.

Coula any one please help me with this requirement.

Thank you All !!
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.
Hello Everyone,
  Here is my simple soql query
public static List<Account> updateMethod(id Id,List<String> selectedFields) {
   String squery = 'select Name,' +selectedFields+ 'FROM Account where id =:Id';
Account currentRec = database.query(squery);
}

Here selectedFields conatins accountfield API names which are passing from LWC js controller, I'm getting unexpected token issue

For Ex: selectedFields conatins Email__c,phone,name ect, I'm getting System.QueryException : unexpected token Email__c.

I'm not sure what might be the issue. Can any one help me.

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.