4

I have created an LWC with a REST API call to grab data from and external DB. The data is fetched successfully and then rendered in the component. I would then like to create a record based on the data retrieved. I have tried an onchange Event for the fields but this doesn't work because the changes are done programmatically.

How can I either trigger the onNameChange or map the json response to variables which can be used when creating the record. I am new to LWC and JS so tips on best practice would be appreciated.

<template>
    <lightning-card title="Account Quick Create" icon-name="standard:account">
        <div class="slds-m-around_medium">
                    <lightning-layout-item>
                          <lightning-combobox
                             name="progress"
                             label="Country"
                             value=""
                             placeholder="Select a Country"
                             options={options}
                             onchange={handleChange}
                            required
                            ></lightning-combobox>
                    </lightning-layout-item>
                </div>
        <div class="slds-m-around_medium">
            <lightning-layout vertical-align="end" class="slds-m-bottom_small">

                <lightning-layout-item flexibility="grow">
                    <lightning-input
                        type="search"
                        onchange={handleSearchKeyChange}
                        label="Search businesses by organization number"
                        value={searchKey}
                    ></lightning-input>
                </lightning-layout-item>
                <lightning-layout-item class="slds-p-left_xx-small">
                    <lightning-button
                        label="Search"
                        onclick={handleSearchClick}
                    ></lightning-button>
                </lightning-layout-item>
            </lightning-layout>


            <template if:true={org}>
                    <lightning-input
                    type="hidden"
                    disabled
                    data-id="accountId"
                    value={accountId}
        ></lightning-input>

                    <lightning-input type="text" label="Name" placeholder="" value={org.navn} onchange={handleNameChange}></lightning-input>
                    <lightning-input type="text" label="Address" placeholder="" value={org.forretningsadresse.adresse} disabled></lightning-input>
                    <lightning-input type="text" label="Zip/Postal Code" placeholder="" value={org.forretningsadresse.postnummer} disabled></lightning-input>
                    <lightning-input type="text" label="City" placeholder="" value={org.forretningsadresse.poststed} disabled></lightning-input>
                    <lightning-input type="number" label="Number of Employees" placeholder="" value={org.antallAnsatte} disabled></lightning-input>

                <div class="slds-align_absolute-center slds-m-around_medium">
                     <lightning-button 
                        label="Create Account"
                        variant="brand"
                        onclick={createAccount}
                    ></lightning-button>
                </div>


            </template>
            <!--
                render error message 

            <template if:true={error}>
                <c-error-panel errors={error}></c-error-panel>
            </template>

            -->
        </div>


    </lightning-card>
</template>

import { LightningElement, track } from 'lwc';

import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { createRecord } from 'lightning/uiRecordApi';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
import NAME_FIELD from '@salesforce/schema/Account.Name';
import Address_FIELD from '@salesforce/schema/Account.BillingAddress';
import Employee_FIELD from '@salesforce/schema/Account.NumberOfEmployees';




const QUERY_URL =
    'https://data.brreg.no/enhetsregisteret/api/enheter/';


export default class CreateAccount extends LightningElement {
    @track searchKey = '';
    @track org =false;
    @track error;
    @track accountId;


    name = '';


    get options() {
        return [
            { label: 'Test Picklist value', value: '' },
            { label: 'Test Picklist value', value: '' },
        ];
    }



    handleChange(event) {
        this.value = event.detail.value;
    }

    handleNameChange(event) {
        this.accountId = undefined;
        this.name = event.target.value;
   }


    handleSearchKeyChange(event) {
        this.searchKey = event.target.value;


    }

    handleSearchClick() {
        // The Fetch API is currently not polyfilled for usage in IE11.
        // Use XMLHttpRequest instead in that case.
        fetch(QUERY_URL + this.searchKey)
            .then(response => {
                // fetch isn't throwing an error if the request fails.
                // Therefore we have to check the ok property.
                if (!response.ok) {
                    this.error = response;
                }
                return response.json();

            })

            .then(jsonResponse => {
                this.org = jsonResponse;

            })
            .catch(error => {
                this.error = error;
                this.org = undefined;
            });

    }



    createAccount() {
        const fields = {};
        fields[NAME_FIELD.fieldApiName] = this.name;
        fields[Address_FIELD.fieldApiName] = '';
        fields[Employee_FIELD.fieldApiName] = '';
        const recordInput = { apiName: ACCOUNT_OBJECT.objectApiName, fields };

        createRecord(recordInput)
            .then(account => {
                this.accountId = account.id;
                this.org=false;
                this.searchKey='';
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Success',
                        message: 'Account created',
                        variant: 'success'
                    })
                );
            })
        }
    }


1

I struggled to make lightning/uiRecordApi work as well. You can use imperative apex to send JSON values and use it to create the record(s) using apex.

| improve this answer | |
  • Thanks for your answer. I am able to display the response from the GET request in the UI. I would prefer to be able to use JS to store the response to variables which can then be used to create a record instead of using Apex. Any luck with this? – Jemat Nov 4 '19 at 15:43
0

Account.BillingAddress is a compound field. Try breaking out the fields that comprise Billing Address and set those field values individually to create the record.

import ADDRESS_BILLINGSTREET_FIELD from '@salesforce/schema/Account.BillingStreet';
import ACCOUNT_BILLINGCITY_FIELD from '@salesforce/schema/Account.BillingCity';
import ACCOUNT_BILLINGSTATE_FIELD from '@salesforce/schema/Account.BillingState';
import ACCOUNT_BILLINGPOSTALCODE_FIELD from '@salesforce/schema/Account.BillingPostalCode';
import ACCOUNT_BILLINGCOUNTRY_FIELD from '@salesforce/schema/Account.BillingCountry';
| improve this answer | |

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.