2

Here is an apex code which has been wrritten based on some condition.This is working fine for our requiremnet.But when we add some logic to display error message,it is not fire an error message on click of save button.

Visualforce

<apex:page standardcontroller="Competitor__c" extensions="ctrlCompetitor" language="{!$CurrentPage.parameters.lang}" action="{!init}">
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"/>  
    <apex:sectionheader title="{!$ObjectType.Competitor__c.label} Edit" subtitle="{!IF(ISNULL(Competitor__c.name), 'New Competitor',Competitor__c.name)}"/>
    <script>    
    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:pageMessages id="mymsg" />**
    <apex:form >   
        <apex:pageblock mode="edit" title="{!$ObjectType.Competitor__c.label} Edit">
            <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>

</apex:page>

================================================================================

public with sharing class ctrlCompetitor { 



    public static Integer flag=0; 

 public Competitor__c cc{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,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(){

      Competitor__c comp=new Competitor__c();
      //List<Competitor__c> checklist=new List<Competitor__c>();
      //checklist=[select Competitor_Machine__C,Competitor_Machine_Description__c from Competitor__c];

      if (comp.Competitor_Machine__C == 'other' && comp.Competitor_Machine_Description__c == null)
      {
              ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'If other is selected please enter a description');//Same old drama 
ApexPages.addMessage(myMsg);
          // Return null so the page won't redirect
        return null;
      }
      try{
      if(ApexPages.currentPage().getParameters().get('Name')!=null)
      {

      insert cc;
      }
      else 
      update cc;
      }
      catch(Exception e){}        
      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));

    }



}
1
  • 1
    Do you have (a) message compontent(s) on your Visualforce page ? Commented Jan 6, 2014 at 8:21

2 Answers 2

4

When this happens to me it is usually one of two things:

(1) I don't have an component on my page

(2) I am using a rerender attribute on my or that is submitting the form and I haven't added the id of my component, which means that the error is being swallowed and the page just looks like its refreshing - I've explained this point in more detail at:

http://bobbuzzard.blogspot.co.uk/2012/08/the-importance-of-page-messages.html

However, looking at your code I don't think any pagemessages will be added - this section:

     Competitor__c comp=new Competitor__c();
      //List<Competitor__c> checklist=new List<Competitor__c>();
      //checklist=[select Competitor_Machine__C,Competitor_Machine_Description__c from Competitor__c];

      if (comp.Competitor_Machine__C == 'other' && comp.Competitor_Machine_Description__c == null)
      {
              ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'If other is selected please enter a description');//Same old drama 
ApexPages.addMessage(myMsg);
          // Return null so the page won't redirect
        return null;
      }

instantiates a new, empty Competitor__c() record, so none of the fields will be populated, which means you won't add a message. Your code then tries to insert/update the record:

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

      insert cc;
      }
      else 
      update cc;
      }
      catch(Exception e){}        
      return new PageReference('/'+ApexPages.currentPage().getParameters().get('retURL').substring(1,16));
    }

However, if an exception occurs you can't redirect the user to a new pagereference as you are using a rerender attribute on the commandbutton, so I'd expect the page to simply refresh if an exception is thrown.

8
  • yup i tried.it doesn't work . may be i go wrong some where could you please check the above code
    – user4902
    Commented Jan 6, 2014 at 10:00
  • <apex:pageMessages id="msgs" /> <apex:commandButton value="Save" action="{!Save}" rerender="msgs"/>
    – user4902
    Commented Jan 6, 2014 at 10:00
  • Answer updated. Commented Jan 6, 2014 at 11:22
  • but i need to add a validation to this code.When we click on save it has to check whether competitor machine=other and competitor descr==null then it has to fir an error msg. haw can i code this in to the exsiting code
    – user4902
    Commented Jan 6, 2014 at 11:39
  • Don't instantiate a new Competitor__c - use the one that is bound to the inputs on the Visualforce page. Commented Jan 6, 2014 at 12:01
2

Try to rerender parent component of apex:pageMessages. See following example

Visualforce page:

<apex:page controller="pageMessagesController">
    <apex:form >
        <apex:pageBlock id="msgs">
            <apex:pageMessages />

            <apex:pageBlockButtons >
                <apex:commandButton value="Save" action="{!Save}" rerender="msgs"/>
            </apex:pageBlockButtons>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Controller:

public class pageMessagesController {

    public void save() {
        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'This is apex:pageMessages'));
    }
}

Instead of apex:pageBlock you can use components you are using.

4
  • this also doesn't work
    – user4902
    Commented Jan 6, 2014 at 10:54
  • Can you share your visualforce code? Commented Jan 6, 2014 at 10:55
  • mail id? above was the code
    – user4902
    Commented Jan 6, 2014 at 10:57
  • I have edited sample code in my example. Please check that. Commented Jan 6, 2014 at 11:14

You must log in to answer this question.

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