0

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);
    
           
        }
    
       
    }
2
  • Please edit your post to include a reproducible, minimum code sample. See How to Ask.
    – David Reed
    Commented Oct 22, 2021 at 18:52
  • Have edited the post, please have a look. Modified the code so that you can replace it as well. Thanks.
    – Ajay
    Commented Oct 22, 2021 at 20:07

2 Answers 2

0

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.

0

Thanks @NickCook for the suggestion. Yes the user must pick the picklist value from the drop down and hence we went with combo boxes. But what I found out is - it is not possible to insert a dependent picklist field using LDS without giving the value of controlling field.

Hence I went with Salesfroce javascript API (Create Method) - using this way I was able to import the fields and add it with a fields variable (variable with {} type) so that I can add the values for these fields by picking the values from the UI using template.query selector and have also had to hard code the controlling field value so that both go in.

The reason I went with this is because the user should not see controlling field but should see dependent field and should be able to save the case.

Thanks to JS API methods which saved my time.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .