function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
SirishaMSirishaM 

How to display the Trigger error messages on Visual force page

Hi,

I wrote a "before insert"  trigger for finding duplicates in my custom object and I also wrote a VF page for the same object.
My VF page has a custom extension.

Even though trigger does not allow the duplicates but it does not display the error message on VF page
.Do I need to change anything in page to display the errors ?

Thanks,
Sirisha
mtbclimbermtbclimber
With this trigger:

Trigger:
trigger test on Account (before insert) {
    trigger.new[0].name.addError('Nice try');
}

The following page will show the expected error on save:

Page:
<apex:page standardController="Account">
    <apex:form >
        <apex:pageBlock >
            <apex:pageMessages />
            <apex:pageblockButtons >
                <apex:commandButton action="{!save}" value="Save"/>
            </apex:pageblockButtons>
            <apex:pageBlockSection >
                <apex:inputField value="{!account.name}"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

As will this page/apex controller on save:

Code:
<apex:page controller="AccountCon" tabStyle="Account">
    <apex:form >
        <apex:pageBlock >
            <apex:pageMessages />
            <apex:pageblockButtons >
                <apex:commandButton action="{!save}" value="Save"/>
            </apex:pageblockButtons>
            <apex:pageBlockSection >
                <apex:inputField value="{!account.name}"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Controller:

public class AccountCon {

public Account account {
get {
if (account == null) Account = new Account(Name='new account');
return account;
}
set;
}


public PageReference save() {
try {
insert account;
} catch (DMLException e) {
ApexPages.addMessages(e);
return null;
}
return null;
}

}

 As Jill mentions in this thread there is additional documentation you can refer to around the ApexPages methods, Messages class and error handling.



SirishaMSirishaM
Hi mtbclimber,

Thanks a lot for replying .. I was using the

asst.addError('Duplicate Records'); where asst is the object name..

After changing it to Trigger.new[0].name.... its working now.

Thanks again!!!

Sirisha


mtbclimbermtbclimber
No problem.  BTW, that example works with object level errors to, i.e.:

Trigger:
trigger test on Account (before insert) {
    trigger.new[0].addError('Nice try');
}

 
Just so anyone reading this thread doesn't get the wrong idea, I used trigger.new[0] here since this was merely an example of how to surface an error managed by a trigger within a visualforce page.

Please do NOT misconstrue this as something you should pattern your trigger code after. trigger.new is a collection of the records passed into the trigger by the calling action which can *often* include multiple records.

Trigger authors should be evaluating every record sent into the request (not just the first one) for possible action.   You may be thinking, "my rules need only apply to users in the UI anyway" but even if your users don't use the API or the import wizard (today) we are introducing more and more capabilities within the application to operate on multiple records - take the new mass/inline editing capabilities of list views in Summer '08 for example.

If triggers are the right level for your validation then you need to consider all entry points. If the UI is the right level and you are using visualforce then put your validations in your controller.  Note: you can use the same addError() mechanisms on sobjects in your controller as I have highlighted above in the trigger's new sobject.
GoForceGoGoForceGo
The errors are shown on top of the page.

How do you show errors right next to the field?



beener3beener3
Hi,

I'm also trying to get my error's next to the field. do you have a solution for this?
would you please provide some code?

Thanks in advance

Ben
mtbclimbermtbclimber
The same way you would do this in a trigger:

Code:
public Account account { get; set; }

public void save() {

   if(account.name == 'Poon') {
       account.name.addError('What kind of name is that?, try again');
   }
}


Message Edited by mtbclimber on 01-03-2009 11:59 AM
GoForceGoGoForceGo
I meant the configured validation rule errors - they always show up on top of the page.



beener3beener3
Hi,

I'm sorry I wasn't clear. I'll try to better explain myself.
I have a VF page table in which some columns use Inputfields .

When I save (using the method update). I get some DML exceptions for the rows that are not valid (in other words, custom validation rules do not allow the data to be entered).

I would like the errors to appear next to the field (preferable) or at least next to the row (less preferable) of the record which invalidates the rule.

Since I don't know how to address a field on the VF page,
I thought of a layman's solution: I would add a column "Errors", in which the error for that column would be written. but how do I write to the column, in the correct row from the Controller?

BTW, please note that I'm not talking about Apex Trigger's errors. I'm talking about validation errors.

Thanks

Ben
mtbclimbermtbclimber
The usual mechanism for this, adding the caught exception to the messages collection doesn't seem to be keeping the row/field level information right now. We're investigating the cause for this.  In the mean time, can you use the StandardSetController here?  The save mechanism on that does keep the validation errors' field/row level information intact.  For example, put a validation rule on contact.title and violate it in this page:

Code:
<apex:page standardController="Contact" recordSetVar="contacts">
    <apex:form >
        <apex:pageBlock >
            <apex:pageblockButtons >
                <apex:commandButton value="Save" action="{!save}"/>
            </apex:pageblockButtons>
            <apex:pageMessages />
            <apex:pageBlockTable value="{!contacts}" var="c">
                <apex:column headerValue="Last Name">
                    <apex:inputField value="{!c.lastname}"/>
                </apex:column>
                <apex:column headerValue="Title">
                    <apex:inputField value="{!c.title}"/>
                </apex:column>
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>

 And you should see the error bind to the right row/field.

This will work with a StandardSetController constructed and proxied from a custom (apex) controller as well.

If your object isn't supported by the StandardSetController or if this doesn't work you could create a wrapper class that has members for your sobject and it's respective saveResult which would also allow for partial processing support since the save method on standardsetcontroller is all-or-nothing.

Hope this helps.  I'll post back here when we have an update on the issue of maintaining this information from a non-standard controller save.

mtbclimbermtbclimber
We have a fix queued up for the Spring '09 release to keep the row/field level intact for the DML operations in Apex. 
vanessenvanessen

for my case it does not appear...i am using a custom VF page like this:

 

<apex:page standardcontroller="Concurrence__c" extensions="AP05ConcurrenceController" recordsetVar="conc">

<apex:form >
        <apex:pageBlock title="Nouvelles concurrences" >            
            <apex:pageMessages />
            <apex:Messages />
            ......

 

My trigger call a class having the following code:

 

if((concurrenceList[i].Opportunite__c == Oid) && (oppAccUploadedSet.get(Oid) != null )
                     &&(oppAccUploadedSet.get(Oid).contains(concurrenceList[i].Compte__c)))
                {
                    System.debug('## Duplicate batch upload having account ID: '+ concurrenceList[i].Compte__c +' for opportunity ID:<<<<<<<<<<  ' + Oid);                
                    concurrenceList[i].Compte__c.adderror(system.Label.error2);
                }

 

the underlined line is the code which generates the error ,but in my page the error display like this:

 

Insert failed. First exception on row 0; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, Aucune Concurrence créée - Concurrence existant: [Compte__c]

Une erreur d'installation inattendue s'est produite. Votre organisation de développement a été notifiée.