I am getting the error mentioned in subject with below code when execution runs through Else condition without DML statement. I am not getting how to change Pagereference?

Apex Code

 AllocQ= useravailbleQty ;

     If(AllocatedQuantity>=Qty || AllocatedQuantity==null )
     {try {
            upsert (this.Test); 
        } catch (Exception e) {
           // return null;

     else {
         ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'Error: a.    You do not have sufficient allocations to complete this request.');

       // }

        PageReference pageRef = new PageReference('/apex/FormRequestPage?id='+this.test.id);
  • Not clear where you are getting error. Which part of your code?
    – Ratan Paul
    Feb 18, 2016 at 8:52
  • This line is the root cause. PageReference pageRef = new PageReference('/apex/FormRequestPage?id='+this.test.id); id=null coming in URL Feb 18, 2016 at 9:03
  • So what is the this.test is it a record?
    – Ratan Paul
    Feb 18, 2016 at 9:05
  • Check if the Id field is get populated correctly. Also it's not a good idea to use system key words like test for custom implementations
    – highfive
    Feb 18, 2016 at 9:09

2 Answers 2


Looks like Id is null in your else case, so this.test record was not inserted. Record does not have an Id until it is inserted in the database. Make sure you insert your record before that else otherwise your logic won`t work.

  • Yes it is null , I need pagereference only if DML is successful Feb 18, 2016 at 9:50
  • But then you might want to add an if statement before your pageRef to check if that id is not null. Or move pageref just after the upsert, so if it will fail you won`t get there. Feb 18, 2016 at 12:59

Please go on apex page "FormRequestPage" and check the name of standard controller.

Like in your case Suppose your standard controller is Account object then "this.test.id" should be Account rcord Id.

You are passing wrong id here means another object's record id.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .