Showing posts with label wire service. Show all posts
Showing posts with label wire service. Show all posts

Thursday, August 8, 2019

Delete Record using Wire Service(uiRecordApi) in Lightning Web Component(lwc)

This post explains how to delete record using wire service(uiRecordApi) in lighting web components(lwc)

import { deleteRecord } from 'lightning/uiRecordApi' From scope module

In this demo, I am deleting account record using uiRecordApi.

Example

deleteRecordInLWC.html
<template>
    <div style="text-align: center;">
        <lightning-card title="Delete Record">
            <lightning-button label="Delete Record" onclick={handleDeleteRecord} variant="brand"></lightning-button>
        </lightning-card>
    </div>
</template>
deleteRecordInLWC.js
import { LightningElement, wire } from 'lwc';
// import uiRecordApi to delete record
import { deleteRecord } from 'lightning/uiRecordApi';

// importing to account record to delete
import getAccount from '@salesforce/apex/LWCExampleController.fetchAccount';

// importing to show to toast messages
import {ShowToastEvent} from 'lightning/platformShowToastEvent';

export default class DeleteRecordInLWC extends LightningElement {
    accRecord;

    // getting account record to delete
    @wire(getAccount)
    objAcc(result) {
        if (result.data) {
            this.accRecord = result.data;
        } 
        else if (result.error) {
            this.accRecord = undefined;
        }
    }
    
    // deleteing account record 
    handleDeleteRecord() {
        // passing account id to delete record
        // recordId is required value
        deleteRecord(this.accRecord.Id)
        .then(result => {
            window.console.log('result ====> '+result);
            this.dispatchEvent(new ShowToastEvent({
                title: 'Success!!',
                message: 'Account Deleted Successfully!!',
                variant: 'success'
            }),);
        })
        .catch(error => {
            this.dispatchEvent(new ShowToastEvent({
                title: 'Error!!',
                message: JSON.stringify(error),
                variant: 'error'
            }),);
        })
    }
}
deleteRecordInLWC.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="DeleteRecordInLWC">
    <apiVersion>46.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>
ApexClass
public inherited sharing class LWCExampleController {
    @AuraEnabled(Cacheable = true)
    public static Account fetchAccount() {
        Account objAcc =  [Select Id From Account Limit 1];
        return objAcc;
    }
}
Result



Resource
https://developer.salesforce.com/docs/component-library/documentation/lwc/lwc.reference_delete_record

Monday, August 5, 2019

How to create a record using Wire service(uiRecordApi) in Lightning Web Component(lwc)

This post explains how to create a record using wire service(uiRecordApi) in Lightning Web Component(lwc).


Example

Import 'lightning/uiRecordApi' scope module in your component.

createRecordInLWC.html
<template>
    <lightning-card title="Create Account Record" icon-name="standard:account">
        <div style="margin-left: 6%" if:true={error}>
            <lightning-badge label={error} style="color: red;"></lightning-badge>
        </div>

        <template if:true={accRecord}>
            <div class="slds-m-around--xx-large">
                <div class="container-fluid">
                    <div class="form-group">
                        <lightning-input label="Enter Account Name" name="accName" required="required" type="text" value={accRecord.Name} onchange={handleNameChange}></lightning-input>
                    </div>
                    <div class="form-group">
                        <lightning-input label="Enter Phone Number" name="accPhone" type="text" value={accRecord.Phone} onchange={handlePhoneChange}></lightning-input>
                    </div>
                    <div class="form-group">
                        <lightning-input label="Enter Account Type" name="accEmail" required="required" type="text" value={accRecord.Type} onchange={handleTypeChange}></lightning-input>
                    </div>
                    <div class="form-group">
                        <lightning-input label="Enter Industry" name="accEmail" type="text" value={accRecord.Industry} onchange={handleIndustryChange}></lightning-input>
                    </div>
                </div>
                <br/>
                <lightning-button label="Submit" onclick={handleSave} variant="brand"></lightning-button>
            </div>
        </template>
    </lightning-card>
</template>
createRecordInLWC.js
import { LightningElement, track} from 'lwc';

// import uiRecordApi to create record
import { createRecord } from 'lightning/uiRecordApi';
// importing to show toast notifictions
import {ShowToastEvent} from 'lightning/platformShowToastEvent';

// importing Account fields
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
import NAME_FIELD from '@salesforce/schema/Account.Name';
import Phone_FIELD from '@salesforce/schema/Account.Phone';
import Industry_FIELD from '@salesforce/schema/Account.Industry';
import Type_FIELD from '@salesforce/schema/Account.Type';

export default class CreateRecordInLWC extends LightningElement {
    @track error;

    // this object have record information
    @track accRecord = {
        Name : NAME_FIELD,
        Industry : Industry_FIELD,
        Phone : Phone_FIELD,
        Type : Type_FIELD
    };


    handleNameChange(event) {
        this.accRecord.Name = event.target.value;
        window.console.log('Name ==> '+this.accRecord.Name);
    }

    handlePhoneChange(event) {
        this.accRecord.Phone = event.target.value;
        window.console.log('Phone ==> '+this.accRecord.Phone);
        window.console.log('object ==> '+JSON.stringify(ACCOUNT_OBJECT));
    }

    handleTypeChange(event) {
        this.accRecord.Type = event.target.value;
        window.console.log('Type ==> '+this.accRecord.Type);
    }

    handleIndustryChange(event) {
        this.accRecord.Industry = event.target.value;
        window.console.log('Industry ==> '+this.accRecord.Industry);
    }


    handleSave() {
        const fields = {};

        fields[NAME_FIELD.fieldApiName] = this.accRecord.Name;
        fields[Phone_FIELD.fieldApiName] = this.accRecord.Phone;
        fields[Industry_FIELD.fieldApiName] = this.accRecord.Industry;
        fields[Type_FIELD.fieldApiName] = this.accRecord.Type;
       
        // Creating record using uiRecordApi
        let recordInput = { apiName: ACCOUNT_OBJECT.objectApiName, fields }
        createRecord(recordInput)
        .then(result => {
            // Clear the user enter values
            this.accRecord = {};

            window.console.log('result ===> '+result);
            // Show success messsage
            this.dispatchEvent(new ShowToastEvent({
                title: 'Success!!',
                message: 'Account Created Successfully!!',
                variant: 'success'
            }),);
        })
        .catch(error => {
            this.error = JSON.stringify(error);
        });
    }
}
createRecordInLWC.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="CreateRecordInLWC">
    <apiVersion>46.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>
Output

Saturday, January 5, 2019

wire service in Lightning Web Components(LWC)


This post explains wire service in Lightning web components(lwc)

What is the wire service?

  1. Lightning web components(lwc) use reactive wire service to read Salesforce data.
  2. It is Built on Lightning Data service.
  3. Components use @wire in their JavaScript class to read data from one of the wire adapters in the lightning/ui*Api namespace.
Reactive wire service supports reactive variables, which are prefixed with $. If a reactive variable changes, the wire service provisions(requests) new data.

wire service syntax

import { adapterId } from 'adapterModule';
@wire(adapterId, adapterConfig)
propertyOrFunction;

adapterId (Identifier) ---> The identifier of the wire adapter.
adapterModule (String) —>The identifier of the module that contains the wire adapter function, in the format namespace/moduleName.
adapterConfig (Object) —> A configuration object specific to the wire adapter. Configuration object property values can be either strings or references to objects and fields imported from @salesforce/schema.
propertyOrFunction —> A private property or function that receives the stream of data from the wire service.
  • If a property is decorated with @wire, the results are returned to the property’s data property or error property. 
  • If a function is decorated with @wire, the results are returned in an object with a data property and an error property.

Example

 Import references to salesforce Object and fields
1. To import a reference to an object, use this syntax.
import objectName from '@salesforce/schema/object';
Ex:
import PROPERTY_OBJECT from '@salesforce/schema/Property__c';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
2. To import a reference to a field, use this syntax.
import FIELD_NAME from '@salesforce/schema/object.field';
Ex:
import POSITION_LEVEL_FIELD from '@salesforce/schema/Property__c.Name';
import ACCOUNT_NAME_FIELD from '@salesforce/schema/Account.Name';
3. To import a reference to a field via a relationship, use this syntax.
import SPANNING_FIELD_NAME from '@salesforce/schema/object.relationship.field';
Ex:
import ACCOUNT_OWNER_NAME_FIELD from '@salesforce/schema/Account.Owner.Name';

Decorate a Property with @wire

  • Wiring a property with @wire is useful when you want to consume the data or error.
  • If the property decorated with @wire is used as an attribute in the template and its value changes,
  • the wire service provisions(requests) the data and triggers the component to rerender.
Ex:
import { LightningElement, api, wire } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';

export default class Record extends LightningElement {
    @api recordId;

    @wire(getRecord, { recordId: '$recordId', fields: ['Opportunity.Name'] })
    record;
}

Decorate a Function with @wire

  • Wiring a function is useful to perform logic whenever new data is provided or when an error occurs. 
  • The function is invoked whenever a value is available, which can be before or after the component is connected or rendered.
Ex:
import { LightningElement, api, track, wire } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';

export default class WireFunction extends LightningElement {
    @api recordId;
    @track record;
    @track error;

    @wire(getRecord, { recordId: '$recordId', fields: ['Opportunity.Name'] })
    wiredAccount({ error, data }) {
        if (data) {
            this.record = data;
        } else if (error) {
            this.error = error;
        }
    }
}