1

can anyone tell me what's wrong with my code?

public static void mobiFormRecordDtlsUpdate(sObject tplan){

    try{
        sObject updateDtls = tplan;
        if(!string.ISBLANK(tplan.Id) && (tplan != null)) {
            update updateDtls;
        }else if (tplan!= null){ 
            insert updateDtls;
      }
    }catch(Exception ex){
        ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.Error,ex.getMessage());
        ApexPages.addMessage(msg);  

    }

}
  • How often/where do you call this method? – Koen Certyn Oct 6 '17 at 7:49
  • 2
    Nothing at all wrong with it except you can get rid of most of the code in the try block by using single upsert after checking if not null – Eric Oct 6 '17 at 7:56
  • It should not be called within a for loop. – Raul Oct 6 '17 at 8:19
  • 1
    This method is in helper class. whenever am saving/updating this method is called and this method is called from two vf pages. so you guys give me a solution, it would be helpful :) – SFDC Oct 6 '17 at 9:06
4

The code seems alright.

So, to answer your question on bulkification of the code. You can do some changes to pass the parameter as a List and perform the operation.

Two ways you can do is are as follows:

Using Database.upsert with allorNone flag as false, which will ensure the remainder of the DML operation can still succeed even if any one of the record fails.Below is the sample code

public static void mobiFormRecordDtlsUpdate(List<sObject> tplanList){
    Database.SaveResult[] srList = Database.update(tplanList,false);
    for (Integer i =0; i < tplanList.size(); i++)
    if (!srList[i].isSuccess() {
      // log the error somewhere for later admin action - typically to a persistent sobj
    }
}

Using Database.upsert with allorNone flag as true, wherein exception is thrown if the method is not successful. Sample code below

public static void mobiFormRecordDtlsUpdate(List<sObject> tplanList){
    try{
            Database.upsert(tplanList,true); //You can skip passing the 2nd argument as 'true'. As default is true.
    }catch (Exception e) {
        ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.Error,ex.getMessage());
        ApexPages.addMessage(msg);  
    }
}

Now you can call the method by adding it in the sObject List

List<sObject> tplanList = new List<sObject>();
//Add all the sObjects after doing a null check
//Call the method
ClassName.mobiFormRecordDtlsUpdate(tplanList);
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.