Hide controlling field and how to pass values of controlling,dependent picklist fields to save record using Lightning record edit form – lwc

dependent-picklistlightninglightning-data-servicelightning-recordeditformlightning-web-components

I have created a form using lightning record edit form which basically has few case object standard fields and a controlling and a dependent field. I was able to default the controlling field value in the JS and was able to pass the controlling field value to the dependent field in the JS and was able to display only the dependent picklist field and its values on the UI.

I am able to save the form by selecting value from the dependent picklist and standard fields which I had on the form. However once the record gets created using LDS from the lightning record edit form there are no values in the controlling as well as dependent picklist fields.

How can I handle this?. I am saving the form using the lightning button and on button do I have to do anything?

Code:

HTML:

 <template>
    <div class="slds-p-bottom_large slds-p-left_large" style="width:500px">

        <div class="slds-text-heading_large">
            <div  class="slds-text-align_center">Create Type 1 case</div></div>
            
        <template if:true={userClassification}>
       <!-- using the onsuccess attribute on the record edit form I had a JS function which will pull the record Id and navigate the user to the record detail in a community portal-->      
                <lightning-record-edit-form object-api-name="Case" layout-type = "Full" onsuccess={handleSuccess}>
                    <lightning-messages></lightning-messages>
                    <lightning-layout>
                        <lightning-layout-item size="12">
                        <lightning-input-field 
                        field-name="ContactId"                        
                          value={contactId}>
                    </lightning-input-field>
                                       
                    <lightning-input-field field-name="Field1">
                    </lightning-input-field>                 
                        
                      
                           
                        </lightning-layout-item>
                        
                        <lightning-layout-item size="12">
                   
              <!-- this is the dependent picklist field-->          
                            <lightning-combobox label="Field2"
                            name="Field2"                                                         
                            options={finalDependentVal} 
                            value={selectedControlling}
                            disabled={dependentDisabled}                                    
                            >
                        </lightning-combobox>
                    </lightning-layout-item>
                    </lightning-layout>
<!-- the below button will be saving the form-->
                    <lightning-button type="submit"
                                      name="submit"
                                      label="Confirm"
                                      onclick={showNotification}
                                      >
                        </lightning-button>
                    
                </lightning-record-edit-form> 
                      
    </template>  

    
    </div>


   
</template>

JS:

    import { LightningElement,wire,track,api } from 'lwc';
    import { getRecord, getFieldValue } from "lightning/uiRecordApi";
    import CONTACT_ID from "@salesforce/schema/User.ContactId";
    
    // this gets you the logged in user
    import USER_ID from "@salesforce/user/Id";
    import getUserDetails from '@salesforce/apex/ABC.ABC';
    import { CurrentPageReference ,NavigationMixin } from 'lightning/navigation';
    import { getPicklistValuesByRecordType,getObjectInfo  } from 'lightning/uiObjectInfoApi';
    import CASE_OBJECT from '@salesforce/schema/Case';
    
    export default class ISTCP_Create_Case_From_Portal extends  NavigationMixin(LightningElement) {
       
        @api variable1;
        @api variable2;
        @api variable3;
        @api variable4;
    
        @api userClassification;
    
        @api variable5;
        @api variable6;
    
        @api contactId;
    
        @track correctRecordTypeId;
    
        @api caseId;
        
        controllingPicklist=[];
        dependentPicklist;
        @track finalDependentVal = [];
        @track selectedControlling = "--None--";
    
     
        showpicklist = false;
        dependentDisabled=true;
        showdependent = false;
    
    
        connectedCallback() {
    
            getUserDetails()
           .then(result => {          
                this.userAudience = result;
                if(this.userAudience === 'xyz'){
                    this.userClassification = false;
                }
                else if (this.userAudience === 'abc'){
                    this.userClassification = true;
                }
                else{
                    console.log('#### else statement')
                }
               
            }).catch(error => {
                console.log(error);
                this.showErrorToast(error);
            });
    
    
        }
    
    
        @wire(getRecord, { recordId: USER_ID, fields: [CONTACT_ID] })
        user;
      
        get contactId() {
            this.contactId = getFieldValue(this.user.data, CONTACT_ID);
          return getFieldValue(this.user.data, CONTACT_ID);
        }
    
        @wire(CurrentPageReference)
        pageRef;
    
       
    // fetching the required record type Id
        @wire(getObjectInfo, { objectApiName: CASE_OBJECT })
        wiredObjectInfo({error, data}) {
            if (error) {
              // handle Error
            } else if (data) {
                const rtis = data.recordTypeInfos;
            this.correctRecordTypeId = Object.keys(rtis).find(rti => rtis[rti].name === 'abcrecordtype');
            console.log('this record type id is',this.correctRecordTypeId);
           
            }
          };
    
// fetching the dependent picklist values by hard-coding the values of controlling field value

        @wire(getPicklistValuesByRecordType, { objectApiName: CASE_OBJECT, recordTypeId: '$correctRecordTypeId'})
        fetchPicklistValuesForGPTIForHowCanWeHelpYouField({error,data}){
            if (error) {
                console.log('unable to fetch values')
              }
            
           else if(data && data.picklistFieldValues){
                let optionsValue = {}
                optionsValue["label"] = "--None--";
                optionsValue["value"] = "--None--";
                this.controllingPicklist.push(optionsValue);
              
                data.picklistFieldValues["controllingFieldAPIName"].values.forEach(optionData => {
                    this.controllingPicklist.push({label : "ABC", value :"ABC"});
                });
                this.dependentPicklist = data.picklistFieldValues["Field2"];
              //  this.showpicklist = true;
    
                this.finalDependentVal=[];
              //  this.showdependent = false;
                const selectedVal = "ABC";
                this.finalDependentVal.push({label : "--None--", value : "--None--"})
                let controllerValues = this.dependentPicklist.controllerValues;
                this.dependentPicklist.values.forEach(depVal => {
                    depVal.validFor.forEach(depKey =>{
                        if(depKey === controllerValues[selectedVal]){
                            this.dependentDisabled = false;
                           // this.showdependent = true;
                            this.finalDependentVal.push({label : depVal.label, value : depVal.value});
                        }
                    });
                     
                });
               
            }
        }
       
    // this handleSuccess method will pull record Id and will navigate to the record detail in the community portal

        handleSuccess(event){
            const payload = event.detail;
            var objJSON = JSON.parse(JSON.stringify(payload)); 
            let caseRecordId = objJSON["id"];       
         
            this[NavigationMixin.Navigate]({
                type: 'standard__webPage',
                attributes: { 
                    url: '/case/' + objJSON["id"] + '/' +  "detail"
                    
                }
            });
        }
    
        showNotification() {
            const evt = new ShowToastEvent({
                title: "Case Created Successfully",
                message: "Please check the portal cases list view for the case created",
                variant: "success",
            });
            this.dispatchEvent(evt);
    
           
        }
    
       
    }

Best Answer

A lightning-record-edit-form will only automatically insert data for fields defined with the lightning-input-field component.

You've used a lightning-combobox for your dependent picklists, which means you need to manually process these so it's added to your record.

Is there any reason you're not just using the standard lightning-input-field for these? What happends if you replace the comboboxes with an input-field?

If you must do it custom, you're going to need to define a handlesubmit method that gets the values of these comboboxes and adds it to the record before inserting/updating.

Related Topic