# `updateRecord(recordInput, clientOptions)`

Updates a record. Provide the record Id of the record to update in `recordInput`.

## Syntax

```javascript
import { updateRecord } from 'lightning/uiRecordApi';
updateRecord(recordInput: Record, clientOptions?: Object): Promise<Record>
```

## User Interface API Resource

```html
PATCH /ui-api/records/{recordId}
```

`updateRecord` uses this [User Interface API resource](https://developer.salesforce.com/docs/atlas.en-us.uiapi.meta/uiapi/ui_api_resources_record_patch.htm), but doesn’t support all its parameters.

## Parameters

| Parameter Name  | Type   | Description                                                                                                                                                                                                                                                                                                                                                                                                                             | Required?                                                                         |
| --------------- | ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- |
| `recordInput`   | Object | A [`RecordInput`](https://developer.salesforce.com/docs/atlas.en-us.uiapi.meta/uiapi/ui_api_requests_record_input.htm) object used to update the record. To create the object, call[`generateRecordInputForUpdate(record, objectInfo)`](/docs/platform/lwc/guide/reference-generate-record-input-update.md). Alternatively, create the `RecordInput` object by passing in the fields and their values. See the [Usage](#usage) section. | ![Yes](https://a.sfdcstatic.com/developer-website/sfdocs/lwc/media/checkmark.png) |
| `clientOptions` | Object | To check for conflicts before you update a record, pass `const clientOptions = {'ifUnmodifiedSince' : lastModifiedDate}`. Get `lastModifiedDate` via a wire service adapter that returns a record object: `const lastModifiedDate = record.fields.LastModifiedDate.value;`.                                                                                                                                                             |                                                                                   |

`recordInput` has several properties.

| `recordInput` Property | Type    | Description                                                                                                                                                                                                                                                                                                                                                                   | Required?                                                                         |
| ---------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- |
| `fields`               | Map     | Map of field names to field values. See [Update a Record](https://developer.salesforce.com/docs/atlas.en-us.uiapi.meta/uiapi/ui_api_resources_record_patch.htm) in the *User Interface API Developer Guide*.                                                                                                                                                                  | ![Yes](https://a.sfdcstatic.com/developer-website/sfdocs/lwc/media/checkmark.png) |
| `apiName`              | String  | To create a record, specify the API name of an object from which to create the record. To update a record, use `null` or don’t pass this property.                                                                                                                                                                                                                            |                                                                                   |
| `triggerOtherEmail`    | Boolean | For a case, specifies whether to send email to users outside the organization. In Salesforce, this email can be triggered by creating, editing, or deleting a contact for a case. The default value is `false`.                                                                                                                                                               |                                                                                   |
| `triggerUserEmail`     | Boolean | For a case or a lead, specifies whether to send email to users in the organization. In the Salesforce user interface, this email can be triggered by various events: resetting a password, creating a user, changing the case owner, or adding comments to a case. The default value is `false`. For case owner changes, also set `useDefaultRule=true`, or no email is sent. |                                                                                   |
| `useDefaultRule`       | Boolean | For a case or lead, specifies whether to use the default (active) assignment rule. If you specify `useDefaultRule`, don’t specify an `assignmentRuleId`. The default value is `false`. For an Account, specifies whether to apply the default territory assignment rules.                                                                                                     |                                                                                   |
| `allowSaveOnDuplicate` | Boolean | Specifies whether to save a duplicate record. The default value is `false`.                                                                                                                                                                                                                                                                                                   |                                                                                   |

## Returns

A Promise object that resolves with the updated record. The record contains data for the fields in the record layout.

## Usage

Before you use this wire adapter, make sure that there isn’t an easier way to update the data. To create a form for working with records, consider the [`lightning-record-*-form` components](/docs/platform/lwc/guide/data-get-user-input.md).

:::note
Create a custom form only if you need more customization than the `lightning-record-*-form` components allow.
:::

This example creates a custom form that updates a record. It uses a `getSingleRecord` Apex controller to load the `FirstName` and `LastName` fields for a single contact record. (Name is a compound field. To edit the name, you must use the FirstName and LastName fields.)

As a custom behavior, the **Update Contact** button is disabled when one or both name fields are empty. The Id field is for reference only and is disabled so users can’t edit it.

```html
<template>
  <lightning-card title="LdsUpdateRecord" icon-name="standard:record">
    <div class="slds-m-around_medium">
      <template lwc:if={contact.data}>
        <lightning-input label="Id" disabled value={contact.data.Id}></lightning-input>
        <lightning-input
          label="First Name"
          value={contact.data.FirstName}
          data-field="FirstName"
          onchange={handleChange}
          class="slds-m-bottom_x-small"
        ></lightning-input>
        <lightning-input
          label="Last Name"
          value={contact.data.LastName}
          data-field="LastName"
          onchange={handleChange}
          class="slds-m-bottom_x-small"
          required
        ></lightning-input>
        <lightning-button
          label="Update Contact"
          variant="brand"
          onclick={updateContact}
          disabled={disabled}
        ></lightning-button>
      </template>
      <template lwc:elseif={contact.error}>
        <!-- handle Apex error -->
      </template>
    </div>
  </lightning-card>
</template>
```

Changes are updated using `updateRecord`. Requiredness is not enforced on the client-side. To display field-level errors on invalid fields, call `reportValidity()`.

:::note
If you use the [`lightning-record-*-form` components](/docs/platform/lwc/guide/data-get-user-input.md), all fields are displayed based on your Salesforce schema. For example, it automatically handles requiredness on the client-side for required fields. To customize how the form works, use `updateRecord`. For example, you can prevent users from leaving the non-required FirstName field blank to improve data completeness, or disable the button when specific fields aren’t valid.
:::

```javascript
import { LightningElement, track, wire } from "lwc";
import { ShowToastEvent } from "lightning/platformShowToastEvent";
import { updateRecord } from "lightning/uiRecordApi";
import { refreshApex } from "@salesforce/apex";
import getSingleContact from "@salesforce/apex/ContactController.getSingleContact";
import FIRSTNAME_FIELD from "@salesforce/schema/Contact.FirstName";
import LASTNAME_FIELD from "@salesforce/schema/Contact.LastName";
import ID_FIELD from "@salesforce/schema/Contact.Id";

export default class LdsUpdateRecord extends LightningElement {
  disabled = false;
  @track error;

  @wire(getSingleContact)
  contact;

  handleChange(event) {
    // Display field-level errors and disable button if a name field is empty.
    if (!event.target.value) {
      event.target.reportValidity();
      this.disabled = true;
    } else {
      this.disabled = false;
    }
  }

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

    if (allValid) {
      // Create the recordInput object
      const fields = {};
      fields[ID_FIELD.fieldApiName] = this.contactId;
      fields[FIRSTNAME_FIELD.fieldApiName] = this.template.querySelector(
        "[data-field='FirstName']",
      ).value;
      fields[LASTNAME_FIELD.fieldApiName] =
        this.template.querySelector("[data-field='LastName']").value;

      const recordInput = { fields };

      updateRecord(recordInput)
        .then(() => {
          this.dispatchEvent(
            new ShowToastEvent({
              title: "Success",
              message: "Contact updated",
              variant: "success",
            }),
          );
          // Display fresh data in the form
          return refreshApex(this.contact);
        })
        .catch((error) => {
          this.dispatchEvent(
            new ShowToastEvent({
              title: "Error creating record",
              message: error.body.message,
              variant: "error",
            }),
          );
        });
    } else {
      // The form is not valid
      this.dispatchEvent(
        new ShowToastEvent({
          title: "Something is wrong",
          message: "Check your input and try again.",
          variant: "error",
        }),
      );
    }
  }
}
```

The `getSingleContact` Apex method returns a single contact record.

```apex
public with sharing class ContactController {
    @AuraEnabled(cacheable=true)
    public static Contact getSingleContact() {
        return [
            SELECT Id, Name, Title, Phone, Email, Picture__c
            FROM Contact
            WITH USER_MODE
            LIMIT 1
        ];
    }
}
```

**See Also**

- [Call Apex Methods](/docs/platform/lwc/guide/apex.md)
- [Display Data in a Table with Inline Editing](/docs/platform/lwc/guide/data-table-inline-edit.md)
