[SalesForce] Display error message on particular field in VF page

In our VisualForce page, we are displaying the fields dynamically based on the user's selected fields in setting page and the order of fields displayed changes based on user's wish, which we are displaying dynamically like I said via Apex Repeat function. Now any of the fields which is required and if it is null should through an error, so far the error's are displayed at the top.

I want to display error message in the particular field.

could anyone sort this out.

enter image description here

In save() method am querying the fields which I gave required in my setting page and looping through those if its null am through the error

relatedTplan- sObject

if(mffList.size()>0)
            for(string st : mffList){
                if(string.valueOf(relatedTplan.get(st)) == null){   

                    relatedTplan.getSObject(st).addError('error message');
                    return; 
                    //relatedTplan.addError('Please fill the required fields.');  
                } 
            }

In my vf page

<apex:inputfield value="{!relatedTplan[updateObj.MFF_FieldName]}" />

No Error message displayed

Best Answer

You need to use addError on the field in question, which also implies that you must directly bind the field to an apex:inputField. Here's a trivial example:

<apex:page controller="q204269">
    <apex:form>
        <apex:pageBlock>
            <apex:pageBlockSection columns="1">
                <apex:inputField value="{!record.Name}" />
            </apex:pageBlockSection>
            <apex:pageBlockButtons>
                <apex:commandButton action="{!save}" value="Save" />
            </apex:pageBlockButtons>
        </apex:pageBlock>
    </apex:form>
</apex:page>

public class q204269 {
    public Account record { get; set; }
    public q204269() {
        record = new Account();
    }
    public void save() {
        if(record.Name == null) {
            record.Name.addError('You must enter a value!');
        }
    }
}

If the field is not directly bound to a visible input, it will appear at the top of the page, as you've observed.

Related Topic