function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
PSteves91PSteves91 

Displaying error messages using a custom save method

Hello,

 

Does anyone know how to display error messages to a custom Visualforce page?

Code:

VF:

<apex:page standardController="Opportunity" id="OppItem" extensions="AddNewProducts">
    <apex:form >
        <h1>Opportunity Product Management</h1><br/><hr/><br/><apex:messages /><br/>
        <apex:panelgrid width="100%" columns="2">
            <apex:pageBlock title="Product Search" >
                <apex:pageBlockButtons location="bottom">
                    <apex:commandButton action="{!goToProducts}" value="Normal Product Load"/>
                </apex:pageBlockButtons>
                <apex:pageblockSection title="Opportuntiy Information" columns="1" collapsible="false">
                    <apex:pageblocksectionItem >
                        <apex:outputLabel value="Opportunity Name: "></apex:outputLabel>
                        <apex:outputText value="{!oppName}"></apex:outputText>
                    </apex:pageblocksectionItem>
                    <apex:pageblocksectionItem >
                        <apex:outputLabel value="Close Date: "></apex:outputLabel>
                        <apex:outputText value="{!oppCloseDate}"></apex:outputText>
                    </apex:pageblocksectionItem> 
                    <apex:pageblocksectionItem >
                        <apex:outputLabel value="Contract Renewal Date: "></apex:outputLabel>
                        <apex:outputText value="{!oppRenewDate}"></apex:outputText>
                    </apex:pageblocksectionItem>                 
                </apex:pageblockSection>
                <apex:pageBlockSection title="Use 'TAB' key to search for products." columns="1" collapsible="false">
                    <apex:pageblocksectionItem >
                        <apex:outputLabel value="Product Style#: " tabindex="0"></apex:outputLabel>
                        <apex:inputText id="pstyle" value="{!prodStyleNum}">
                            <apex:actionSupport event="onchange" action="{!productSearch}" reRender="out"/>
                        </apex:inputText>
                    </apex:pageblocksectionItem>
                </apex:pageBlockSection>
            </apex:pageBlock>
            <apex:pageBlock title="Line Item Load" mode="edit">
                <apex:outputPanel id="out">
                   <apex:actionstatus id="status" startText="Fetching data...">
                       <apex:facet name="stop"> 
                               <apex:panelgrid columns="2">
                                   <apex:outputText value="{!actMsg}" /><br/><br/>
                                   <apex:outputLabel value="Quantity: " />
                                   <apex:inputText id="quant" value="{!quantified}" tabindex="1"/>
                                   <apex:outputLabel value="End User Price: "/>
                                   <apex:inputText id="up" value="{!userPrice}" tabindex="2"/>
                                   <apex:outputLabel value="Dealer Price: "/>
                                   <apex:outputText id="dp" value="{!dipper}"/>
                                   <apex:outputLabel value="Date: "/>
                                   <apex:inputText id="sd" value="{!serviceD}" tabindex="3"/>
                                   <apex:outputLabel value="Award Probability: "/>
                                   <apex:inputText id="awardprob" value="{!Award}" tabindex="4">
                                       <apex:actionSupport event="onchange" action="{!save}" focus="pstyle" reRender="OppItem"/>
                                   </apex:inputText>
                               </apex:panelgrid>
                       </apex:facet>
                   </apex:actionstatus>
               </apex:outputPanel>                 
            </apex:pageBlock>
        </apex:panelgrid>
    </apex:form>
    <apex:pageBlock title="Related Opportunity Line Items">
        <apex:pageBlockSection title="Results">
            <apex:outputPanel id="oppStatus">
                <apex:actionstatus id="oliStatus" startText="Fetching records...">
                    <apex:facet name="stop">
                        <apex:pageblockTable value="{!oppLI}" var="oppLineItems" align="center">
                            <apex:column value="{!oppLineItems.PricebookEntry.Name}"/>
                            <apex:column value="{!oppLineItems.Quantity}"/>
                            <apex:column value="{!oppLineItems.UnitPrice}"/>
                            <apex:column value="{!oppLineItems.ServiceDate}"/>
                            <apex:column value="{!oppLineItems.Award_Probability__c}"/>
                        </apex:pageblockTable>
                   </apex:facet>
               </apex:actionstatus>
            </apex:outputPanel>
        </apex:pageBlockSection>  
    </apex:pageBlock>
</apex:page>

 

 

PSteves91PSteves91

Apex:

public class AddNewProducts {

    public List<OpportunityLineItem> oppLI;
    public OpportunityLineItem oli = new OpportunityLineItem();
    public Opportunity opp;
    public String oppName, oppRenewDate, oppCloseDate, pstyle, actMsg, sd;
    public Date ord, ocd;
    public List<Product2> product;
    public PriceBookEntry pbe = new PriceBookEntry();
    public Boolean saveMe;
    public Double awardprob, quant,up, dp;
    public ID pricebookID, opporID; 
   
    //Use the constructor to build a list of related line items
    public AddNewProducts(ApexPages.StandardController controller) {
        Id id = ApexPages.currentPage().getParameters().get('id'); 
       
        oppLI = (id == null) ? new List<OpportunityLineItem>() :
            [SELECT UnitPrice, ServiceDate, Quantity,PricebookEntryId,ListPrice,
                PricebookEntry.Name, PricebookEntry.ProductCode, OpportunityId, Id,
                Award_Probability__c
                FROM OpportunityLineItem WHERE OpportunityId= :id];
               
        opp = (id == null) ? new Opportunity():
            [SELECT Id, Name, Renewal_Contract_Date__c, CloseDate
                FROM Opportunity WHERE Id= :id];
    }//end constructor
   
    public void productSearch()
    {
        actMsg = '';
        if(pstyle != '')
        {
            for(PriceBookEntry pbe:[SELECT Id, UnitPrice, IsActive
                        FROM PriceBookEntry
                         WHERE Pricebook2Id    = '01s800000006gVfAAI'
                         AND Product2.Name =: pstyle])
             {
                
                 if(pbe.IsActive == FALSE){
                        actMsg = 'You cannot add an inactive product.';   
                        saveMe = false;                       
                 }//end if
                 else{
                     actMsg = 'Use the \'Tab\' key to save your product';
                    saveMe = true;
                                                 
                     // add the line item... or not
                    oli.UnitPrice = pbe.UnitPrice; //End User Price
                    oli.PricebookEntryId = pbe.id; //only the standard price book
                    oli.OpportunityId = opp.id;         
                                       
                    dp = oli.UnitPrice; //Dealer Price
                    up = oli.UnitPrice; //End User Price
                    pricebookID = pbe.id;
                 }// end else
            }//end for prod loop
        }//end if
        else{actMsg = 'Please enter a product style to search for.'; saveMe = false; }
        //return null; //end else
    }//end pagereference method
   
    public PageReference save() {
        //we will only save  products to opp line items if product is valid
        if(saveMe == true){
              OpportunityLineItem joint = new OpportunityLineItem();
            //joint.UnitPrice = oli.UnitPrice;
            joint.Quantity = quant;
            joint.TotalPrice = quant*up;
            joint.ServiceDate = Date.valueof(sd);
            joint.Award_Probability__c = awardprob;
            joint.PricebookEntryId = pricebookID;
            joint.OpportunityId = opp.Id;
           
            try{
                   insert (joint);
                   PageReference pageRef = new PageReference('/apex/AddOppLineItems?scontrolCaching=1&id='+opp.Id);
                   pageRef.setRedirect(true);
                   return pageRef;
               }
            catch(DmlException ex){
                ApexPages.addMessages(ex); 
                return null;
               }
        }//end if
        else{
            actMsg = 'Product cannot be saved because its not active or does not have a list price.';
            return null; 
        }//end else 
    }//end method
   
    public PageReference goToProducts(){
        PageReference pageRef = new PageReference('/ui/opportunity/SelectSearch?addTo='+opp.Id+'&retURL=/'+opp.Id);
        pageRef.setRedirect(true);
       
        return pageRef;
    }//end method
   
    public List<OpportunityLineItem> getoppLI() {
       return oppLI;
    }//end method
   
    public List<Product2> getproduct() {
       return product;
    }//end method
   
    public Opportunity getopp(){
        return opp;
    }//end method
   
    public OpportunityLineItem getoli(){
        return oli;
    }//end method
   
    public PriceBookEntry getpbe(){
        return pbe;
    }//end method
   
    public double getuserPrice() {
        //return userPrice;
        return up;
    }//end method
   
    public void setuserPrice(double g) {
        //this.userPrice=g;
        this.up=g;
    }//end method
   
    public double getdipper() {
        return dp;
    }//end method
   
    public void setdipper(double c) {
        this.dp=c;
    }//end method
   
    public String getoppName(){
        oppName = opp.Name;
        return oppName;
    }//end method
   
    public String getoppRenewDate(){
        ord = opp.Renewal_Contract_Date__c;
        oppRenewDate = String.valueOf(ord);
        return oppRenewDate;
    }//end method
   
    public String getoppCloseDate(){
        ocd = opp.CloseDate;
        oppCloseDate = String.valueOf(ocd);
        return oppCloseDate;
    }//end method

    public string getprodStyleNum() {       
        return pstyle;
    }//end method
   
    public string getactMsg() {       
        return actMsg;
    }//end method
   
    public void setprodStyleNum(string s) {       
        this.pstyle=s;   
    }//end method
   
    public double getquantified() {
        return quant;
    }//end method
   
    public void setquantified(double v) {    
        this.quant=v;
    }//end method
   
    public String getserviceD() {
        sd = oppCloseDate;
        return sd;
    }//end method
   
    public void setserviceD(String d) {       
        this.sd=d;   
    }//end method
   
    public double getAward() {
        return awardprob;
    }//end method
   
    public void setAward(double r) {       
        this.awardprob=r;   
    }//end method
   
}//end class

PSteves91PSteves91

 

What I am trying to accomplish is to enable a user to load products to an opportunity by allowing them to search for a product name... if they knowthe product name. If they don't, then they will be able to add products to an opportunity the standard way.

 

There are validation rules that correctly fire when I try to add an opportunityLineItem... I see the error messages in the log, but I need to display that message to the user.

 

For example:

   The user searches for product name '00715' by entering that name into the search field.

   Once the user presses the 'Tab' key, the controller searches the database. If it finds the product, it returns the required fields for inserting an opportunitylineitem into the database.

   There are several custom fields with validation rules on the opportunitylineitem, one of which is the Award Probabilty. The user must enter either 100, 75, 50, 25, 0.

   The insert is triggered after the user tabs off of the Award Probability field. If I leave this field blank, I should see an error.

 

Again, in the debug logs I see:

Please specify a probability of either 0, 25, 50, 75, or 100

 Any help would be very much appreciated.

PSteves91PSteves91
I tried using <apex:pageMessages> and <apex:messages> with no luck. I understand that I need to rerender the page, but I am not sure how to do that by having the user tab through the form.
PSteves91PSteves91

ok... so I've cleaned up my code a bit, but I am still not able to get the validation errors to the page.

public class AddNewProducts {
    public List<OpportunityLineItem> oppLI;
    public Opportunity opp;
    public String oppName, oppRenewDate, oppCloseDate, pstyle, actMsg, sd;
    public Date ord, ocd;
    public Boolean saveMe;
    public Double awardprob, quant,up, dp;
    public ID pricebookID, opporID; 
   
    //Use the constructor to build a list of related line items
    public AddNewProducts() {
        Id id = ApexPages.currentPage().getParameters().get('id'); 
       
        oppLI = (id == null) ? new List<OpportunityLineItem>() :
            [SELECT UnitPrice, ServiceDate, Quantity,PricebookEntryId,ListPrice,
                PricebookEntry.Name, PricebookEntry.ProductCode, OpportunityId, Id,
                Award_Probability__c
                FROM OpportunityLineItem WHERE OpportunityId= :id];
               
        opp = (id == null) ? new Opportunity():
            [SELECT Id, Name, Renewal_Contract_Date__c, CloseDate
                FROM Opportunity WHERE Id= :id];
    }//end constructor
   
    public void productSearch()
    {
        actMsg = '';
        if(pstyle != '')
        {
            for(PriceBookEntry pbe:[SELECT Id, UnitPrice, IsActive
                        FROM PriceBookEntry
                         WHERE Pricebook2Id    = '01s800000006gVfAAI'
                         AND Product2.Name =: pstyle])
             {
                
                 if(pbe.IsActive == FALSE){
                        actMsg = 'You cannot add an inactive product.';   
                        saveMe = false;                       
                 }//end if
                 else{
                     actMsg = 'Use the \'Tab\' key to save your product';
                    saveMe = true;
                                                       
                    dp = pbe.UnitPrice; //Dealer Price
                    up = pbe.UnitPrice; //End User Price
                    pricebookID = pbe.id;
                    awardprob = 0;
                 }// end else
            }//end for prod loop
        }//end if
        else{actMsg = 'Please enter a product style to search for.'; saveMe = false; }
    }//end pagereference method
   
    public PageReference saver() {
        //we will only save  products to opp line items if product is valid
        if(saveMe == true){
              OpportunityLineItem joint = new OpportunityLineItem();
            joint.Quantity = quant;
            joint.TotalPrice = quant*up;
            joint.ServiceDate = Date.valueof(sd);
            joint.Award_Probability__c = awardprob;
            joint.PricebookEntryId = pricebookID;
            joint.OpportunityId = opp.Id;
           
            try{
                   insert (joint);
                   PageReference pageRef = new PageReference('/apex/AddOppLineItems?scontrolCaching=1&id='+opp.Id);
                   pageRef.setRedirect(true);
                   return pageRef;
               }
            catch(DmlException ex){
                ApexPages.addMessages(ex); 
                return null;
               }
        }//end if
        else{
            actMsg = 'Product cannot be saved because its not active or does not have a list price.';
            return null; 
        }//end else 
    }//end method
   
    public PageReference goToProducts(){
        PageReference pageRef = new PageReference('/ui/opportunity/SelectSearch?addTo='+opp.Id+'&retURL=/'+opp.Id);
        pageRef.setRedirect(true);
       
        return pageRef;
    }//end method
   
    public List<OpportunityLineItem> getoppLI() {
       return oppLI;
    }//end method
   
    public Opportunity getopp(){
        return opp;
    }//end method
   
    public double getuserPrice() {
        //return userPrice;
        return up;
    }//end method
   
    public void setuserPrice(double g) {
        //this.userPrice=g;
        this.up=g;
    }//end method
   
    public double getdipper() {
        return dp;
    }//end method
   
    public String getoppName(){
        oppName = opp.Name;
        return oppName;
    }//end method
   
    public String getoppRenewDate(){
        ord = opp.Renewal_Contract_Date__c;
        oppRenewDate = String.valueOf(ord);
        return oppRenewDate;
    }//end method
   
    public String getoppCloseDate(){
        ocd = opp.CloseDate;
        oppCloseDate = String.valueOf(ocd);
        return oppCloseDate;
    }//end method

    public string getprodStyleNum() {       
        return pstyle;
    }//end method
   
    public string getactMsg() {       
        return actMsg;
    }//end method
   
    public void setprodStyleNum(string s) {       
        this.pstyle=s;   
    }//end method
   
    public double getquantified() {
        return quant;
    }//end method
   
    public void setquantified(double v) {    
        this.quant=v;
    }//end method
   
    public String getserviceD() {
        sd = oppCloseDate;
        return sd;
    }//end method
   
    public void setserviceD(String d) {       
        this.sd=d;   
    }//end method
   
    public double getAward() {
        return awardprob;
    }//end method
   
    public void setAward(double r) {       
        this.awardprob=r;   
    }//end method
   
}//end class