0

I have a LWC that calls an APEX class to query Contacts related to an account and display them. The LWC allows the user to update displayed fields. I am able to successfully call the APEX, display the records, and update the records. I am having trouble updating the displayed values when they change.

Here is the HTML:

<template>

    <!-- Card -->
    <lightning-card title="Contact Information" value={recordId} icon-name="standard:contact">

        <!-- Actions -->
        <div slot="actions">
            <lightning-button-icon icon-name="utility:add" variant="bare" alternative-text="New Contact" size="Medium"
                onclick={addContact}>
            </lightning-button-icon>
        </div>

        <template if:true={contacts.data}>

            <ul class="slds-has-dividers_around-space" style="margin-right: 5px; margin-left: 5px;">

                <template for:each={contacts.data} for:item="contact">

                    <li class="slds-item" key={contact.Id}>

                        <!-- Contact Card  -->
                        <lightning-card title={contact.Name} icon-name="standard:client">

                            <!-- Contact Card Actions -->
                            <div slot="actions">
                                <lightning-button-icon icon-name="utility:edit_form" variant="bare"
                                    alternative-text="Update" onclick={openmodal} value={contact.Id}
                                    data-id={contact.Id} target="_blank">
                                </lightning-button-icon>
                            </div>

                            <!-- Display Fields -->
                            <div class="slds-region_narrow">
                                <dl class="slds-dl_horizontal">
                                    <!-- Title -->
                                    <dt class="slds-dl_horizontal__label slds-text-title">Title:</dt>
                                    <dd class="slds-dl_horizontal__detail">
                                        {contact.Title}
                                    </dd>
                                    <!-- Email -->
                                    <dt class="slds-dl_horizontal__label slds-text-title">Email:</dt>
                                    <dd class="slds-dl_horizontal__detail">
                                        {contact.Email}
                                    </dd>
                                    <!-- Mobile Phone -->
                                    <dt class="slds-dl_horizontal__label slds-text-title">Mobile Phone:</dt>
                                    <dd class="slds-dl_horizontal__detail">
                                        <lightning-click-to-dial value={contact.MobilePhone} record-id={contact.Id}>
                                            {contact.MobilePhone}
                                        </lightning-click-to-dial>
                                    </dd>
                                </dl>
                            </div>
                        </lightning-card>

                    </li>

                </template>

            </ul>

        </template>

    </lightning-card>

    <!-- Modal Edit 'Contact' -->
    <template if:true={openmodel}>

        <div class="demo-only" style="height: 640px;">

            <section role="dialog" tabindex="-1" aria-labelledby="modal-heading-01" aria-modal="true"
                aria-describedby="modal-content-id-1" class="slds-modal slds-fade-in-open">

                <div class="slds-modal__container">

                    <header class="slds-modal__header">

                        <!-- TITLE -->
                        <h2 id="modal-heading-01" class="slds-text-heading_medium slds-hyphenate">
                            {fullName}
                        </h2>

                    </header>

                    <!-- BODY -->
                    <div class="slds-modal__content slds-p-around_medium" id="modal-content-id-1">

                        <!-- CREATE CONTACT -->
                        <lightning-card>

                            <lightning-record-edit-form record-id={recordEditId} object-api-name="Contact">

                                <!-- Lightning Messages Display -->
                                <lightning-messages></lightning-messages>

                                <!-- Contact Edit Form -->
                                <div class="slds-grid slds-wrap">

                                    <div class="slds-col slds-size_1-of-2">

                                        <!-- Title -->
                                        <lightning-input-field data-field="Title" field-name="Title">
                                        </lightning-input-field>

                                        <!-- Email -->
                                        <lightning-input-field data-field="Email" field-name="Email">
                                        </lightning-input-field>

                                        <!-- Mobile Phone -->
                                        <lightning-input-field data-field="MobilePhone" field-name="MobilePhone">
                                        </lightning-input-field>

                                    </div>
                                </div>
                            </lightning-record-edit-form>
                        </lightning-card>
                    </div>

                    <!-- FOOTER -->
                    <footer class="slds-modal__footer">
                        <!-- Cancel Button -->
                        <lightning-button label="Cancel" variant="neutral" onclick={closeModal}></lightning-button>

                        <!-- Spacing -->
                        &nbsp;&nbsp;&nbsp;&nbsp;

                        <!-- Update/Save Button -->
                        <lightning-button label="Update" variant="brand" type="submit" onclick={saveForm}>
                        </lightning-button>

                    </footer>

                </div>

            </section>
            <!-- Create Shading for Modal -->
            <div class="slds-backdrop slds-backdrop_open"></div>

        </div>

    </template>

</template>

The user clicks an edit button associated to the contact which opens a modal and allows the user to update and save the record.

Here is the JS:

import {LightningElement,wire,api,track} from 'lwc';
import getContactList from '@salesforce/apex/getAccountContacts.getContactList';
import {ShowToastEvent} from 'lightning/platformShowToastEvent';
import {NavigationMixin} from 'lightning/navigation';
import {updateRecord} from 'lightning/uiRecordApi';
import ID_FIELD from '@salesforce/schema/Contact.Id';
import TITLE_FIELD from '@salesforce/schema/Contact.Title';
import EMAIL_FIELD from '@salesforce/schema/Contact.Email';
import MOBILE_FIELD from '@salesforce/schema/Contact.MobilePhone';

export default class AccountContactInformation extends NavigationMixin(LightningElement) {

    @api recordId; // Grab the Record Id
    @api objectApiName; // Grab the Objects API Name
    @track openmodel = false; // Default Modal to Closed
    @track recordEditId;

    @wire(getContactList, {
        accountId: '$recordId'
    })
    contacts

    // Open Modal
    openmodal(event) {
        console.log(this.objectApiName);
        this.openmodel = true;
        this.recordEditId = event.target.value;
        console.log(this.recordEditId);
    }

    // Close Modal
    closeModal() {
        this.openmodel = false
    }

    saveForm() {

        const allValid = [...this.template.querySelectorAll('lightning-input')]
            .reduce((validSoFar, inputFields) => {
                inputFields.reportValidity();
                return validSoFar && inputFields.checkValidity();
            }, true);

        const fields = {};
        fields[ID_FIELD.fieldApiName] = this.recordEditId;
        fields[TITLE_FIELD.fieldApiName] = this.template.querySelector("[data-field='Title']").value;
        fields[EMAIL_FIELD.fieldApiName] = this.template.querySelector("[data-field='Email']").value;
        fields[MOBILE_FIELD.fieldApiName] = this.template.querySelector("[data-field='MobilePhone']").value;

        const recordInput = {
            fields
        };

        if (allValid) {

            updateRecord(recordInput)
                .then(() => {
                    this.dispatchEvent(
                        new ShowToastEvent({
                            title: 'Success',
                            message: 'Contact updated',
                            variant: 'success'
                        })
                    );
                })
                .catch(error => {
                    this.dispatchEvent(
                        new ShowToastEvent({
                            title: 'Error Updating record',
                            message: error.body.message,
                            variant: 'error'
                        })
                    );
                });

            this.closeModal();
        } 
        else {
            // The form is not valid
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Something is wrong',
                    message: 'Check your input and try again.',
                    variant: 'error'
                })
            );
        }


    }


}

I tried calling the APEX again to update the fields and it does look like it the values are updating.

Any assistance would be greatly appreciated.

Thanks,

1 Answer 1

1

I was able to resolve this issue by using Apex Refresh

import { refreshApex } from '@salesforce/apex';

I updated my initial @wire Function to the following:

    // Variables for Data Refresh
    contacts;
    error;
    wiredContactsResult;

    @wire(getContactList, {accountId: '$recordId'})
    contactsResult(result) {
        console.log('result:');
        console.log(result);
        console.log(result.data);

        this.wiredContactsResult = result;
        if(result.data){
            console.log('data');
            console.log(result.data);
            this.contacts = result.data;
        } else if (result.error) {
            console.log('error');
            console.log(error);
        }
    }

And then added the following when I wanted to refresh the data or where applicable:

                console.log('Returning updated Contact List');
                return refreshApex(this.wiredContactsResult);`

For more extensive explanation please see the following Documentation:

1
  • If this approach resolved your question, can you mark it as accepted so it no longer shows up as an open question?
    – Adrian Larson
    Commented Mar 5, 2021 at 13:16

You must log in to answer this question.

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