1

I have over 100 input field values in HTML that will be passed to a SObject created in the LWC JS. The SObject will be passed to the server side to persist data.

Every time there is a new input field value, I would have to create a onChange, a function to store value to a variable then pass it to the SObject. Is there a better to do this?

Example for 1 input field:

HTML

<lightning-input 
    type="text"
    label="Notes"
    value={note}
    onchange={handle_note} > 
</lightning-input>

JS

@api note;

handle_note(event) {
    this.note = event.detail.value;
}
    
handle_Submit(event){
        let cust = {
            sobjectType: "Cust__c"
          };
cust.note = this.note
... // Pass sobject to the server side to persist data

1 Answer 1

1

JavaScript allows use to access fields dynamically, using array notation, so we write our handler as:

handleChange (event) {
  this.record[event.target.name] = event.target.value;
}

Then we just set the name:

<lightning-input 
  type="text"
  label="Notes"
  name="Note__c"
  value={note}
  onchange={handleChange} > 
</lightning-input>

From here, you can actually just set the handler on a common parent element:

<div onchange={handleChange}>
  Put your input elements here...
</div>
4
  • So I should set the handler on a common parent instead of having one inside each input field? Because every event.target.value will be stored to their their name field accordingly
    – ApexCowboy
    Commented Dec 1, 2021 at 22:10
  • @ApexCowboy I wrote an example where we use dynamic form rendering for you. It really can be this simple.
    – sfdcfox
    Commented Dec 1, 2021 at 22:53
  • Thanks your solution works great. --- I might open a new question for this later: I successfully passed all data to SObject this.note which is declared globally, but the handleSubmit that passes it to the backend for storing doesn't seem to recognize it in the function.
    – ApexCowboy
    Commented Dec 1, 2021 at 23:32
  • All is good! Fixed minor issue, cheers
    – ApexCowboy
    Commented Dec 1, 2021 at 23:51

You must log in to answer this question.

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