0

My lightning-record-edit-form (running in a Digital Experience) scrolls to off the screen text fields that are required but not filled in when the submit button is clicked. But the scrolling doesn't happen for picklist fields. All the fields are using lightning-input-field tied to the SObject field name.

Suggestions for why this difference in behaviour and how to address it?

(I've found and am looking at lightning-record-edit form not taking the focus to the required field and when required fields are missing in lightning-record-edit-form .)

1 Answer 1

0

This is a summary of the workaround from the two posts listed in the question focussing on supporting a required picklist field.

A lightning-input-field does not render picklists using a <select> but instead draws its own list of items to select from. Perhaps this is what stops the standard form required mechanism from working for picklists.

The lightning-record-edit-form onsubmit is never reached if there is a form validation error so the place to put workaround code is in the onclick of the form submit button:

    <lightning-button
        variant="brand"
        type="submit"
        name="submit"
        label="Submit"
        onclick={handleSubmitButton}
    ></lightning-button>

where if an error is found the first error field is scrolled to and the submit is stopped:

const FORM_SELECTOR = 'lightning-record-edit-form';
const FIELD_SELECTOR = 'lightning-input-field';
const ERROR_FIELD_SELECTOR = 'lightning-input-field:has(.slds-has-error)';

    handleSubmitButton(event) {
        const form = this.template.querySelector(FORM_SELECTOR);
        if (form) {

            // Report validity on all fields
            const fields = form.querySelectorAll(FIELD_SELECTOR);
            for (const field of fields) field.reportValidity()

            // Scroll to the first invalid field
            const errorFields = form.querySelectorAll(ERROR_FIELD_SELECTOR);
            if (errorFields.length > 0) {
                const errorField = errorFields[0];
                errorField.scrollIntoView();
                errorField.focus();

                // Stop the submit
                event.preventDefault();
            }
        }
    }

This appears to work, though seems a lot of boilerplate to handle a fairly common case.

You must log in to answer this question.

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