Record in LWC

Create and Insert Record in LWC Without Using record-edit-form | Salesforce Developer Guide

In this blog, we will learn how to create and insert records in Lightning Web Component (LWC) Without Using record-edit-form.

Let's create Lightning Web Component (LWC) using lightning-card, below is the code for the same.

<template>
<lightning-card>   
    <template if:true={spinnerStatus}>      
        <div class="spinner">        
                <lightning-spinner variant="brand" alternative-text="Loading..."></lightning-spinner>                       
        </div>
   </template>     
         <div style="text-align: right">          
            <lightning-button   style="margin:5px;" onclick={toggleAccordion} label={toggleAccordionLabel} slot="actions"></lightning-button>
         </div>
         <lightning-accordion class="financialProfileSection" allow-multiple-sections-open active-section-name={activeSections}>
            <lightning-accordion-section name="A" label="Account Details">
                <div class="slds-grid">
                    <div class="slds-col slds-size_1-of-2 slds-p-right_xx-large">
                        <lightning-input type="text"  label="Name" value={Name} onchange={handlername}></lightning-input>
                    </div>
                    <div class="slds-col slds-size_1-of-2 slds-p-right_xx-large">
                        <lightning-input type="text"  value={AccountNumber} onchange={handleAccountNumber} label="AccountNumber"></lightning-input>
                    </div>
                </div>
            </lightning-accordion-section>
            <lightning-accordion-section name="B" label="PickList Details">
                <div class="slds-grid">
                    <div class="slds-col slds-size_1-of-2 slds-p-right_xx-large">
                        <lightning-combobox
                        name="rating"
                        label="Rating"
                        value={rating}
                        options={ratingPicklistOptions}
                        onchange={handleRating}                       
                        ></lightning-combobox>
                    </div>
                    <div class="slds-col slds-size_1-of-2 slds-p-right_xx-large">
                        <lightning-combobox
                        name="industry"
                        label="Industry"
                        value={industry}
                        options={industryPicklistOptions}
                        onchange={handleindustry}                       
                        ></lightning-combobox>
                    </div>
                </div>
            </lightning-accordion-section>           
         </lightning-accordion>
         <footer class="slds-modal__footer">
            <div class="slds-col_bump-left slds-text-align_right slds-p-horizontal_x-small slds-text-align_center">
                <!--  <lightning-button variant="brand" label="Next" title="Next" type="submit" onclick={handleClickRoute}
                    disabled={disableNextButton} class="slds-m-left_x-small slds-p-right_xx-small">
                </lightning-button> -->
                <lightning-buttonvariant="brand"label="Save"title="Save"
                    class="slds-m-left_x-small slds-p-right_xx-small" onclick={handleForSave}>
                </lightning-button>               
            </div>
            </footer>
</lightning-card>
</template>

dont miss out iconDon't forget to check out: How to Get Current Record Id in Lightning Web Component | Salesforce Developer Guide

import { LightningElement, track, wire } from 'lwc';
import { refreshApex } from '@salesforce/apex';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import insertAcc from '@salesforce/apex/accountInsert.insertAcc';
import { getObjectInfo } from 'lightning/uiObjectInfoApi';
import { getPicklistValues } from 'lightning/uiObjectInfoApi';
import ACCOUNT_OBJINFO from '@salesforce/schema/Account';
import RATING  from '@salesforce/schema/Account.Rating';
import INDUSTRY_FIELD from '@salesforce/schema/Account.Industry';
export default class FinancialProfile extends LightningElement {
    toggleAccordionLabel = 'Collapse All';
    activeSections = ['A', 'B'];
    Name;
    AccountNumber;
    rating;
    industry;
    @track account ={};
    @track ratingPicklistOptions;
    @track industryPicklistOptions;
    @track spinnerStatus =false;
    @wire( getObjectInfo ,{
        objectApiName:ACCOUNT_OBJINFO
    })
    accountInfo
    @wire(getPicklistValues,{
        recordTypeId: '$accountInfo.data.defaultRecordTypeId',
        fieldApiName: INDUSTRY_FIELD
    })
    industryPicklist(
        {
            error,
            data
        }){
            if(data){
                // alert('industry picklist :'+JSON.stringify(this.data))
                this.industryPicklistOptions = data.values;
            }else if(error){
            //alert('error '+JSON.stringify(error))
        }
    }
    handleindustry(event){
        this.industry = event.target.value;
        this.account.industry= this.industry;
    }   
    @wire(getPicklistValues,{
        recordTypeId: '$accountInfo.data.defaultRecordTypeId',
         fieldApiName: RATING
    })
    ratingPicklist({data,error}){
        if(data){
            // alert('rating piclist'+data)
            this.ratingPicklistOptions=data.values;
        }else if(error){
            // alert('error '+JSON.stringify(error))
        }
    }
    handleRating(event){
        this.account.rating=event.target.value;
        // alert('handlerating :'+event.target.value);
        //alert('handlerating details'+event.detail.value)
    }
    handlername(event){
        this.Name = event.target.value;
        console.log(this.Name)
        this.account.Name=this.Name;
    }
    handleAccountNumber(event){
        this.AccountNumber = event.target.value;
        console.log(this.AccountNumber)
        this.account.AccountNumber=this.AccountNumber;
    }
    toastEventFire(title,msg,variant,mode){
        const e = new ShowToastEvent({
            title: title,
            message: msg,
            variant: variant,
            mode: mode
        });
        this.dispatchEvent(e);
    }        
    handleForSave(){
        //alert(JSON.stringify(this.account));
        this.spinnerStatus = true;
        alert(JSON.stringify(this.account));
        insertAcc({ acc : this.account})
        .then(result =>{
            this.spinnerStatus = false;
            this.Name='';
            this.AccountNumber='';
            this.rating='';
            this.industry='';
            this.toastEventFire('Success','account Record is Saved','success')                      
        })
        .catch(error =>{
            this.error = error.message;
            alert(JSON.stringify(error))
        })
    }
    toggleAccordion(event) {        
        if (this.activeSections.length > 0) {
            this.activeSections = [];
            this.toggleAccordionLabel = 'Expand All';
        } else {
            this.activeSections = ['A', 'B'];
            this.toggleAccordionLabel = 'Collapse All';
        }
    }
}

dont miss out iconCheck out an amazing Salesforce video tutorial here: Creating Massive Junction Records with LWC | Salesforce Lightning Tutorial

public class accountInsert {
    @AuraEnabled
    public static void insertAcc(account acc){
        // return [select id,name,site from account where id=:acc.id];
        try{
            insert ACC;
        }catch(Exception ex){
            throw new AuraHandledException(ex.getMessage());
        }
    }
}

 

Responses

Popular Salesforce Blogs