1

My requirement is , I wanna add an error message to field seems like standard error only using apex , I don't wanna make them required. Should be like:

enter image description here

Update:

Apex Class:

public class MyController1 {
    Account account;
    public PageReference save() {
        try {
            update account;
        } catch (DmlException ex) {
            ApexPages.addMessages(ex);
        }
        return null;
    }
    public String getName() {
        return 'MyController';
    }
    public Account getAccount() {
        if (account == null) account = [select id, name, numberofemployees, numberoflocations__c from Account where id =: ApexPages.currentPage().getParameters().get('id')];
        return account;
    }
}

Page

<apex:page controller="MyController1" tabStyle="Account">
    <apex:messages />
    <apex:form >
        <apex:pageBlock title="Hello {!$User.FirstName}!">
        This is your new page for the {!name} controller. <br/>
        You are viewing the {!account.name} account.

        <p>Number of Locations: <apex:inputField value="{!account.NumberofLocations__c}"
            id="Location_validation"/>
        (Enter an alphabetic character here, then click save to see what happens.) </p>

        <p>Number of Employees: <apex:inputField value="{!account.NumberOfEmployees}"
            id="Employee_validation"/>
        (Enter an alphabetic character here, then click save to see what happens.) </p>
            <p />
        <apex:commandButton action="{!save}" value="Save"/>
         <p />
        </apex:pageBlock>
    </apex:form>
</apex:page>
8
  • have you tried with field.addError method developer.salesforce.com/docs/atlas.en-us.apexcode.meta/… ? Commented May 6, 2016 at 5:00
  • Hello Ratan, Actually, I have tried but I don't want an error of that type I need to add an error that seems like, the error come when we create an Account record nd forgot to enter 'Account Name'. Commented May 6, 2016 at 5:03
  • using addError method you can add the error message to specific field you just need to rerender that field in vf page.. Commented May 6, 2016 at 5:05
  • will you please code it for me ... cause I've tried lots of code... Commented May 6, 2016 at 5:08
  • Please Post the code that what you have tried. So that we can say what to modify in it.... Commented May 6, 2016 at 5:08

2 Answers 2

4

This is the code that will work with addError methdod

account.NumberOfEmployees.addError('You must enter a value.'); this way you can add error message on field level ..

Page

<apex:page controller="AddErrorCtrl" tabStyle="Account">
    <apex:messages />
    <apex:form >
        <apex:pageBlock title="Hello {!$User.FirstName}!" id="pblock">
        This is your new page for the {!name} controller. <br/>
        You are viewing the {!account.name} account.

        <p>Number of Locations: <apex:inputField value="{!account.NumberofLocations__c}"
            id="Location_validation"/>
        (Enter an alphabetic character here, then click save to see what happens.) </p>

        <p>Number of Employees: <apex:inputField value="{!account.NumberOfEmployees}"
            id="Employee_validation"/>
        (Enter an alphabetic character here, then click save to see what happens.) </p>
            <p />
        <apex:commandButton action="{!save}" value="Save" rerender="pblock"/>
         <p />
        </apex:pageBlock>
    </apex:form>
</apex:page>

Controller

public class AddErrorCtrl {
    Account account;

    public PageReference save() {
        if(account.NumberOfEmployees == null)
        {
            account.NumberOfEmployees.addError('You must enter a value.');
            return null;
        }
        if(account.NumberofLocations__c == null)
        {
            account.NumberofLocations__c.addError('You must enter a value.');
            return null;
        }
        try{
            update account;
        }
        catch(DmlException ex){
            ApexPages.addMessages(ex);
        }
        return null;
    }

    public String getName() {
        return 'MyController';
    }

    public Account getAccount() {
        if(account == null)
        account = [select id, name, numberofemployees, numberoflocations__c from Account
        where id = :ApexPages.currentPage().getParameters().get('id')];
        return account;

    }
}

Updates: Validate fields using Jquery

<apex:page controller="AddErrorCtrl" tabStyle="Account">
    <style>
    .error{ border:1px solid red !important;}
    .messageClass{color: red; display: inline; float: right;position: absolute;margin: 3px;font-size:11px}
    </style>
    <apex:messages />
    <apex:form >
        <apex:pageBlock title="Hello {!$User.FirstName}!" id="pblock">
        This is your new page for the {!name} controller. <br/>
        You are viewing the {!account.name} account.

        <p>
            Number of Locations: <apex:inputText value="{!account.NumberofLocations__c}" id="Location_validation"/>
        </p>
        <p>
            Number of Employees: <apex:inputText value="{!account.NumberOfEmployees}" id="Employee_validation"/>
        </p>
        <p>
            <input type="button" value=" Save " onclick="validateFields();" class="btn"/>
            <apex:actionFunction action="{!save}" name="SaveAF" rerender="pblock" />
        </p>
        </apex:pageBlock>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.js" ></script>
        <script>
            var isValidate = true;
            function validateFields()
            {
                var varFieldlist = ["Location_validation",  "Employee_validation"];
                validateRequiredFields(varFieldlist);
                if(isValidate)
                {
                    SaveAF();
                }
            }
            function validateRequiredFields(arrayFields){
                $.each( arrayFields, function( i, val ) {
                    if($('[id$='+val+']').val() =='')
                    {
                        if(!$('[id$='+val+']').hasClass('error'))
                        {
                            $('[id$='+val+']').addClass('error');
                            $('[id$='+val+']').after("<p class='messageClass' id="+'__'+val+"> Required </p>");
                            isValidate = false;
                        }
                    }
                    else if($('[id$='+val+']').hasClass('error'))
                    {
                        $('[id$='+val+']').removeClass('error');
                        $('[id$=__'+val+']' ).remove();
                        isValidate = true;
                    }
                });
            }
        </script>
    </apex:form>
</apex:page>

enter image description here

12
  • I wanna use <apex:inputText>....not the <apex:inputField>. Commented May 6, 2016 at 5:47
  • @AkshAy using inputText you can't do that, inorder to achieve this you need ajavascript else just go with apex:inputField.. Any reason for not using apex:inputField Commented May 6, 2016 at 5:50
  • @Ratan....will you please help me out with this Please And ya there is reason that's why m still trying Commented May 6, 2016 at 5:53
  • yes coz there is a requirment .... for that case Commented May 6, 2016 at 5:58
  • 1
    Sure Ratan your r really very helpFull thanks once again :) Commented May 6, 2016 at 7:29
1
account.NumberOfEmployees.addError('You must enter a value.'); 

this way you can add error message on field level ..as per your requirement

0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.