erikvm
erikvm

Reputation: 928

Bind input value to specific value in object

I'm trying to build a timesheet application where users can enter the amount of hours they are working each day. I'm storing the data about each user in an object and I wish to populate an input field in a table with each respective hour (duration). To illustrate how I want to store the data, I added an image: https://i.sstatic.net/tUHUx.jpg

And also a fiddle: https://jsfiddle.net/h64wafkp/14/

Basically, each user in the database has a one-to-many relationship with another table called "hours", so the data structure looks as such:

 {
"id": 1,
"firstname": "JayZ",
"lastname": "Carter",
"email": "[email protected]",
"hours": [
  {
    "id": 226,
    "user_id": 1,
    "date": "2018-12-05",
    "duration": 140
  },
  {
    "id": 1,
    "user_id": 1,
    "date": "2018-12-02",
    "duration": 13
  },
  {
    "id": 2,
    "user_id": 1,
    "date": "2018-12-03",
    "duration": 13
  }
]

},

Then there's the table itself which is just a regular html table with each respective day as column headers. My issue is how to bind each duration to each respective date cell (see image above). Any suggestions?

Upvotes: 0

Views: 226

Answers (1)

trincot
trincot

Reputation: 349974

In your methods define a function to get the duration for a given user and date:

getDuration(user_id, date) {
    const user = this.users.find(user => user.id == user_id);
    const hour = user.hours.find(hour => hour.date == date);
    return hour ? hour.duration : 0;
},

Then in the HTML part add a :value attribute to the input element:

:value="getDuration(user.id, day)"

If you need to also bind updates to those input values back to the data structure, you'll need to define a function setDuration and call it with the following input attribute:

@input="e => setDuration(user.id, day, e.target.value)"

You would again locate the user and hour as above, but then you need to possibly add an hour object to the hours array, where you need a new id. I don't know how you would generate new id values in your case, so I'll leave that for you to implement (see comment):

setDuration(user_id, date, duration) {
    const user = this.users.find(user => user.id == user_id);
    const hour = user.hours.find(hour => hour.date == date);
    if (hour) {
        hour.duration = duration;
    } else {
        user.hours.push({
            id: getNewId(), // <--- implement this!
            user_id,
            date,
            duration
        });
    }
},

After our exchange below it turns out that your ORM will recognise an hour record needs to be inserted (instead of updated) if there is no id property, so in that case just omit the line:

            id: getNewId(), // <--- implement this!

Upvotes: 2

Related Questions