0

here is the modified code which i'm trying. In my code i'm trying to using validtion rule based on condition Competitor_C.Machine_c=='other' and Description__c==null==============>"error msg" *Problem:*Machine field was not capturing value"other" .any suggestions ?

vf:
<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:messages />
    <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(){
      try{
      Competitor__c comp=new Competitor__c();
      if (comp.Competitor_Machine__c == 'other' && comp.Competitor_Machine_Description__c == null)
      {
          ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR, 'Something went wrong...') );

          // Return null so the page won't redirect
          return null;
      }
      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));

    }



}
6
  • Do you want to do the validation front-end using javascript/jquery or on the server side with APEX? Dec 19, 2013 at 5:10
  • on the UI it has to display error messgae.
    – user4902
    Dec 19, 2013 at 5:14
  • Why not use salesforce validation ruled ? Dec 19, 2013 at 6:19
  • 3
    It certainly should work, why don't you show us what you have tried for a validation rule. This should be easily accomplished through a validation rule, no need for all this. Dec 19, 2013 at 12:39
  • 2
    @user4902 can I suggest that you instead reword your question to request for help with creating a validation rule, specify the objects and fields and the logic rule that you want to evaluate. It is important that you are familiar with the subject matter before you embark in looking for a solution so that you can understand what you are looking for in detail and how to apply the answer to a number of scenarios in future.
    – Bartley
    Dec 19, 2013 at 13:21

2 Answers 2

6

First, add a <apex:pageMessages /> tag to your VF page so that the user will see the messages.

Second, create a validation rule on your object to enforce this requirement.

Validation Rule on Competitor__c object

if machine picklist=='other' and description==null, then this should fire an error message.

Error Condition Formula

ISPICKVAL(Machine__c, 'Other') && ISBLANK(Description__c)

Error Message

A description is required when 'Other' is selected.
2
  • Hi Mark,i followed the steps mentioned by you.But this doesn't capture the Machine value as other
    – user4902
    Dec 20, 2013 at 5:42
  • 1
    @user4902 your question states Competitor_C.Machine_c=='other' so I do not understand your reply. Please edit your original question to clarify what you are asking for the community to help you with.
    – Mark Pond
    Dec 26, 2013 at 19:07
4

If you really must use custom validation (although I don't see why regular validation rules would not work), you can use the following approach.

Add pageMessages component at the beginning of your form:

<apex:form id="form">

    <apex:pageMessages />
    ...
    <!-- your components here -->
</apex:form>


And finally, implement validation logic in your Save handler:

//method invoked to save and return to the original Opportunity record Page
public PageReference Save(){
  try{
      // *** Add custom validation here ***
      if (something == 'other' && somethingElse == null)
      {
          ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR, 'Something went wrong...') );

          // Return null so the page won't redirect
          return null;
      }
      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));
}
2
  • 3
    Or, to highlight a specific field, use addError instead.
    – sfdcfox
    Dec 19, 2013 at 15:21
  • @dino.yup i did the same but still the field was not capturing the value.
    – user4902
    Dec 20, 2013 at 5:53

You must log in to answer this question.

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