0

I want to show apex:pageMessage when validation error occured. In the below code i called save method from the javascript. previusly save method called from action function. after changing code based on requirement apex page messages are not displaying. How can i show page messages in vf page..? vf page:

<apex:page Standardcontroller="CF_Sections__c" extensions="CF_SectionEditController" >
    <apex:pagemessages id="errorMsg"/>
    <apex:form >
        <apex:outputPanel >
        <apex:actionFunction name="savesection" action="{!saveMethod}" reRender="errorMsg"/>
        <apex:actionFunction name="remcountry" action="{!emptyRemCountry}" reRender="pageblock"/>
        <apex:pageblock mode="detail" id="pageblock" >
            <apex:pageblockbuttons >
                <apex:commandbutton value="Save" action="{!removeCountries}" reRender="saveoutput"/> 
                <apex:commandbutton value="Save & New" action="{!saveNewmethod}"/>
                <apex:commandbutton value="Cancel" action="{!Cancel}"/>
            </apex:pageblockbuttons>
            <apex:pageblocksection showheader="true" columns="2" id="pb" title="Section Details">
                <apex:inputfield value="{!section.CF_Section_Name__c}" required="true" style="width:400px;height:30px;"/>
                <apex:inputfield value="{!section.CF_Content_Available__c}" required="false"/>
                <apex:pageBlockSectionItem >
                    <apex:outputPanel id="levelLabel" style="float:right;" layout="none" >
                        <apex:outputLabel value="Section Level" />
                    </apex:outputPanel>
                    <apex:outputpanel style="float:right;" layout="none">
                        <apex:actionRegion > 
                            <apex:inputfield value="{!section.CF_Section_Level__c}" required="true" id="level">
                                <apex:actionSupport event="onchange"  reRender="o1,pb1,app,spp,psvLabel,secname,scname,asd" />
                            </apex:inputfield>
                        </apex:actionRegion>
                    </apex:outputpanel>   
                </apex:pageBlockSectionItem>
                <apex:outputtext rendered="{!isnew}"/>
                <apex:inputfield value="{!section.CF_Is_Removed__c}" required="false" rendered="{!!isnew}"/>
                <apex:inputfield value="{!section.CF_Section_Order__c}"  required="true"/>
                <apex:pageBlockSectionItem >
                    <apex:outputLabel value="Approver "  styleClass="labelCol first last" for="v2" style="font-weight:bold;font-size:11px"/>
                    <apex:outputtext value="{!Approver}" id="v2" />  
                </apex:pageBlockSectionItem>
            </apex:pageblocksection>
            <apex:pageBlocksection id="o1" columns="1"  > 
                <apex:pageBlockSectionItem >
                    <apex:outputPanel id="psLabel" style="float:right;padding-left: 1px;" layout="none" >
                        <apex:outputLabel value="Parent Section" rendered="{!section.CF_Section_Level__c == 'Level 2' || section.CF_Section_Level__c == 'Level 3'}" />
                    </apex:outputPanel>
                    <apex:actionRegion >
                        <apex:outputPanel id="psvLabel" >
                            <apex:inputfield value="{!section.CF_Parent_Section__c}" required="true" rendered="{!section.CF_Section_Level__c == 'Level 2' || section.CF_Section_Level__c == 'Level 3'}">   
                            <apex:actionsupport event="onchange" action="{!changesecName}" rerender="scname,asd,tr,secname,v3"/>
                            </apex:inputfield>                    
                        </apex:outputPanel>
                    </apex:actionRegion>
                </apex:pageBlockSectionItem>
                       </apex:pageBlocksection> 
                  <apex:pageBlocksection id="asd">       
                <apex:pageblocksectionitem >
                    <apex:outputPanel id="scname" style="float:right;" layout="none" >
                        <apex:outputLabel value="Parent Section Name" rendered="{!(section.CF_Section_Level__c == 'Level 2' || section.CF_Section_Level__c == 'Level 3') && section.CF_Parent_Section__c!=null}"/>
                    </apex:outputPanel>
                    <apex:outputpanel style="float:right;" layout="none" id="tr"> 
                            <apex:outputtext value="{!secName}" id="secname" rendered="{!section.CF_Section_Level__c == 'Level 2' || section.CF_Section_Level__c == 'Level 3' }"/>
                    </apex:outputpanel>    
                </apex:pageblocksectionitem>            
            </apex:pageBlocksection> 
            <apex:pageblocksection title="Review Details">
                <apex:pageBlockSectionItem >
                    <apex:outputPanel style="float:right;" layout="none" >
                        <apex:outputLabel value="Review Period (Days)" styleClass="labelCol first last"   style="font-weight:bold;font-size:11px;padding-left: 62px;">
                            &nbsp;<apex:image value="/img/alohaSkin/help_orange.png" title="Next Review Date = Last Review Date + Review Period(in days). Reminder will be sent 7 days before next review date" style="width:13px"/>
                        </apex:outputLabel>
                        <apex:inputfield value="{!section.CF_Review_Period__c}" style="width:150px"/>
                    </apex:outputpanel>
                </apex:pageBlockSectionItem>
                <apex:pageBlockSectionItem >
                    <apex:outputPanel style="float:right;" layout="none" >
                        <apex:outputlabel value="Escalation Period (Days)"  styleClass="labelCol first last"  style="font-weight:bold;font-size:11px;padding-left: 75px;" >
                            &nbsp;<apex:image value="/img/alohaSkin/help_orange.png" title="Escalation Date = Last reviewed date + Escalation Period(in days). Escalation email will be sent on the day of escalation." style="width:13px"/>
                        </apex:outputlabel>
                        <apex:inputfield value="{!section.CF_Escalation_Period__c}" required="false"/>
                    </apex:outputpanel>
                </apex:pageBlockSectionItem>
            </apex:pageblocksection>
            <apex:pageblocksection title="Country Details">
                <apex:pageBlockSectionItem >
                    <apex:outputLabel value="Countries " title="Select Ctrl+Shift+End/Home to select all  countries" styleClass="labelCol first last" for="v3" style="font-weight:bold;font-size:11px"/>
                    <c:MultiselectPicklist leftLabel="Available Countries"
                                            leftOption="{!allcountries}"
                                            rightLabel="Selected Countries"
                                            rightOption="{!selectedCountries}"
                                            width="150px" id="v3" size="5" />
                </apex:pageBlockSectionItem>
            </apex:pageblocksection>
        </apex:pageblock>
        </apex:outputPanel>
        <apex:outputPanel id="saveoutput">
            <apex:outputpanel rendered="{!isValidated}">
                <script>
                    var removcountry='{!removeCountry}';
                    if(removcountry!='Null'&& removcountry!=''){
                        var message="Removing country from this section will remove it from all child sections of this section too. Do you want to proceed..?";
                        if (confirm(message) == true) {
                            savesection();
                        } else {
                            remcountry();
                        }
                    }
                    else {
                        savesection();
                    }
                </script>
            </apex:outputpanel>
        </apex:outputPanel>
    </apex:form>
</apex:page>

controller:

public with sharing class CF_SectionEditController {

    public SelectOption[]        selectedCountries      { get; set; }
    public String                Approver               { get; set; } 
    public String                Country                { get; set; }
    public SelectOption[]        allCountries           { get; set; } 
    public CF_Sections__c        section                { get; set; }
    public Map<String,String>    mapLabelvalue;                       // Used for storing the Country ID and Name
    public set<String>           labels;
    public boolean               isnew                   { get; set; }
    public List<CF_GroupList__c> grpList;
    Id                           sectionid;
    Integer                      SectionOrder;
    Boolean                      parentRender;
    List<GroupMember>            loggedinUserGroup;
    Map<String,String>           mapApproverQueue;
    public string                secName                { get; set; }
    public string                removeCountry          { get; set; }
    public list<string>          oldcountries           { get; set; }
    public boolean               isValidated            { get; set; }

    public CF_SectionEditController(ApexPages.StandardController controller) {

        mapLabelvalue     = new Map<String,String>();
        loggedinUserGroup = new List<GroupMember>();
        labels            = new set<String>();  
        allcountries      = new List<SelectOption>();
        selectedcountries = new List<SelectOption>();
        sectionid         = ApexPages.currentPage().getParameters().get('id');
        Set<String> uniqueApprovers  = new Set<String>();
        List<String> approverGroupList = new List<String>();
        oldcountries = new List<String>();
        removeCountry = '';
        errorMessage = '';
        isValidated = false;
        mapApproverQueue  = new Map<String,String> ();

        //Fetches all the Groups from the Custom Setting 
        grpList = CF_Utils.getGroupfromCustomSetting();

        for ( CF_GroupList__c g : grpList ) { 
            uniqueApprovers.add(g.Approver_Group__c);
        }
        approverGroupList.addall(uniqueApprovers);
        loggedinUserGroup = CF_Utils.checkLoggedinUserinaGroup(approverGroupList);


        //Fetches all the Section Labels available
        for(CF_Sections__c sec: [select id,CF_Section_Level__c,CF_Section_Order__c,CF_Section_Label__c,CF_Section_Name__c FROM CF_Sections__c]) {
            labels.add(sec.CF_Section_Label__c);
        }


        // IF new , instance for Section is created. 
        //If Edit, Queries the Related Section record for editing
        section = (sectionid == null) ? new  CF_Sections__c() : CF_DataAccessLayer.getRelatedSection(sectionid);
        if(sectionid == null){
        isnew=true;
        }
        else
        secName=section.CF_Parent_Section__r.CF_Section_Name__c;

         if(loggedinUserGroup.size()>0 )
            Approver = loggedinUserGroup[0].Group.name;
         else
           Approver= section.CF_approver__C;

        //Fetches all the Countries from the Country Object for the users to select in a drop down list 
        List<Country__c> Countries;
        if(section.CF_Section_Level__c=='Level 1' || section.CF_Section_Level__c==null || sectionid==null ) {
            Countries = CF_DataAccessLayer.getCountries();
        }
        else {
            CF_Sections__c sect=[Select ID, Name from CF_Sections__c where id=:sectionid limit 1];
            countries = [Select Id, name from Country__c where id in  :section.CF_Parent_section__r.CF_Country__c.split(';')];
        }

         // Stores the country list fetched as a picklist 
        for ( Country__c c : Countries ) {
           If(section.id==null || (!string.isempty(section.CF_Country__c) && !(section.CF_Country__c.contains(c.id))))
            allCountries.add(new SelectOption(c.id,c.Name));
            mapLabelvalue.put(c.Id,c.Name);
        }
         If(section.id != null) 
         Country= countryDisplay();
         system.debug(Country);

        //Fetches all the existing countries
        If(Section.id != null) {
            IF(!string.isempty(section.CF_Country__c)) {
                For(String s:section.CF_Country__c.split(';'))
                { 
                  oldcountries.add(s);
                }
            }
        }

        If(Section.id != null) {
            IF(!string.isempty(section.CF_Country__c)) {
            selectedCountries.clear();
                For(String s:section.CF_Country__c.split(';'))
                { 
                  if(mapLabelvalue.get(s)!=null)
                  selectedCountries.add(new SelectOption(s,mapLabelvalue.get(s))); 
                }
            }
             SectionOrder=  Integer.valueof(section.CF_Section_Order__C);              
        }


    }//End of constructor

    public PageReference savemethod() {
            Boolean updated = saveoperation();
            If(updated == true){
                return new PageReference('/' + section.Id);
            }
            else
                 return null;
    }

    public PageReference saveNewmethod() {
        Boolean updated = saveoperation();
        If(updated == true) {
        section = new  CF_Sections__c() ;
            Pagereference p = new Pagereference('/apex/CF_SectionEditPage');
            p.setredirect(true);
            return p; 
        }
        else 
            return null; 


     }


    public Boolean saveoperation() {

     Boolean updated = false;
     Country='';
     //Adds the selected approvers to the Approver field in Section
     If(loggedinUserGroup.size()>0)
        section.CF_Approver__c =loggedinUserGroup[0].Group.developername;

     else if(String.isempty(section.CF_Approver__c))
        section.CF_Approver__c = '';
     If(section.id != null || String.isnotempty(section.CF_Country__c)) {
           section.CF_Country__c = '';
     }

        // adds the selected countries to the Country Field in Section
        For(Integer i=0;i<selectedcountries.size();i++) {
            if(String.isempty(section.CF_Country__c))
                section.CF_Country__c = '';

                section.CF_Country__c = section.CF_Country__c + selectedcountries[i].getValue() +  ';';

        }

        Country = countryDisplay(); 


        if(selectedcountries.size() >0) {
            section.CF_Country__c =   section.CF_Country__c.removeend(';');

        }    

        If(string.isempty(section.CF_Country__c)) 
        {
          ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,CF_Constants.CF_SECTION_COUNTRY_REQUIRED));
          return null; 
        }

        else IF( (section.CF_Section_Level__c == CF_Constants.CF_SECTION_LEVEL2 ||section.CF_Section_Level__c == CF_Constants.CF_SECTION_LEVEL3) && string.isempty(section.CF_Parent_Section__c))
        {
         ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,CF_Constants.CF_SECTION_PARENT_REQUIRED ));
         return null;
        }

        else IF((section.CF_Escalation_Period__c != null && Section.CF_Review_Period__c ==null) ||  (section.CF_Escalation_Period__c == null && Section.CF_Review_Period__c !=null)) {
         ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,CF_Constants.CF_ESC_REV_NULL));
         return null;
        }

        else IF(string.isempty(section.CF_Approver__c))
        {
         ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,CF_Constants.CF_SECTION_APPROVER_REQUIRED ));
         return null;
        }
        // Checks for the duplicate label for a new record
        else If( labels.contains( computeLabel()) && (sectionid == null  || section.CF_Section_order__C != SectionOrder)) {
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,CF_Constants.CF_SECTION_LABEL_ALREADY_EXISTS));
            return null;
        }
        else if(section.CF_Is_Removed__C == true &&checkforremoved() ==false )
        {

                  ApexPages.addMessage(new ApexPages.message(ApexPages.severity.Error,'Please mark all the child sections as removed'));
                   return null;

        }

        else 
        {   
            IF(section.CF_Section_Level__C == CF_Constants.CF_SECTION_LEVEL1)
                section.CF_Parent_Section__C = null;
            upsert section;
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Successfully'));
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.Confirm,CF_Constants.CF_SECTION_SAVE));           
            updated =true;

        }

       return updated;
     }

    public String computeLabel() {

        CF_Sections__c sect = new  CF_Sections__c();
        String lab;
        try{

        If(Section.CF_Section_Level__c != CF_Constants.CF_SECTION_LEVEL1)
           sect =CF_DataAccessLayer.getRelatedSection(section.CF_Parent_Section__C);

        IF(section.CF_Section_Level__c == CF_Constants.CF_SECTION_LEVEL1) {
            lab = String.valueof(section.CF_Section_Order__c) +'.0';
        }
        else IF(section.CF_Section_Level__c ==  CF_Constants.CF_SECTION_LEVEL2) {
           lab = String.valueof(sect.CF_Section_Order__c) +'.'+ String.valueof(section.CF_Section_Order__c);
        }  
        else {        
            IF( section.CF_Section_Level__c == CF_Constants.CF_SECTION_LEVEL3) {
                IF(sect.CF_Section_Level__c == CF_Constants.CF_SECTION_LEVEL1)
                   lab = String.valueof(sect.CF_Section_Order__c) +'.0.'+String.valueof(section.CF_Section_Order__c );
                else
                   lab = String.valueof(sect.CF_Parent_Section__r.CF_Section_Order__c) + '.'+String.valueof(sect.CF_Section_Order__c )+'.'+String.valueof(section.CF_Section_Order__c );
            } 
            else
                lab = '0';        
        }
        return lab;
        }
        catch(exception e) { return null;}
    }

    public PageReference cancel() { 
        if(section.id == null)  
            return new PageReference('/'+ CF_Sections__c.sObjectType.getDescribe().getKeyPrefix());
        else
            return new PageReference('/' + section.Id);
    }

    public pagereference cancelView() {
         return new PageReference('/'+ CF_Sections__c.sObjectType.getDescribe().getKeyPrefix());    
    }


    public String countryDisplay() {
       String ctry='';
       if(section.CF_Country__c != null && section.CF_Country__c !='') {
            For(String s : section.CF_Country__c.split(';')) {
                if(mapLabelvalue.get(s) != null)
                ctry = ctry + mapLabelvalue.get(s) + ';';
            }

            if(section.CF_Country__c.split(';').size()>0)
                ctry= ctry.removeend(';');
            return ctry;
       }
       else 
            return null;
    }
    public void changesecName(){
        if(section.CF_Parent_Section__c!=null){
            CF_Sections__c sec=[select CF_Section_Name__c, CF_Country__c from CF_Sections__c where id=:section.CF_Parent_Section__c ];
            SecName=sec.CF_Section_Name__c;

            allCountries.clear();
            selectedCountries.clear();
            List<country__c> parentseccoun=[Select Id, name from Country__c where id in : sec.CF_Country__c.split(';')];
            for(Country__c con: parentseccoun){
                allCountries.add(new SelectOption(con.id,con.name));
            }
        }

    }

    public Boolean checkforremoved() {

        Boolean removed= true;
        if(section.id != null) {
            List<CF_Sections__c> sectionlist = new List<CF_Sections__c>();
            IF(Section.CF_Section_Level__C ==  CF_Constants.CF_SECTION_LEVEL1) {
                sectionlist  = CF_DataAccessLayer.getRelatedSectionforLevel1(section.id);
                List<CF_Sections__c> childlist = new List<CF_Sections__c>();
                IF(sectionlist.size() > 0)
                    For(integer i=0;i<sectionlist.size();i++)  
                        if(sectionlist[i].Parent_Levels__r.size()>0)     
                            childlist.addall(sectionlist[i].Parent_Levels__r);
                IF(sectionlist.size()>0 || childlist.size()>0)
                    removed = false;
             }
             else if(Section.CF_Section_Level__C ==  CF_Constants.CF_SECTION_LEVEL2)
             {    
                sectionlist  = CF_DataAccessLayer.getRelatedSectionforLevel2(section.id);
                if(sectionlist.size() >0)
                removed = false;
             }       
        }
        return removed;
    }

    public void removeCountries() {
        isValidated = true;
        string selCountrySec= '';
        if(section.id!=null){

            // Fetches the selected countries in picklist
            if(!selectedCountries.isEmpty()){
                Boolean Start = true;
                for(Selectoption strOpt : selectedCountries) {
                    if(Start) {
                        selCountrySec = strOpt.getvalue();
                        Start = false;
                    } else {               
                        selCountrySec = selCountrySec + ';' + strOpt.getvalue();
                    }
                }
            }

            // Finding the removed countries by comparing existing countries and selected countries  
            if(section.CF_Section_Level__c==CF_Constants.CF_Section_LEVEL1 || section.CF_Section_Level__c==CF_Constants.CF_Section_LEVEL2){
                for(String oldId :oldcountries){
                    if(selCountrySec!= null && selCountrySec!=''){
                        if(selCountrySec.contains(oldId)==false){
                            removeCountry += oldId;
                        }
                    }
                }
            }
        }//end if
    }//end removeCountries

    public void emptyRemCountry() {
        removeCountry ='';
    }
}
2
  • You sure your control is entering into any of those if else conditions for ApexPages.addMessage? Try adding a System.debug inside if block. Nov 30, 2015 at 10:59
  • Yes, sure control is entering into pagemessage, and it's working now. added page message tag inside form. Nov 30, 2015 at 11:02

1 Answer 1

0

use <apex:pagemessages id="errorMsg"/> inside apex form or pageblock

You must log in to answer this question.

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