2

we designed a vf page called competitor.Competitor has validation rule.This is running fine in the back end.But the validation error message has not been displayed on the page. Here the controller :

public with sharing class ctrlCompetitor { 


    public static Integer flag=0; 

 public Competitor__c cc{get;set;} 
 public String customerId{get;set;}
    public Competitor__c cc1=new Competitor__c(); 
    public List<Competitor__c> listComptr=new List<Competitor__c>();  
    public ctrlCompetitor(){}

    //extension invoked to pre-populate the Name parameter
    public ctrlCompetitor(ApexPages.StandardController stdController) {  
     try{
       cc=new Competitor__c();      
       cc = (Competitor__c)stdController.getRecord(); 
       if(ApexPages.currentPage().getParameters().get('Name')!=null)
         cc.Name=ApexPages.currentPage().getParameters().get('Name'); 
     }
     catch(Exception e){System.debug(e.getMessage());}
    }

   //cache all the primary competitors for the particular opportunity
   public void init(){      
    listComptr=[SELECT Id,Name,Primary_Competitor__c from Competitor__c where 
                                 Opportunity__r.Id =:ApexPages.currentPage().getParameters().get('retURL').substring(1,16) AND Primary_Competitor__c=true];     
   }

   //method to uncheck the primary competitor for other competitor records     
   @RemoteAction
   public static void checkPrimaryComp(String oppId){              
    Map<Id,Competitor__c> compMap=new Map<Id,Competitor__c>([SELECT Id,Name,Primary_Competitor__c from Competitor__c where Opportunity__r.Id =: 
                                         oppId.substring(1,16)]);     
     for(Competitor__c comp : compMap.values()){         
        comp.Primary_Competitor__c=false;}       
     update compMap.values();      
   }

   //invoked to check for the first primary competitor
   @RemoteAction
   public static String checkFirstPrimaryComp(String oppId){
   List<Competitor__c> listTemp=[SELECT Id,Name,Primary_Competitor__c from Competitor__c where 
                                 Opportunity__r.Id =:oppId.substring(1,16) AND Primary_Competitor__c=true];
       if(listTemp.size()==0){return 'true';}
       else{return 'false';}   

   }

   //method invoked on update of Competitor records
   public void onUpdatePrimaryComp(){
   try{
     if(Trigger.IsUpdate && !Trigger.IsInsert && flag==0){
     flag++;
     SET<Id> oppIds=new SET<Id>();          
     for(Sobject sobj: Trigger.new){
        Competitor__c cc1=(Competitor__c)sobj;
        oppIds.add(cc1.Opportunity__c);             
     }       
     List<Competitor__c> listTemp=[SELECT Id,Name,Primary_Competitor__c,Competitor_Machine__c,Competitor_Machine_Description__c,Opportunity__r.Id from Competitor__c where Opportunity__r.Id in : oppIds AND
                               Primary_Competitor__c=true] ;        
     if(listTemp.size()!=0){
         for(Sobject sobj: Trigger.new){
             Competitor__c cc1=(Competitor__c)sobj;

             if(cc1.Primary_Competitor__c==true){
                 for(Integer i=0;i<listTemp.size();i++){
                     if(listTemp.get(i).Opportunity__r.Id == cc1.Opportunity__c){
                       listTemp.get(i).Primary_Competitor__c=false;}
                 }
             }
          } 

       update listTemp;}     
     }}
     catch(Exception e){


     System.debug('==Exception Message==='+e.getMessage());}
   }

    //method invoked to save and return to the original Opportunity record Page
    public PageReference Save(){

    try{
      if(ApexPages.currentPage().getParameters().get('Name')!=null)
      {

      insert cc;
      }
      else 
      update cc;
      }
       catch(DMLException e){
       ApexPages.Message msg = new ApexPages.Message(Apexpages.Severity.ERROR, e.getdmlMessage(0) );
ApexPages.addMessage(msg);


     }     
      return new PageReference('/'+ApexPages.currentPage().getParameters().get('retURL').substring(1,16));
    }

    //method is invoked on click of CANCEL button
    public PageReference Cancel(){
    try{
    if(ApexPages.currentPage().getParameters().get('Name')==null){
        if(listComptr.get(0).primary_Competitor__c==false){
            listComptr.get(0).primary_Competitor__c=true;
        }
    }
      update listComptr;
    }
    catch(Exception e){
      System.debug('==Exception Message==='+e.getMessage());
    }
     return new PageReference('/'+ApexPages.currentPage().getParameters().get('retURL').substring(1,16));

    }


}

Visualforce Page:

function chngPrimComp(cmp,val){        
    var c; 
    var flag=0;
    if(cmp.checked==false && flag!=0){            
        alert('{!$Label.msgCantUnchk}');
        cmp.checked=true;
        flag++;
    } 
    if(cmp.checked==true && flag==0){              
        ctrlCompetitor.checkFirstPrimaryComp('{!$CurrentPage.parameters.retURL}',function(result, event){
            if(event.status){            
                if(result=='false'){                    
                c=confirm('{!$Label.msgPrmryCompCnfrm}');
                    if(c==true){
                    flag++;                               
                        ctrlCompetitor.checkPrimaryComp('{!$CurrentPage.parameters.retURL}',function(result, event){
                            if(event.status){}
                            if(event.exception){}
                        });
                    }
                    else if(c==false){
                    cmp.checked=false;
                    }
                }
            }   
        });
    }        
}
</script>

<apex:form >   
    <apex:pageblock mode="edit"  title="{!$ObjectType.Competitor__c.label} Edit" >
 <apex:PageMessages />
        <apex:pageblockbuttons > 
            <apex:commandButton value="Save" action="{!Save}" />                               
            <apex:commandbutton value="Cancel" action="{!Cancel}"/>
        </apex:pageblockbuttons>
        <apex:outputpanel >
            <apex:pageblocksection title="Information" showheader="true" columns="2">
                    <apex:inputfield id="oppid" value="{!Competitor__c.Opportunity__c}" required="true"/>
                    <apex:inputfield value="{!Competitor__c.Amount__c}" required="false"/>
                    <apex:inputfield value="{!Competitor__c.Competitor_Name__c}" required="true"/>                 
                    <apex:inputfield id="chkbox" value="{!Competitor__c.Primary_Competitor__c}" required="false" onchange="chngPrimComp(this,this.value);" />                                               
                    <apex:inputfield value="{!Competitor__c.Competitor_Machine__c}" required="false"/>                                                
                    <apex:pageblocksectionitem />
                    <apex:inputfield value="{!Competitor__c.Competitor_Machine_Description__c}" required="false"/>
         <apex:pageblocksectionitem />
            </apex:pageblocksection>
                <apex:pageblocksection title="Competitor Strengths / Weaknesses" showheader="true" columns="2">
                    <apex:inputfield value="{!Competitor__c.Competitors_Strength__c}" required="false"/>
                    <apex:inputfield value="{!Competitor__c.Competitors_Weakness__c}" required="false"/>
                    <apex:inputfield value="{!Competitor__c.Competitive_Situation__c}" required="false"/>
     <apex:pageblocksectionitem />
            </apex:pageblocksection>
                    <apex:pageblocksection title="System Information" showheader="true" columns="2">
                    <apex:inputfield value="{!Competitor__c.Name}" required="true"/>                        
             </apex:pageblocksection>
        </apex:outputpanel>
    </apex:pageblock>       
</apex:form>

3 Answers 3

3

I'm guessing that the error should be surfaced by the save action method:

//method invoked to save and return to the original Opportunity record Page
public PageReference Save(){

try{
  if(ApexPages.currentPage().getParameters().get('Name')!=null)
  {

  insert cc;
  }
  else 
  update cc;
  }
   catch(DMLException e){
   ApexPages.Message msg = new ApexPages.Message(Apexpages.Severity.ERROR, e.getdmlMessage(0) );
ApexPages.addMessage(msg);

 }     
  return new PageReference('/'+ApexPages.currentPage().getParameters().get('retURL').substring(1,16));
}

The problem is that although you are adding a message to the page via ApexPages.addMessage(), in the final line you always redirect the user to a different page based on the retUrl parameter on the URL:

 return new PageReference('/'+ApexPages.currentPage().getParameters().get('retURL').substring(1,16));

Unless the page that you redirect to is a Visualforce page and uses the same controller as your current page, a client side redirect will take place which will drop any error information.

Given that you are trapping the validation failure as a DML exception and presumably want to give the user a chance to fix the problem, I would think it would make more sense to stay on the page and display the error to the user, in which case you should only redirect them to the retUrl page upon success:

//method invoked to save and return to the original Opportunity record Page
public PageReference Save(){

PageReference pr=null; // refresh the page by default

try{
  if (null==cc.id)
  {

  insert cc;
  }
  else 
  update cc;
  // set the resulting page reference to redirect to the retUrl on success
  pr = new PageReference('/'+ApexPages.currentPage().getParameters().get('retURL').substring(1,16));
  }
   catch(DMLException e){
   ApexPages.Message msg = new ApexPages.Message(Apexpages.Severity.ERROR, e.getdmlMessage(0) );
ApexPages.addMessage(msg);

 }     
  return pr;
}
3
  • 1
    Awesome. Thank you. No words to express gratitude for u r work.
    – user4902
    Commented Jan 9, 2014 at 8:32
  • Thank you.i copied the same .now it displays new error. if Primary competitor=true and if i click on save it says Error: Record ID: cannot specify Id in an insert call
    – user4902
    Commented Jan 9, 2014 at 8:38
  • I've updated the answer to check if the id is defined and based on that use an insert/update as appropriate. Commented Jan 9, 2014 at 8:42
0

I have very simple validation rule on opportunity product "UnitPrice<>ListPrice"

Basically, users cannot modify the price. This works great for standard "Add Products" button. But via VF page, the ListPrice is null, atleast when insert call is made. Hence it never fires the validation rule.

Here is snippet

sObj = new OpportunityLineItem(OpportunityId=Id, PricebookEntryId=key, UnitPrice=1000, Quantity=qty, Description=desc);

sObjs.add(sObj);

try{ insert sObjs; } catch (System.DmlException e) { ApexPages.Message msg = new ApexPages.Message(Apexpages.Severity.ERROR, e.getdmlMessage(0) ); ApexPages.addMessage(msg); }


ListPrice is derived from pricebookentry. What are my options here?

regards Mitesh

0
0

Never mind, I figured it out. Instead of ListPrice, I can use

UnitPrice <> PricebookEntry.UnitPrice

You must log in to answer this question.

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