1

To create records for each objects we are using Navigation Mixin, But we tried searching the product field in the Opportunity Product we are facing some salesforce error which are attached below.enter image description here

A solution we tried for this problem by using lightning-record-edit-form which is working fine, But in our scenario we are pre-populating some of our fields during the page load and which can't be done using lightning-record-edit-form.

Any workaround for this?

1 Answer 1

0

You can try this below code which will create/prepopulate the values that could be invoked from any record page and prepopulate default values on the record creation screen of a different Object

This goal emanated from the need to create a custom object record from the Opportunity record, via clicking a quick action, prepopulating the values from the Opportunity on the record creation screen before the record actually got created by the user clicking 'Save' within the modal.

The solution uses a custom metadata type for the field mapping (to map source object to default value on destination object).

enter image description here

navToNewRecCreateModalWithDefaults.js

// LWC used to prepopulate values on a record creation modal, invoked from a quick action
// Note: this LWC depends on the quick action API name being in the following format:
//  ObjectName_XXXXX_QuickActionName

//  Example: Quote_Request_c_XXXXX_New_Quote_Request_V2
// Note: if dealing with custom object, you cannot use __c in the naming convention above due to
//  Salesforce system limitation.
import { LightningElement, api, wire } from "lwc";
import { ShowToastEvent } from "lightning/platformShowToastEvent";
import { encodeDefaultFieldValues } from "lightning/pageReferenceUtils";
import retrieveDefaultValues from "@salesforce/apex/DefaultValuesLwcController.retrieveDefaultValues";

import getFilesOnRecord from "@salesforce/apex/ApexUtils.getFilesOnRecord";
import { CurrentPageReference } from "lightning/navigation";
import { NavigationMixin } from "lightning/navigation";

export default class DefaultValuesComponent extends NavigationMixin(
LightningElement
) {
sObjectApiName = "";
quickActionAPIName = "";
_recordId;
retrievedRecordId = false;
  @wire(CurrentPageReference)
  getStateParameters(currentPageReference) {
    // if the page is a quick action, get quick action API name
    if (currentPageReference.type === "standard__quickAction") {
      let quickActionPath = currentPageReference.attributes.apiName;
      let firstSplit = quickActionPath.split(".")[1];
      let sObjectApiName = firstSplit.split("_XXXXX_")[0];
      if (sObjectApiName.includes("_c")) {
        sObjectApiName = sObjectApiName.replace("_c", "__c");
      }
  this.sObjectApiName = sObjectApiName;`
`      this.quickActionAPIName = firstSplit.split("_XXXXX_")[1];
 }}

@api set recordId(value) {
this._recordId = value;}

 get recordId() {
return this._recordId;}
 /**
* Renderedcallback to call our main method to navigate to new quote request record creation screen and load defaults*/
renderedCallback() {
if (!this.retrievedRecordId && this.recordId) {
  this.retrievedRecordId = true; // Escape case from recursion
  this.retrieveDefaultValuesMethod();
}}
 /**
* Method to perform the retrieval of default values from the opportunity/business and populate
*  those in the Quote Request record creation form
*/
 retrieveDefaultValuesMethod() {
const quickActionApiName = String(this.quickActionAPIName);
// call apex controller method to retrieve the default values:
retrieveDefaultValues({
  recordId: this.recordId,
  quickActionApiNameParam: quickActionApiName
})
  .then((result) => {
    const defaultValues = encodeDefaultFieldValues(result);
    this[NavigationMixin.Navigate]({
      type: "standard__objectPage",

      attributes: {
        objectApiName: this.sObjectApiName,
        actionName: "new"
      },

      state: {
        defaultFieldValues: defaultValues
      }
    });
  })
  .catch((error) => {
    this.dispatchEvent(
      new ShowToastEvent({
        title: "Error querying record",
        message: error.body.message,
        variant: "error",
        mode: "sticky"
      })
    );
  });}}

navToNewRecCreateModalWithDefaults.html:

<template>
 <div style="display: none">{recordId}</div></template>

DefaultValuesLwcController.cls:

public class DefaultValuesLwcController {
private static String quickActionApiName;
private static String parentObjectName;
 /**
 * @description: singleton method to query default values
 * @return defaultValueFieldMappings (List<Default_Value_Field_Mapping__mdt>: a list of default value pairs
 */
 private static List<Default_Value_Field_Mapping__mdt> defaultValueFieldMappings {
    get {
        if (defaultValueFieldMappings == null) {
            defaultValueFieldMappings = [
                SELECT Parent_Object_Field__c, Target_Object_Field__c
                FROM Default_Value_Field_Mapping__mdt
                WHERE Quick_Action_API_Name__c = :quickActionApiName AND Parent_Object_Name__c = :parentObjectName
            ];
        }
        return defaultValueFieldMappings;
    }
    set;
}
 /**
 * @description: method to map the target field to the associated queried value from the parent object
 * @param record (SObject): the queried parent record
 * @param quickActionApiName (String): the name of the quick action interfacing with this controller
 * @return the queried record
 */
 private static Map<String, String> getDefaultValuesFieldMap(SObject record, String quickActionApiName) {
    Map<String, String> defaultValuesFieldMap = new Map<String, String>();
    for (Default_Value_Field_Mapping__mdt dvfm : defaultValueFieldMappings) {
        Object fieldValueObj = record.get(dvfm.Parent_Object_Field__c);
        String parentObjFieldValue;
        if (fieldValueObj instanceof Date) {
            parentObjFieldValue = String.valueOf((Date) record.get(dvfm.Parent_Object_Field__c));
        } else {
            parentObjFieldValue = String.valueOf(record.get(dvfm.Parent_Object_Field__c));
        }
        defaultValuesFieldMap.put(dvfm.Target_Object_Field__c, parentObjFieldValue);
    }
    return defaultValuesFieldMap;
}

/**
 * @description: method to query custom fields, since the out-of-box lwc getRecords can't do it effectively
 * @param recordId (Id): Id of the record to query
 * @param quickActionApiName (String): the name of the quick action invoking this apex method
 * @return the queried record
 */
@AuraEnabled
public static Map<String, String> retrieveDefaultValues(Id recordId, String quickActionApiNameParam) {
    System.debug('DefaultValuesLwcController.retrieveDefaultValues quickActionApiNameParam: ' + quickActionApiNameParam);
    try {
        quickActionApiName = quickActionApiNameParam;
        parentObjectName = String.valueOf(recordId.getSobjectType());
        List<String> fieldsToQuery = new List<String>();
        for (Default_Value_Field_Mapping__mdt dvfm : defaultValueFieldMappings) {
            fieldsToQuery.add(dvfm.Parent_Object_Field__c);
        }

        String queryString = 'SELECT ' + String.join(fieldsToQuery, ', ') + ' FROM ' + parentObjectName + ' WHERE Id = :recordId';
        System.debug('DefaultValuesLwcController.retrieveDefaultValues queryString: ' + queryString);
        SObject record = Database.query(queryString);

        return getDefaultValuesFieldMap(record, quickActionApiName);
    } catch (Exception e) {
        System.debug('DefaultValuesLwcController.retrieveDefaultValues exception: ' + e.getMessage() + ', ' + e.getStackTraceString());
        throw new AuraHandledException(e.getMessage());
    }
}}
2
  • this code was posted by someone few days back in this community. can you add reference to the original author in your answer so that original author gets due credit for his work. thanks. May 2 at 18:30
  • @pavan, Thanks for your response. For opportunity working fine, if i tired the same for Opportunity product, i got error while search the product field. May 3 at 5:01

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.