Handling Missing Required Fields in LWC Component

errorjavascriptlightning-web-componentstoast

There is a LWC that has been built for custom approval cases on the opportunity object. Recently we have made a view fields on the opportunity object as required fields. There are some older records that don't have these fields populated and is preventing users from submitting for approval on the record.

Currently, there is no indication for the users that the missing required fields is what's preventing them from submitting the case. The user is clicking the submit button but it just sits there.

I would like to provide them with some toast event that will give some indication what the root cause is because sometimes a little handholding is required.

I can see the error logged in the console when submitting a case without the required fields but I'm not too experienced with JavaScript and after some digging and frustration I'm still unsure if I have it correct.

Below is the error I'm seeing in the console when trying to submit approval and there are missing required fields. The error is showing only one of the fields that is missing, probably by design, as it will throw an error on the first field it encounters.

enter image description here

Is there a way to throw a toast event with a general message when this type of error is encountered? I would like to provide the user with more information such as which field is missing but it looks like I will only be able to provide one field on each attempt that fails.

This is the current template that I have inside of my submit event:

   .catch(error => {
      console.error(error);
      const e = new ShowToastEvent({
        title: 'Error Occurred Submitting For Approval',
        message: 'One or more of the following fields are missing: Deal Type, Industry',
        variant: 'error',
        mode: 'dismissable',
      });
      this.dispatchEvent(e);
  1. I don't even know if this is implemented correctly
  2. Is there a way to pull the errors that are shown when trying to save the record when the required fields are missing and display them in the toast event?

Best Answer

error.message gives the message:

.catch(error => {
  console.error(error);
  const e = new ShowToastEvent({
    title: 'Error Occurred Submitting For Approval',
    message: error.message,
    variant: 'error',
    mode: 'dismissable',
  });
  this.dispatchEvent(e);

You could clean it up by parsing everything after the ;, of course.

This could also be made better by using the allOrNone DML option while writing your Apex code so that you can parse all the errors.