Tuesday, December 20, 2016

Visualforce - Beyond Basics Series 33 - Show error for any Input fields

Is there any standard way for displaying error message for a field ?

When a controller/extension (Or) Trigger uses addError method in Sobject field, it will be displayed under the field in the Visualforce Page.


What about non-sobject field ?

But, if the input field has binding through a non-sobject variable, then there's no standard way of displaying the error message under  the field.


How to show them ?

The error message has to be displayed manually.

Where is the code ?

I have illustrated by simply adding error message in a map in Controller, Then, in Visualforce page, if there's an error, the error message will be displayed.
public class testcls33_20122016 {
Opportunity opp;
public Map<String, String> errorMap {get; set;}
public testcls33_20122016(ApexPages.StandardController sc) {
opp = (Opportunity) sc.getRecord();
errorMap = new Map<String, String> { 'Name' => '' };
}
public void save() {
errorMap.put('Name', 'Organization locked. Sorry for inconvinience');
}
}
view raw gistfile1.txt hosted with ❤ by GitHub
<apex:page standardController="Opportunity" extensions="testcls33_20122016">
<apex:form>
<!-- Input Form -->
<apex:outputLabel value="Name "/>
<apex:inputText value="{!Opportunity.Name}"/>
<!-- Field Error - for Name -->
<apex:outputText value="{!errorMap['Name']}" style="color:red;"
rendered="{!errorMap['Name'] != null}"/>
<br/>
<!-- Button -->
<apex:commandButton value="Save" action="{!save}"/>
</apex:form>
</apex:page>
view raw gistfile1.txt hosted with ❤ by GitHub


Any screenshot ?


Walk through in video ?





No comments:

Post a Comment

Thanks for reading my blog !