Day: February 16, 2019

Usage Of lightning-record-edit-form

Let us discuss here how to use the lightning-record-edit-form . A lightning-record-edit-form component is a wrapper component that accepts a record ID and is used to display one or more fields and labels associated with that record. The lightning-input-field component is used inside the lightning-record-edit-form to create editable fields. The lightning-output-field component and other display components such as lightning-formatted-name can be used to display read-only information in your form.lightning-record-edit-form requires a record ID to display the fields on the record. It doesn’t require additional Apex controllers or Lightning Data Service to display record data. This component also takes care of field-level security and sharing for you, so users see only the data they have access to.

lightning-record-edit-form and lightning-input-field support the following features.

  • Display a record edit layout for editing a specified record
  • Display a record create the layout for creating a new record

 

Editing a Record

To enable record editing, pass in the ID of the record and the corresponding object API name to be edited. Specify the fields you want to include in the record edit layout using lightning-input-field. Create a Lightning Web component using the below SFDX command

sfdx force:lightning:component:create --type lwc --componentname recordeditform --outputdir force-app\main\default\lwc

Use the below recordeditform.html code

<template>
<lightning-record-edit-form record-id={recordId} object-api-name="Contact"
onsuccess={handleSuccess} onsubmit ={handleSubmit} >
        <lightning-messages>
        </lightning-messages>
        <lightning-output-field field-name="AccountId">
        </lightning-output-field>
        <lightning-input-field field-name="FirstName">
        </lightning-input-field>
        <lightning-input-field field-name="LastName">
        </lightning-input-field>
        <lightning-input-field field-name="Email">
        </lightning-input-field>
        <lightning-button class="slds-m-top_small" variant="brand" type="submit" name="update" label="Update">
        </lightning-button>
    </lightning-record-edit-form>
</template>

Use the below recordeditform.js code

import {
    LightningElement,
    api
} from 'lwc';

export default class Recordeditform extends LightningElement {
    @api recordId;
    handleSubmit(event) {
        console.log('onsubmit: '+ event.detail.fields);

    }
    handleSuccess(event) {
        const updatedRecord = event.detail.id;
        console.log('onsuccess: ', updatedRecord);
    }
}

Use the recordeditform.js-meta.xml code

 

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="helloWorld">
    <apiVersion>45.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
</LightningComponentBundle>

Push the changes and you can able to see the below screen and you can able to edit the contact record

 

 

 

Creating a Record

To enable record creation, pass in the object API name for the record to be created. Specify the fields you want to include in the record create layout using lightning-input-field components.  A record Id is generated when a record is created successfully. To return the Id, use the onsuccess handler.

Use the below recordeditform code.

<template>
    <lightning-record-edit-form object-api-name="Contact" onsuccess={handleSuccess}>
        <lightning-messages></lightning-messages>
        <div class="slds-m-around_medium">
            <lightning-input-field field-name='Id' value={contactId}></lightning-input-field>
            <lightning-input-field field-name='LastName'></lightning-input-field>
            <lightning-input-field field-name='FirstName'></lightning-input-field>
            <lightning-input-field field-name='Email'></lightning-input-field>
            <lightning-input-field field-name='AccountId'></lightning-input-field>

            <div class="slds-m-top_medium">
                <lightning-button variant="brand" type="submit" name="save" label="Create Contact">
                </lightning-button>
            </div>
        </div>
    </lightning-record-edit-form>
</template>
import {
    LightningElement,
    api,track
} from 'lwc';

export default class Recordeditform extends LightningElement {
    @track contactId;
    handleSuccess(event) {
        this.contactId = event.detail.id;
    }

}

 

Push the changes and you can able to see the below details as shown below.

Overriding Default Behaviors

To customize the behavior of your form when it loads or when data is submitted, use the onload and onsubmit attributes to specify event handlers. If you capture the submit event and submit the form programmatically, use event.preventDefault() to cancel the default behavior of the event. This prevents a duplicate form submission. Here in the example, we will be setting the fields values on the onsubmit behaviors.

Update the code as shown below which will set some of the account field values automatically.

import {
    LightningElement,
    api,
    track
} from 'lwc';

export default class Recordeditform extends LightningElement {
    handleSubmit(event) {
        event.preventDefault(); // stop the form from submitting
        const fields = event.detail.fields;
        console.log(JSON.stringify(fields));

        fields.title = 'VP of Opearations';
        fields.MobilePhone = '2123123123213';
        fields.LeadSource = 'Web';
        this.template.querySelector('lightning-record-edit-form').submit(fields);
    }
    handleSuccess(event) {
        const payload = event.detail;
        console.log(JSON.stringify(payload));

        const updatedRecord = event.detail.id;
        console.log('onsuccess: ', updatedRecord);
    }

}

Use the below HTML code.

<template>
<lightning-record-edit-form object-api-name="Contact" onsuccess={handleSuccess} onsubmit={handleSubmit}>
        <lightning-messages></lightning-messages>
        <div class="slds-m-around_medium">
            <lightning-input-field field-name='Id' value={contactId}></lightning-input-field>
            <lightning-input-field field-name='LastName'></lightning-input-field>
            <lightning-input-field field-name='FirstName'></lightning-input-field>
            <lightning-input-field field-name='Email'></lightning-input-field>
            <lightning-input-field field-name='AccountId'></lightning-input-field>

            <div class="slds-m-top_medium">
                <lightning-button variant="brand" type="submit" name="save" label="Create Contact">
                </lightning-button>
            </div>
        </div>
    </lightning-record-edit-form>
</template>

 

Using Record Types

If your org uses record types, picklist fields display values according to your record types. You must provide a record type ID using the record-type-id attribute if you have multiple record types on an object and you don’t have a default record type. Otherwise, the default record type ID is used like below.

<lightning-record-edit-form object-api-name="Contact" record-type-id="003XXXXXXXXXXXXXXX" onsuccess={handleSuccess}>

</lightning-record-edit-form>

Error Handling

You must include lightning-messages to support error handling and displaying of error messages. If the record edit layout includes a lightning-button component with type="submit", when the button is clicked the lightning-record-edit-form component automatically performs error handling and saves any changes in the input fields. Similarly, if the record create layout provides a submit button, when the button is clicked error handling is automatically performed and a new record is created with the input data you provide. Additionally, the lightning-record-edit-form component provides basic input validation like below.

<template>
    <lightning-record-edit-form object-api-name="Contact"  onsuccess={handleSuccess}>
        <lightning-messages></lightning-messages>
        <div class="slds-m-around_medium">
          
        </div>
    </lightning-record-edit-form>
</template>

 

You can able to see the errors as shown below .

 

Usage Of lightning-record-view-form

Let us discuss here how to use the lightning-record-view-form. A lightning-record-view-form component is a wrapper component that accepts a record ID and is used to display one or more fields and labels associated with that record using lightning-output-fieldlightning-record-view-form requires a record ID to display the fields on the record. It doesn’t require additional Apex controllers or Lightning Data Service to display record data. This component also takes care of field-level security and sharing for you, so users see only the data they have access to.

Displaying Record Fields

Create a Lightning web component using the below SFDX command.

sfdx force:lightning:component:create --type lwc --componentname recordview --outputdir force-app\main\default\lwc

Use the below recordview.html code

<template>
    <lightning-record-view-form record-id={recordId} object-api-name="Contact">
        <div class="slds-box">
            <lightning-output-field field-name="FirstName">
            </lightning-output-field>
            <lightning-output-field field-name="LastName">
            </lightning-output-field>
            <lightning-output-field field-name="MobilePhone">
            </lightning-output-field>
            <lightning-output-field field-name="Email">
            </lightning-output-field>
        </div>
    </lightning-record-view-form>
</template>

Use the below recordview.js code

import { LightningElement ,api} from 'lwc';

export default class Recordview extends LightningElement {
    @api recordId ;
}

Use the below recordview.js-meta.xml code

 

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="helloWorld">
    <apiVersion>45.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
</LightningComponentBundle>

 

Push changes and add to the page layouts.you can able to see the below output.

To create a multi-column layout for your record view, use the Grid utility classes in Lightning Design System. This example creates a two-column layout.

Update the code as shown below.

<template>
    <lightning-record-view-form record-id={recordId} object-api-name="Account">
        <div class="slds-grid">
            <div class="slds-col slds-size_1-of-2">
                <lightning-output-field field-name="Name"></lightning-output-field>
                <lightning-output-field field-name="Phone"></lightning-output-field>
            </div>
            <div class="slds-col slds-size_1-of-2">
                <lightning-output-field field-name="Industry"></lightning-output-field>
                <lightning-output-field field-name="AnnualRevenue"></lightning-output-field>
            </div>
        </div>
    </lightning-record-view-form>
</template>

Push the changes and you can able to see the result as below.

 

We’ve seen how record fields render using lightning-input-field and lightning-output-field. To render data in a custom way, use the getRecord or getRecordUi wire adapters.

Update the code as shown below.

<template>
    <lightning-record-view-form record-id={recordId} object-api-name={accountObject}>
        <div class="slds-grid">
            <div class="slds-col slds-size_1-of-2">
                <!-- Other record data here -->
            </div>
            <div class="slds-col slds-size_1-of-2">
                <lightning-formatted-text value={nameValue} class="slds-text-heading_large">
                </lightning-formatted-text>
            </div>
        </div>
    </lightning-record-view-form>
</template>

 

In the component’s JavaScript code, import references to the account object and the name field. The getRecord wire adapter loads the name field for custom rendering in the lightning-formatted-text component instead of the standard lightning-output-field used by lightning-record-view-form.

update the code as shown below.

import {
    LightningElement,
    api,
    wire
} from 'lwc';
/* Wire adapter to fetch record data */
import {
    getRecord,
    getFieldValue
} from 'lightning/uiRecordApi';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
import NAME_FIELD from '@salesforce/schema/Account.Name';
export default class Recordview extends LightningElement {
    /** Id of record to display. */
    @api recordId;

    /* Expose schema objects/fields to the template. */
    accountObject = ACCOUNT_OBJECT;

    /* Load Account.Name for custom rendering */
    @wire(getRecord, {
        recordId: '$recordId',
        fields: [NAME_FIELD]
    })
    record;

    /** Gets the Account.Name value. */
    get nameValue() {
        return this.record.data ? getFieldValue(this.record.data, NAME_FIELD) : '';
    }
}

 

You can able to see the UI as shown below.

Usage Of lightning-slider

Let us discuss here how to use the lightning-slider. A lightning-slider component is a horizontal or vertical slider for specifying a value between two specified numbers. For example, this slider can be used to capture user input about order quantity or when you want to use an input field of type="range". To orient the slider vertically, set type="vertical". Older browsers that don’t support the slider fall back and treat it as type="text"

Here’s an example of a slider with a step increment of 10.

<template>
        <lightning-slider
            label="Volume"
            step="10"
            value="10"
            onchange={handleChange}>
        </lightning-slider>
    </template>

Handle the change event and get the slider value using the event.target property.

import { LightningElement } from 'lwc';

export default class MyDemo extends LightningElement {
    handleChange(event) {
        alert(event.target.value);
    }

By default, the min and max values are 0 and 100, but you can specify your own values. If you specify your own step increment value, you can drag the slider based on the step increment only. If you set the value lower than the min value, then the value is set to the min value. Similarly, setting the value higher than the max value results in the value being set to the max value.

 

In this example, we will be showing the contact data based on the slide range change

Create Apex Class

create an apex class as shown below

public with sharing class ContactController {
    @AuraEnabled(cacheable=true)
    public static List<Contact> getContactList(Integer limitVal) {
        return [SELECT Id, Name,Email,Phone FROM Contact Limit :limitVal];
    }
}

 

LWC 

create a lightning web component using the following sfdx command

 sfdx force:lightning:component:create --type lwc --componentname slider --outputdir force-app\main\default\lwc

 

Use the below slider.html code

 

<template>
    <div class="slds-m-vertical_medium">
        <h1 class="slds-text-heading_small">Slide to Get the Contacts</h1>
        <lightning-slider label="Contact Limit" step="5" value={val} onchange={handleChange}></lightning-slider>

    </div>
    <lightning-card title="Contacts List">

        <ul class="slds-m-around_medium">
            <template for:each={contacts.data} for:item="contact">
                <li key={contact.Id}>
                    {contact.Name}
                </li>
            </template>
        </ul>
    </lightning-card>
</template>

 

Use the below slider.js code

import {
    LightningElement,
    api,
    wire,
    track
} from 'lwc';
import getContactList from '@salesforce/apex/ContactController.getContactList';
export default class Slider extends LightningElement {
    @track val = 5;
    @track contacts;
    handleChange(event) {
        this.val = event.target.value;
    }
    @wire(getContactList, {
        limitVal: '$val'
    })
    contacts;

}

 

Use the below slider.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="helloWorld">
    <apiVersion>45.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
</LightningComponentBundle>

 

Push changes and add it to the page layout and you can able to see the like below

 

 

Usage Of lightning-record-form

Let us discuss here how to use the lightning-record-form . A lightning-record-form component enables you to quickly create forms to add, view, or update a record. Using this component to create record forms is easier than building forms manually with lightning-record-edit-form and lightning-record-view-form. However, lightning-record-form does not support client-side validation quite the same as lightning-record-edit-form.The object-api-name attribute is always required, and the record-id is required unless you’re creating a record.

Modes

The component accepts a mode value that determines the user interaction allowed for the form. The value for mode can be one of the following:

  • edit – Creates an editable form to add a record or update an existing one. When updating an existing record, specify the recordId. Edit mode is the default, and as such, can be omitted.
  • view – Creates a form to display a record that the user can also edit. The record fields each have an edit button.
  • readonly – Creates a form to display a record without enabling edits. The form doesn’t display any buttons.

For all modes, the component expects the fields attribute, the layout-type attribute, or both. Use the fields attribute to specify a comma-separated list of record fields to load into the form. The fields load in the order you list them. Use the layout-type attribute to specify a Full or Compact layout. All fields that have been assigned to the layout are loaded into the form. This is the same behavior as the Lightning Data Service’s force:recordData object. Layouts are typically created or modified by administrators. Loading record data using layout-type allows the form to adapt to those layout definitions. If you provide the fields attribute and the layout-type attribute, the fields specified in the fields attribute are loaded before the layout fields.

This component takes care of field-level security and sharing for you, so users see only the data that they have access to.

Creating a Record

Use mode="edit" and pass in the object API name for the record to be created. Do not specify a recordId. Specify the fields using the fields attribute, or layout-type="Full" attribute to load all the fields defined on the full layout.The compact layout cannot be used for creating records. If you specify layout-type="Compact", the full layout is shown. If you specify the fields attribute, be sure to include any fields that are designated as required for the object’s records. Because no recordId is passed, edit mode loads the form with input fields that aren’t populated with field data. The form displays Submit and Cancel buttons.This example creates an editable two-column form with the full layout and additional fields. The form is used for creating records in an Account object. The onsubmit attribute specifies an action to override the handler for the submit.

Create a Lightning web component using the below SFDX command

sfdx force:lightning:component:create --type lwc --componentname recordform --outputdir force-app\main\default\lwc

Use the below recordform.html code

<template>
    <lightning-record-form object-api-name="Account" layout-type="Compact" columns="2" mode="edit" 
    onsuccess={handleSuccess} onsubmit={handleSubmit}>
    </lightning-record-form>
</template>

Use the below recordform.js code

import {
    LightningElement,
    api
} from 'lwc';

export default class Recordform extends LightningElement {

    handleSubmit(event) {
        console.log(event.detail)
    }
    handleSuccess(event) {
        console.log('Record iD' + event.detail.id);

    }
}

Use the below recordform.js-meta.xml code

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="helloWorld">
    <apiVersion>45.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
</LightningComponentBundle>

 

Push the changes and add this component to the record page layout. you can able to see the complete record create a form

 

Now let’s see how to use create a record with specific fields. Now update the recordform.html code as shown below

<template>
    <lightning-record-form object-api-name={accountObject}  fields={myFields} mode="edit"
        onsuccess={handleSuccess} onsubmit={handleSubmit}>
    </lightning-record-form>
</template>

Use the below recordform.js code which will be passed to the record form.

import {
    LightningElement,
    api
} from 'lwc';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
import NAME_FIELD from '@salesforce/schema/Account.Name';
import WEBSITE_FIELD from '@salesforce/schema/Account.Website';
export default class Recordform extends LightningElement {

     accountObject = ACCOUNT_OBJECT;
     myFields = [NAME_FIELD, WEBSITE_FIELD];
     
    handleSubmit(event) {
        console.log(event.detail);
    }
    handleSuccess(event) {
        console.log('Record iD' + event.detail.id);

    }
}

Push the changes and you can able to see the create form with two fields as shown below.

Editing a Record

If you do not specify the mode attribute, its default value is edit. To edit a record, pass the ID of the record and the corresponding object API name to be edited. Specify the fields using the fields attribute, or layout-type attribute to load all the fields defined on the Full or Compact layout. When record-id is passed, edit mode loads the form with input fields displaying the specified record’s field values. The form also displays Submit and Cancel buttons. This example creates an editable two-column form with a compact layout and additional fields. The form is used for editing records in an Account object. The onsubmit attribute specifies an action to override the handler for the submit. Update the recordform.html code as shown below.

<template>
    <lightning-record-form record-id={recordId} object-api-name="Account" layout-type="Full" columns="2" mode="edit"
       onsuccess={handleSuccess} onsubmit={handleSubmit}>
    </lightning-record-form>
</template>

update the recordform.js code as shown below.

import {
    LightningElement,
    api
} from 'lwc';

export default class Recordform extends LightningElement {
    @api recordId;
    handleSubmit(event) {
        console.log(event.detail);
    }
    handleSuccess(event) {
        console.log('Record iD' + event.detail.id);

    }
}

 

Use mode="view" and pass the ID of the record and the corresponding object API name to be displayed. Specify the fields using the fields attribute, or layout-type attribute to display all the fields defined on the Full or Compact layout.

 

the following code shows the how to edit the specific fields instead of layouts.update the recordform.html code as below.

<template>
    <lightning-record-form object-api-name={accountObject} record-id={recordId}  fields={myFields} mode="edit"
        onsuccess={handleSuccess} onsubmit={handleSubmit}>
    </lightning-record-form>
</template>

 

update the recordform.js code as shown below.

import {
    LightningElement,
    api
} from 'lwc';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
import NAME_FIELD from '@salesforce/schema/Account.Name';
import WEBSITE_FIELD from '@salesforce/schema/Account.Website';
export default class Recordform extends LightningElement {

    @api recordId ; 
     accountObject = ACCOUNT_OBJECT;
     myFields = [NAME_FIELD, WEBSITE_FIELD];
     
    handleSubmit(event) {
        console.log(event.detail);
    }
    handleSuccess(event) {
        console.log('Record iD' + event.detail.id);

    }
}

Now you can able to see the changes as shown below with the specified fields.

Viewing a Record Read-Only

The simplest way to display a record is to use the lightning-record-form. You can display a record in two modes.

view
Loads the form using output fields with inline editing enabled. Editable fields have edit icons. If a user clicks an edit icon, all fields in the form become editable, and the form displays Submit and Cancel buttons.
read-only
Read-only mode loads the form with output fields only. The form doesn’t include edit icons, Submit and Cancel buttons.

This code displays an account record in view mode using the compact layout, which includes fewer fields than the full layout.

Use mode="readonly" and pass the ID of the record and the corresponding object API name to be displayed. Specify the fields using the fields attribute, or layout-type attribute to display all the fields defined on the Full or Compact layout. The read-only mode loads the form with output fields only, and without Submit or Cancel buttons.The following code specifis how to use the read-only mode. Use the below recordform.html code.

<template>
    <lightning-record-form record-id={recordId} object-api-name="Account"
     layout-type="Full" columns="2" mode="readonly"
         onsuccess={handleSuccess} onsubmit={handleSubmit}>
    </lightning-record-form>
</template>

You can able to see the record with read-only data .

 

Let’s update the code with view mode as shown below. view Loads the form using output fields with inline editing enabled. Editable fields have edit icons. If a user clicks an edit icon, all fields in the form become editable, and the form displays Submit and Cancel buttons.

Update the code as shown below and you can able to see the edit icon

<template>
    <lightning-record-form record-id={recordId} object-api-name="Account" layout-type="Full"
     columns="2" mode="View"
        onsuccess={handleSuccess} onsubmit={handleSubmit}>
    </lightning-record-form>
</template>

 

 

Using Record types

If your org uses record types, picklist fields display values according to your record types. You must provide a record type ID using the record-type-id attribute if you have multiple record types on an object and you don’t have a default record type. Otherwise, the default record type ID is used. Display a record create a form based on a record type by providing the record-type-id attribute. This example shows a form that you can place on an account record page. The form displays fields, which include a picklist with values based on the given record type Id.

  <lightning-record-form object-api-name={objectApiName} 
                 record-type-id={recordTypeId}
                 fields={fields}>
            </lightning-record-form>

 

Error Message

To enable automatic error handling, include the component lightning-messages.To customize the behavior of your form when it loads or when data is submitted, use the onload and onsubmit attributes to specify event handlers. Errors are automatically handled. To customize the behavior of the form when it encounters an error on submission or when data is submitted successfully, use the onerror and onsuccess attributes to specify event handlers

<template>
            <lightning-messages></lightning-messages>

    <lightning-record-form record-id={recordId} object-api-name="Account" layout-type="Full"
     columns="2" mode="View"
        onsuccess={handleSuccess} onsubmit={handleSubmit}>
    </lightning-record-form>
</template>