1

I am creating some records in my controller but some of them might fail during insert due to duplication, so I use Database.insert(records, false).

It works just fine and ignores records that already exist. But when I use <apex:pageMessages /> in my page, it tells me:

Error: Error while inserting/updating My SObject: Duplicate Entry!

So apex skips the errors, but they are still existing in the execution context, so they are displayed in VF. Any Idea how to keep the insert(x, false) but also use pageMessages? I'm trying to avoid an extra query doublechecking duplicated records.

3

It is not possible to modify the ApexPages.getMessages() collection so you have no choice but to avoid using apex:pageMessages.

Instead of apex:pageMessages you could use apex:pageMessage and supply your own filtered messages from your controller:

public class YourController {

    public class Message {
        public String summary {get; set;}
        public String severity {get; set;}
        Message(String summary, String severity) {
            this.summary = summary;
            this.severity = severity;
        }
    }

    public Message[] getMessages() {
        Message[] messages = new Message[] {};
        for (ApexPages.Message am : ApexPages.getMessages()) {
            if (!am.getSummary().contains('Duplicate Entry')) {
                messages.add(new Message(
                        am.getSummary(),
                        am.getSeverity().name()
                        ));
            }
        }
        return messages;
    }

    ...
}

displaying them like this:

<apex:repeat value="{! messages }" var="m">
    <apex:pageMessage summary="{! m.summary }" severity="{! m.severity }"/>
</apex:repeat>

(Haven't tested this code but have something similar in an Angular app.)

| improve this answer | |
1

Use rendered attribute of apex:pageMessages

<apex:pageMessages rendered="{!if(contains(ERROR MESSAGE,'Duplicate entry'),'false','true')}"/>

You can also create a Boolean variable in controller and make it true/false based on error message in code.

| improve this answer | |
  • 2
    This will hide any other error messages any time there is a "Duplicate entry" error which is bad. Also don't see how you can check the error message content without doing the work in the controller. – Keith C May 2 '17 at 13:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.