Tweet |
As we want to replicate the behaviour when using input fields, the first thing to look at is the styling of errors on input fields. Viewing the source of the page shows that the style class of the input is changed to 'error', which places a red border around the input box. This is followed by a div containing the error message:
1 | <div class = "errorMsg" ><strong>Error:</strong> Either email or phone must be defined</div> |
So this should be pretty straightforward to replicate. First, we need a wrapper class where each field can have an associated error message. Note that this is by no means the most efficient or elegant wrapper class for this purpose, but it makes it easier to understand what is happening on the page.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | public class Wrapper { public String FirstName {get; set;} public String MiddleName {get; set;} public String LastName {get; set;} public String Email {get; set;} public String FirstNameError {get; set;} public String MiddleNameError {get; set;} public String LastNameError {get; set;} public String EmailError {get; set;} public Wrapper() { FirstNameError= '' ; MiddleNameError= '' ; LastNameError= '' ; EmailError= '' ; } } |
The validation in this case is that one of first or middle name must be defined, so the validation in the save method is:
1 2 3 4 5 6 7 8 9 | for (Wrapper wrap : wrappers) { if ( (( null ==wrap.FirstName) || (wrap.FirstName.trim().length()== 0 )) && (( null ==wrap.MiddleName) || (wrap.MiddleName.trim().length()== 0 )) ) { wrap.FirstNameError= 'Either first name or middle name must be defined' ; wrap.MiddleNameError= 'Either first name or middle name must be defined' ; } } |
Finally, the Visualforce markup to display the error if necessary:
1 2 3 4 5 6 7 | <apex:column headerValue= "First Name" > <apex:inputText value= "{!wrapper.FirstName}" rendered= "{!LEN(wrapper.FirstNameError)==0}" /> <apex:outputPanel rendered= "{!LEN(wrapper.FirstNameError)!=0}" > <apex:inputText styleClass= "error" value= "{!wrapper.FirstName}" /> <div class = "errorMsg" ><strong>Error:</strong> {!wrapper.FirstNameError}</div> </apex:outputPanel> </apex:column> |
If the length of the error message associated with the wrapper property is zero (i.e. there is no error), then the input component is displayed as normal. However, if the length of the error message is greater than zero, a composite output panel is displayed that styles the input component as an error and the error message is output beneath.
I'm duty bound to point out that using the Salesforce styles 'error' and 'errorMsg' is not officially recommended, as Salesforce may choose to change their styling at any point in time. If I were to use this in a production system, I'd recreate (i.e. copy and paste!) the Salesforce styles in my own CSS include.
And here's the page displaying the error messages in the desired style: