0

I have a situation in my code where I need to validate input fields when a user clicks the "Save" button. I have other commandButtons on the page, one specifically that copies the values of an existing set of fields into a new set that rerenders on the page (the button is called "Add row"). The problem I'm encountering is that if I use the immediate attribute on my commandButton, the values of the old set of fields are not copied. I know this is correct functionality, since the immediate attribute discards values from fields. So when the action of creating a new row/set of fields is done, the values are never set (I set these values in Apex btw).

My question is, is there a way to pass these values into Apex and still ignore validation when clicking on certain commandButtons? Will I have to do validation with JavaScript to bypass this? Or will I have to validate in the Apex code so that validation is only done when accessing the save method? Ideally, I would like to not lose the visual validation (red font and error message) that comes by default on required inputFields.

Here is the code for your reference:

VF Page

<apex:page controller="MultiNewMemberForm_Controller" tabstyle="Case">
   <apex:stylesheet value="{!URLFOR($Resource.bootstrap, '/bootstrap-4.0.0-    alpha.6-dist/css/bootstrap-grid.css')}"/>
   <apex:stylesheet value="{!URLFOR($Resource.MultiNewMemberForm_Styles)}"/>
     <apex:form id="theForm">
   <div class="MultiNewMember">
   <apex:pageBlock title="New Members" >
      <div class="row headers">
         <div class="col ident">
            <h4>Ident</h4>
         </div>
         <div class="col namefield">
         </div>
         <div class="col permissionselector">
            <h4>Permission Set</h4>
         </div>
         <div class="col emailtypedd">
            <h4>Welcome Email</h4>
         </div>
         <div class="col invitationdatepicker">
            <h4>Invitation Date</h4>
         </div>
         <div class="col actionbtn">
            <h4>Action</h4>
         </div>
      </div>
      <apex:repeat value="{!wrappers}" var="wrapper">
         <div class="row fieldrow">
            <div class="col ident">
               <apex:outputText value="{!wrapper.ident}"/>
            </div>
            <div class="col namefield">
               <apex:pageBlockSection columns="1">
                  <apex:inputField value="{!wrapper.curCase.Subject}"     label="Subject"/>
                  <apex:inputField value="{!wrapper.curCase.ContactId}"     label="Name"/>
                  <apex:inputField value="{!wrapper.curCase.Profile__c}"     label="Profile"/>
               </apex:pageBlockSection>
            </div>
            <div class="col permissionselector">
               <apex:inputField value="    {!wrapper.curCase.Permission_Set__c}"/>
            </div>
            <div class="col emailtypedd">
               <apex:inputField value="    {!wrapper.curCase.Welcome_Email__c}"/>
            </div>
            <div class="col invitationdatepicker">
               <apex:inputField value="    {!wrapper.curCase.Invitation_Date__c}"/>
            </div>
            <div class="col actionbtn">
               <apex:commandButton value="Delete" action="{!delWrapper}"     rerender="theForm" immediate="true">
                  <apex:param name="toDelIdent" value="{!wrapper.ident}"     assignTo="{!toDelIdent}"/> 
               </apex:commandButton>
            </div>
         </div>
      </apex:repeat>
      <apex:commandButton value="Add Row" action="{!addRows}"     rerender="theForm">
         <apex:param name="addCount" value="1" assignTo="{!addCount}"/> 
      </apex:commandButton>
      <apex:commandButton value="Add 5 Rows" action="{!addRows}"     rerender="theForm">
         <apex:param name="addCount" value="5" assignTo="{!addCount}"/> 
      </apex:commandButton>
      <apex:commandButton value="Save" action="{!save}"/>
   </apex:pageBlock>
   </div>
 </apex:form>
</apex:page>

Apex Controller

public with sharing class MultiNewMemberForm_Controller {
 @AuraEnabled public List<CaseWrapper> wrappers {get; set;}
 @AuraEnabled public static Integer toDelIdent {get; set;}
 @AuraEnabled public static Integer addCount {get; set;}
 private Integer nextIdent=0;

 public MultiNewMemberForm_Controller()
 {
   wrappers=new List<CaseWrapper>();
   for (Integer idx=0; idx<1; idx++)
   {
     wrappers.add(new CaseWrapper(nextIdent++));
   }
 }

 public void delWrapper()
 {
   Integer toDelPos=-1;
    Integer wrapCount = wrappers.size();
   for (Integer idx=0; idx<wrappers.size(); idx++)
   {
     if (wrappers[idx].ident==toDelIdent)
     {
       toDelPos=idx;
     }
   }

   if (-1!=toDelPos)
   {
     wrappers.remove(toDelPos);
   }

    for (Integer idx=0; idx<wrappers.size(); idx++)
    {
        wrappers[idx].ident=idx + 1;
    }

    nextIdent = wrappers.size();
 }

 public void addRows()
 {
   Integer previousRow = wrappers.size()-1;

   for (Integer idx=0; idx<addCount; idx++)
   {
     wrappers.add(new CaseWrapper(nextIdent++));
     setNewRowValues(previousRow);
   }
 }

 private void setNewRowValues(Integer rowRef)
 {
   Integer lastRow = wrappers.size()-1;
    System.debug('rowRef: ' + rowRef);
    System.debug('lastRow: ' + lastRow);
   wrappers[1].curCase.Subject = wrappers[0].curCase.Subject;
   wrappers.get(lastRow).curCase.Profile__c =     wrappers.get(rowRef).curCase.Profile__c;
   wrappers.get(lastRow).curCase.Permission_Set__c =     wrappers.get(rowRef).curCase.Permission_Set__c;
   wrappers.get(lastRow).curCase.Welcome_Email__c =     wrappers.get(rowRef).curCase.Welcome_Email__c;
   wrappers.get(lastRow).curCase.Invitation_Date__c =     wrappers.get(rowRef).curCase.Invitation_Date__c;
    System.debug('Subject: ' + wrappers[0].curCase.Subject);
 }

 public PageReference save()
 {
   List<Case> caseList=new List<Case>();
   for (CaseWrapper wrap : wrappers)
   {
     caseList.add(wrap.curCase);
   }

   insert caseList;

   return new PageReference('/' +     Schema.getGlobalDescribe().get('Case').getDescribe().getKeyPrefix() + '/o');
 }

 public class CaseWrapper
 {
   public Case curCase {get; private set;}
   public Integer ident {get; private set;}

   public CaseWrapper(Integer inIdent)
   {
      ident=inIdent + 1;
     Id recordTypeId = [Select Id from RecordType where Name = 'New Member'     and SobjectType = 'Case' LIMIT 1].Id;
     curCase = new Case(RecordTypeId = recordTypeId);
   }
}
}
  • Either you can validate fields on the controller side or use JavaScript. – Rohit Mourya Mar 20 '17 at 6:34
0

It seems that the only solution was to use a combination of JavaScript and Apex validation for the form. I had to not use the built-in validation for each inputField. Here is the code in case anybody wants to reference:

<apex:page controller="MultiNewMemberForm_Controller" tabstyle="Case">
   <apex:stylesheet value="{!URLFOR($Resource.bootstrap, '/bootstrap-4.0.0-alpha.6-dist/css/bootstrap-grid.css')}"/>
   <apex:stylesheet value="{!URLFOR($Resource.MultiNewMemberForm_Styles)}"/>
   <apex:includeScript value="{!$Resource.jquery224}"/>

   <script>
  $(function() { requireNewFields(); });

  function requireNewFields() {
     $(".nameInput").each(function() {
        if(this.value == null || this.value == '') {
           this.classList.add("field-required");
        }
     });
     $(".profileDd").each(function() {
        if(this.value == null || this.value == '') {
           $(this).addClass("field-required");
        }
     });
     $(".emailDd").each(function() {
        if(this.value == null || this.value == '') {
           $(this).addClass("field-required");
        }
     });
     $(".dateInput").each(function() {
        if(this.value == null || this.value == '') {
           $(this).addClass("field-required");
        }
     });
  }

  function validateField(obj) {
     if(obj.value != '' && obj.value != null) {
        obj.classList.remove("field-required");
     }
     else if (!obj.classList.contains("field-required")) {
        obj.classList.add("field-required");
     }
  }
   </script>
   <apex:actionStatus id="checkNewFields" onstop="requireNewFields()" />
      <apex:form id="theForm">
         <apex:pagemessages />
         <div class="MultiNewMember">
            <apex:pageblock title="New Members">
               <div class="row headers">
                  <div class="col ident">
                     <h4>Ident</h4>
                  </div>
                  <div class="col namefield">
                  </div>
                  <div class="col permissionselector">
                     <h4>Permission Set</h4>
                  </div>
                  <div class="col emailtypedd">
                     <h4>Welcome Email</h4>
                  </div>
                  <div class="col invitationdatepicker">
                     <h4>Invitation Date</h4>
                  </div>
                  <div class="col actionbtn">
                     <h4>Action</h4>
                  </div>
               </div>
               <apex:repeat value="{!wrappers}" var="wrapper">
                  <div class="row fieldrow">
                     <div class="col ident">
                        <apex:outputtext value="{!wrapper.ident}" />
                     </div>
                     <div class="col namefield">
                        <apex:pageblocksection columns="1">
                           <apex:inputfield value="{!wrapper.curCase.Subject}" label="Subject" />
                           <apex:inputfield value="    {!wrapper.curCase.ContactId}" label="Name" styleclass="nameInput" onblur="validateField(this)" />
                           <apex:inputfield value="{!wrapper.curCase.Profile__c}" label="Profile" styleclass="profileDd" onblur="validateField(this)" />
                        </apex:pageblocksection>
                     </div>
                     <div class="col permissionselector">
                        <apex:inputfield value="{!wrapper.curCase.Permission_Set__c}" styleclass="permissionSet" onblur="validateField(this)" />
                     </div>
                     <div class="col emailtypedd">
                        <apex:inputfield value="{!wrapper.curCase.Welcome_Email__c}" styleclass="emailDd" onblur="validateField(this)" />
                     </div>
                     <div class="col invitationdatepicker">
                        <apex:inputfield value="{!wrapper.curCase.Invitation_Date__c}" styleclass="dateInput" onblur="validateField(this)" />
                     </div>
                     <div class="col actionbtn">
                        <apex:commandbutton value="Delete" action="{!delWrapper}" rerender="theForm" status="checkNewFields">
                           <apex:param name="toDelIdent" value="{!wrapper.ident}" assignto="{!toDelIdent}" />
                        </apex:commandbutton>
                     </div>
                  </div>
               </apex:repeat>
               <apex:commandbutton value="Add Row" action="{!addRows}" rerender="theForm" status="checkNewFields">
                  <apex:param name="addCount" value="1" assignto="{!addCount}" />
               </apex:commandbutton>
               <apex:commandbutton value="Add 5 Rows" action="{!addRows}" rerender="theForm" status="checkNewFields">
                  <apex:param name="addCount" value="5" assignto="{!addCount}" />
               </apex:commandbutton>
               <apex:commandbutton value="Save" action="{!save}" />
            </apex:pageblock>
         </div>
      </apex:form>
</apex:page>

public with sharing class MultiNewMemberForm_Controller {
 public List<CaseWrapper> wrappers {get; set;}
 public static Integer toDelIdent {get; set;}
 public static Integer addCount {get; set;}
 private Integer nextIdent=0;

 public MultiNewMemberForm_Controller()
 {
   wrappers=new List<CaseWrapper>();
   for (Integer idx=0; idx<1; idx++)
   {
     wrappers.add(new CaseWrapper(nextIdent++));
   }
 }

 public void delWrapper()
 {
   Integer toDelPos=-1;
    Integer wrapCount = wrappers.size();
   for (Integer idx=0; idx<wrappers.size(); idx++)
   {
     if (wrappers[idx].ident==toDelIdent)
     {
       toDelPos=idx;
     }
   }

   if (-1!=toDelPos)
   {
     wrappers.remove(toDelPos);
   }

    for (Integer idx=0; idx<wrappers.size(); idx++)
    {
        wrappers[idx].ident=idx + 1;
    }

    nextIdent = wrappers.size();
 }

 public void addRows()
 {
   Integer previousRow = wrappers.size()-1;

   for (Integer idx=0; idx<addCount; idx++)
   {
     wrappers.add(new CaseWrapper(nextIdent++));
     setNewRowValues(previousRow);
   }
 }

 private void setNewRowValues(Integer rowRef)
 {
   Integer lastRow = wrappers.size()-1;
   wrappers[lastRow].curCase.Subject = wrappers[rowRef].curCase.Subject;
   wrappers[lastRow].curCase.Profile__c =     wrappers[rowRef].curCase.Profile__c;
   wrappers[lastRow].curCase.Permission_Set__c = wrappers[rowRef].curCase.Permission_Set__c;
   wrappers[lastRow].curCase.Welcome_Email__c = wrappers[rowRef].curCase.Welcome_Email__c;
   wrappers[lastRow].curCase.Invitation_Date__c =     wrappers[rowRef].curCase.Invitation_Date__c;
 }

 public PageReference save()
 {
    // PageReference saveCompletePage = new PageReference('/' + Schema.getGlobalDescribe().get('Case').getDescribe().getKeyPrefix() + '/o');
    PageReference saveCompletePage = new PageReference('/500?fcf=00Bn0000000uzFI');

    if (verifyFields())
    {
       List<Case> caseList=new List<Case>();
        for (CaseWrapper wrap : wrappers)
        {
        caseList.add(wrap.curCase);
        }

        insert caseList;
    }
    else
    {
        saveCompletePage = new PageReference('/apex/MultiNewMemberForm');
        saveCompletePage.setRedirect(false);
    }

    return saveCompletePage;
 }

 private Boolean verifyFields()
 {
    Boolean formVerified = true;

    for (Integer idx=0; idx<wrappers.size(); idx++)
    {
        Integer lineNumber = idx + 1;
        if (wrappers[idx].curCase.ContactId == null)
        {
            formVerified = false;
            validatorMsgGenerator('Name', lineNumber);
        }

        if (wrappers[idx].curCase.Profile__c == null)
        {
            formVerified = false;
            validatorMsgGenerator('Profile', lineNumber);
        }

        if (wrappers[idx].curCase.Permission_Set__c == null)
        {
            formVerified = false;
            validatorMsgGenerator('Permission Set', lineNumber);
        }

        if (wrappers[idx].curCase.Welcome_Email__c == null)
        {
            formVerified = false;
            validatorMsgGenerator('Welcome Email', lineNumber);
        }

        if (wrappers[idx].curCase.Invitation_Date__c == null)
        {
            formVerified = false;
            validatorMsgGenerator('Invitation Date', lineNumber);
        }
}

    return formVerified;
 }

 private void validatorMsgGenerator(String label, Integer lineNumber)
 {
    String errorMsg = 'Error: ' + label + ' missing on line ' + lineNumber;
    ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR, errorMsg);
   ApexPages.addMessage(myMsg);
 }

 public class CaseWrapper
 {
   public Case curCase {get; private set;}
   public Integer ident {get; private set;}

   public CaseWrapper(Integer inIdent)
   {
      ident=inIdent + 1;
     Id recordTypeId = [Select Id from RecordType where Name = 'New Member' and SobjectType = 'Case' LIMIT 1].Id;
     curCase = new Case(RecordTypeId = recordTypeId);
   }
 }
}

Also, if anybody has a better solution, by all means please post it.

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for?Browse other questions tagged or ask your own question.