0

I have a VF page with a custom controller that allows a user to enter multiple records for a custom object using a Type picklist field. I also have a trigger that populates those values to the parent record (Contact) and only allows 1 of each Type for the child records. If there are duplicates, an error message is thrown.

Currently, the error message shows as an non user-friendly message on the page:

Insert failed. First exception on row 0; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, This Type already exists for this Contact: []
Error is in expression '{!saveType}' in component <apex:commandButton> in page newrectype: Class.NewRecController.saveType: line 46, column 1

An unexpected error has occurred. Your development organization has been notified.

What can I do to get this message to show on the VF page at the top as a simple message like "This Type already Exists"?

My Save method is below and I do have apex:pageMessages in my VF page.

public PageReference saveType() {
        insert listRecType;
        PageReference contRecord = new PageReference('/'+contId);
        contRecord.setRedirect(true);
    return contRecord;
    }

1 Answer 1

2

Use a try-catch block:

public PageReference saveType() {
    try {
        insert listRecType;
    } catch(DmlException e) {
        ApexPages.addMessages(e);
        return null;
    }
    PageReference contRecord = new PageReference('/'+contId);
    contRecord.setRedirect(true);
    return contRecord;
}
1
  • Awesome thanks! The weird thing is that I tried that before and it didn't work. I must have had something wrong in my previous code. Thanks so much!
    – J. Neilan
    Commented Sep 24, 2020 at 14:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .