Error on Save: How tonform the User in a Controller Extension

controller-extensionerror-messagesvisualforce

I have built a controller extension for use in a custom NewQuote page (see image below).

  • The controller extension initializes a number of custom fields with data from the Opportunity.
  • The Quote object has a validation rule that prohibits setting both of the checkboxes highlighted in the image. The validation rule works as expected in the standard edit page (see second image). It also works in the NewQuote page except that the error message is not displayed. The new quote is simply not saved and the NewQuote page remains displayed. If the validation rule is inactivated, everything works just fine.
  • There is a related problem: upon successful execution of the standard controller Save() method, the controller extension copies all OpportunityLineItems and appends them to the Quote. There also the question is: how to get the error message displayed (see code of the Save() method below).

This is the code of my controller extension save() method:

public System.PageReference save() { 

    PageReference redir = null;

    // call standard controller to save the quote and give us the page reference 
    redir = stdController.save();
    if (redir == null) {
        // an error occurred: how do I tell the User, 
        //                    or make the standard controller tell the user?
        //                    I know (in the current case) that it is the validation rule on the two checkboxes that prevents saving

        return null;
    }

    // handle line items:
    try {
        setQuoteIds(lineItems, stdController.getId());  // set QuoteIds
        database.insert(lineItems);                     // insert
    } catch (System.DmlException e) {
        // same problem here: no message is displayed on the page, but the insert is not done / is rolled back 
        //                    how to make a message appear on the custom page???
        System.ApexPages.addMessages(e);   
        return null;             
    }

    // redirect to where standard controller tells us
    return redir;
}

NewQuote Custom Page

Edit Quote Page with Validation Error Display

Best Answer

Try the below code for error messages

catch (System.DmlException e) {
    System.ApexPages.addMessage(new ApexPages.message(ApexPages.severity.Error,e.getMessage()));
    return null;             
}

Also on your visualforce page make sure to use the below tag

<apex:pageMessages id="showmsg"></apex:pageMessages>


                    
Related Topic