How can I dynamically assign a value to a lightning record form?

For example, my component has the following section that displays a record form:

<template if:true={showRecordForm}>
    <lightning-record-form
        object-api-name={sObjectApiName}
        onsuccess={handleFormSuccess}
        record-type-id={recordTypeId}
        layout-type="Full"
        columns="2"
        oncancel={handleFormCancel}
        onload={handleFormLoad}>
    </lightning-record-form>
</template>

It will load the form for the object I specify in sObjectApiName, and with the specified record type as well. The problem is that I want to assign some values to specific fields.

Let us say that it is a Case form, and I want to assign an Account ID to the AccountId field, before the case is submitted to the platform.

I tried to query the lightning-input-fields, but with no success:

const inputFields = this.template.querySelectorAll(
    'lightning-input-field'
);
if (inputFields) {
    inputFields.forEach(field => {
        console.log(field)
    });
}

This is a snippet from the documentation of lightning-record-edit-form.

I’m starting to think that this might not be viable, or too much trouble. Is there a way to do this?

Answer

You are trying to use edit form, why dont use – record-edit and try passing values

@track recordInfo = {
    fields: [
        { name: "AccountId", value: "001000000000000AAA" },
        { name: "Description", value: "Description of this record." }
    ]
}

get recordInfoDefined () {
    return this.recordInfo !== undefined && this.recordInfo.fields !== undefined
}
<lightning-record-edit-form
    object-api-name="Case">
    <template if:true={recordInfoDefined} for:each={recordInfo.fields} for:item="field">
        <lightning-input-field
            key={field.name}
            field-name={field.name}
            value={field.value}>
        </lightning-input-field>
    </template>
</lightning-record-edit-form>

Attribution
Source : Link , Question Author : Renato Oliveira , Answer Author : Kris Goncalves

Leave a Comment