1import { LightningElement, track, wire } from "lwc";
2import { ShowToastEvent } from "lightning/platformShowToastEvent";
3import { updateRecord } from "lightning/uiRecordApi";
4import { refreshApex } from "@salesforce/apex";
5import getSingleContact from "@salesforce/apex/ContactController.getSingleContact";
6import FIRSTNAME_FIELD from "@salesforce/schema/Contact.FirstName";
7import LASTNAME_FIELD from "@salesforce/schema/Contact.LastName";
8import ID_FIELD from "@salesforce/schema/Contact.Id";
9
10export default class LdsUpdateRecord extends LightningElement {
11 disabled = false;
12 @track error;
13
14 @wire(getSingleContact)
15 contact;
16
17 handleChange(event) {
18 // Display field-level errors and disable button if a name field is empty.
19 if (!event.target.value) {
20 event.target.reportValidity();
21 this.disabled = true;
22 } else {
23 this.disabled = false;
24 }
25 }
26
27 updateContact() {
28 const allValid = [...this.template.querySelectorAll("lightning-input")].reduce(
29 (validSoFar, inputFields) => {
30 inputFields.reportValidity();
31 return validSoFar && inputFields.checkValidity();
32 },
33 true,
34 );
35
36 if (allValid) {
37 // Create the recordInput object
38 const fields = {};
39 fields[ID_FIELD.fieldApiName] = this.contactId;
40 fields[FIRSTNAME_FIELD.fieldApiName] = this.template.querySelector(
41 "[data-field='FirstName']",
42 ).value;
43 fields[LASTNAME_FIELD.fieldApiName] =
44 this.template.querySelector("[data-field='LastName']").value;
45
46 const recordInput = { fields };
47
48 updateRecord(recordInput)
49 .then(() => {
50 this.dispatchEvent(
51 new ShowToastEvent({
52 title: "Success",
53 message: "Contact updated",
54 variant: "success",
55 }),
56 );
57 // Display fresh data in the form
58 return refreshApex(this.contact);
59 })
60 .catch((error) => {
61 this.dispatchEvent(
62 new ShowToastEvent({
63 title: "Error creating record",
64 message: error.body.message,
65 variant: "error",
66 }),
67 );
68 });
69 } else {
70 // The form is not valid
71 this.dispatchEvent(
72 new ShowToastEvent({
73 title: "Something is wrong",
74 message: "Check your input and try again.",
75 variant: "error",
76 }),
77 );
78 }
79 }
80}