1
<template>
<lightning-record-edit-form object-api-name="Gl__c">
<lightning-input-field field-name="RGl__c" onchange={handleFieldChange}>
                                    </lightning-input-field>
        <lightning-input-field field-name="BGl__c" onchange={handleFieldChange}>
                                        </lightning-input-field>
</lightning-record-edit-form>
<footer class="slds-modal__footer">
             <button class="slds-button slds-button_neutral" onclick={closeModal}>Cancel</button>

             <button class="slds-button slds-button_brand" onclick={saveModal}>Save</button>
          </footer>
    <!-- modal code is here -->
  </template>

How to get the data from fields in the form into the apex controller so I can add data to the other fields and insert the record. I have many fields which I couldn't copy paste here, Is there a way that I can save all the fields of the object in a list and pass that list to the apex controller in Lightning Web components?

event.detail.RGl__c to get the value from the field but if I have many fields, is there a way to code efficiently?

Updated code: lwc.js

  import { LightningElement, track, api} from 'lwc';
   import GL_OBJECT from '@salesforce/schema/Gl__c';

 import saveGlRecord from '@salesforce/apex/GlController.saveGlRecord';



export default class CreateGlModel extends LightningElement {
@track showModal=true; 
flag = false;
@api reqId; 
@api bShowModal = this.showModal;
@track glRecord = {};
saveModal(){
    this.showModal = false;

    saveGlRecord({id: this.reqId},{gl: { ...this.glRecord, sobjectType: GL_OBJECT.objectApiName } })
          .then(result => { this.f = result })
          .catch(error => { this.error = error })
}
handleFieldChange(e) {
    this.glRecord[e.currentTarget.fieldName] = e.target.value;
}
 }

Apex Controller:

    public static Boolean saveGlRecord(String id, Gl__C gl){
     Boolean flag = false;
     System.debug('gl'+ gl);
    }
4

Added based on omments (for creating record):

  1. There is no need of Apex to create record as you have standard createRecord. However, I have provided sample code for both below.

  2. Get the record values from onload event of record-edit-form and create a record structure from that data. Filter the fields based on what fields are used in form.

  3. While processing through Apex, you need sobjectType.

Sample:

HTML:

<template>
    <lightning-record-edit-form object-api-name="Contact">
        <lightning-messages>
        </lightning-messages>
        <lightning-input-field field-name="AccountId" onchange={handleFieldChange}>
        </lightning-input-field>
        <lightning-input-field field-name="FirstName" onchange={handleFieldChange}>
        </lightning-input-field>
        <lightning-input-field field-name="LastName" onchange={handleFieldChange}>
        </lightning-input-field>
        <lightning-input-field field-name="Email" onchange={handleFieldChange}>
        </lightning-input-field>
        <lightning-button class="slds-m-top_small"
                          variant="brand"
                          name="save"
                          label="Save from createRecord"
                          onclick={saveForm}>
        </lightning-button>
        <lightning-button class="slds-m-top_small"
                          variant="brand"
                          name="saveApex"
                          label="Save from Apex"
                          onclick={upsertCon}>
        </lightning-button>
    </lightning-record-edit-form>
</template>

JS:

import { LightningElement, wire, api, track } from 'lwc';
import { createRecord } from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import upsertContact from '@salesforce/apex/poc.upsertContact';
import CONTACT_OBJECT from '@salesforce/schema/Contact';

export default class Poc extends LightningElement {
    @track contactRecord = {};

    handleFieldChange(e) {
        this.contactRecord[e.currentTarget.fieldName] = e.target.value;
    }

    upsertCon() {
        upsertContact({ con: { ...this.contactRecord, sobjectType: CONTACT_OBJECT.objectApiName } })
            .then((contact) => {
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Success',
                        message: 'Contact upserted from apex => ' + contact.Id,
                        variant: 'success'
                    })
                );
            })
            .catch((err) => console.error(err));
    }

    saveForm() {
        // if(this.validated())
        console.log('Contact for save => ', JSON.stringify(this.contactRecord));
        createRecord({ apiName: CONTACT_OBJECT.objectApiName, fields: this.contactRecord })
            .then(contact => {
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Success',
                        message: 'Contact created from saveForm => ' + contact.id,
                        variant: 'success'
                    })
                );
            })
            .catch((error) => {
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Error creating record',
                        message: error.body.message,
                        variant: 'error'
                    })
                );
            });
    }
}

Apex:

@AuraEnabled
public static Contact upsertContact(Contact con) {
    System.debug('con => '+con);
    upsert con;
    return con;
}

For updating record:

  1. There is no need of Apex as you have standard updateRecord. However, if you have some other logic which has to be in Apex only, then you can pass the record to Apex. Given example of both in below POC.

  2. Get the record values from onload event of record-edit-form and create a record structure from that data. Filter the fields based on what fields are used in form.

  3. While processing through Apex, you need sobjectType.

Below is the example:

<template>
    <lightning-record-edit-form record-id="00328000008ZUIdAAO"
                                onload={handleLoad}
                                object-api-name="Contact">
        <lightning-messages>
        </lightning-messages>
        <lightning-input-field field-name="AccountId" onchange={handleFieldChange}>
        </lightning-input-field>
        <lightning-input-field field-name="FirstName" onchange={handleFieldChange}>
        </lightning-input-field>
        <lightning-input-field field-name="LastName" onchange={handleFieldChange}>
        </lightning-input-field>
        <lightning-input-field field-name="Email" onchange={handleFieldChange}>
        </lightning-input-field>
        <lightning-button class="slds-m-top_small"
                          variant="brand"
                          name="save"
                          label="Save from updateRecord"
                          onclick={saveForm}>
        </lightning-button>
        <lightning-button class="slds-m-top_small"
                          variant="brand"
                          name="saveApex"
                          label="Save from Apex"
                          onclick={updateCon}>
        </lightning-button>
    </lightning-record-edit-form>
</template>

JS:

import { LightningElement, wire, api, track } from 'lwc';
import { updateRecord } from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import updateContact from '@salesforce/apex/poc.updateContact';

export default class Poc extends LightningElement {
    @track contactRecord = {};

    updateCon() {
        updateContact({ con: { ...this.contactRecord, sobjectType: 'Contact' } })
            .then(() => {
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Success',
                        message: 'Contact updated',
                        variant: 'success'
                    })
                );
            })
            .catch((err) => console.error(err));
    }

    handleLoad(event) {
        if (!this.loadedForm) {
            let fields = Object.values(event.detail.records)[0].fields;
            const recordId = Object.keys(event.detail.records)[0];
            this.contactRecord = {
                Id: recordId,
                ...Object.keys(fields)
                    .filter((field) => !!this.template.querySelector(`[field-name=${field}]`))
                    .reduce((total, field) => {
                        total[field] = fields[field].value;
                        return total;
                    }, {})
            };
            this.loadedForm = true;
        }
    }
    handleFieldChange(e) {
        this.contactRecord[e.currentTarget.fieldName] = e.target.value;
    }
    saveForm() {
        // if(this.validated())
        console.log('Contact for save => ', JSON.stringify(this.contactRecord));
        updateRecord({ fields: this.contactRecord })
            .then(() => {
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Success',
                        message: 'Contact updated',
                        variant: 'success'
                    })
                );
            })
            .catch((error) => {
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Error creating record',
                        message: error.body.message,
                        variant: 'error'
                    })
                );
            });
    }
}

Apex:

@AuraEnabled
public static Contact updateContact(Contact con) {
    update con;
    return con;
}

NOTE:

If you also need to use lightning-input in record-edit-form, you can refer to this example: Building an efficient LWC form without record-edit-form

Correction from question:

The problem is in :

saveGlRecord({id: this.reqId},{gl: { ...this.glRecord, sobjectType: GL_OBJECT.objectApiName } })

This will not work as all the parameters should be passed in single object:

saveGlRecord({
        id: this.reqId, 
        gl: { ...this.glRecord, sobjectType: GL_OBJECT.objectApiName } 
    })
  • your example is awesome, I have learnt new things but it is for updating the record, I am looking for inserting a new record. I have updated code in the post at the bottom but I am still stuck to send the contactRecord to apex – Mentee Aug 20 at 7:12
  • updated answer.. – salesforce-sas Aug 20 at 8:18
  • When I am printing the variable in the apex controller, it is still null, in your code import { createRecord } from 'lightning/uiRecordApi'; but it doesn't call apex controller :(. Still not working for me – Mentee Aug 20 at 15:38
  • that is standard one – salesforce-sas Aug 20 at 15:40
  • added upsertContact in answer. it should definitely work, I just checked it in my org – salesforce-sas Aug 20 at 15:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.