I have a form to collect user data, and I want to be able to update collection fields for existing users or add new records for new users. The user can use a pulldown box to select their name from the collection (this was pre-loaded with a collection query). Right now I’m struggling with “update” but I might be back soon to talk about “Insert”.
I capture the ID of the record, use wixData.get() to grab the record, update the field in question, and use wixData.update() push it back to the collection. No errors are thrown by the code, but nothing is getting updated in the colleciton. I used some console.log() messages to check the ID that I grabbed from the original query and the ID that is being used for the Get-Update functions.
The code below has the following:
- Collection is named “TV”
- “full” is the field name in the collection, and #dbFullName is the user input dropdown box. These two things I use to get the current ID (maybe there’s a better way to do this?)
- “lastName” is the field in the collection that I’m trying to update (for testing, but eventually I want users to be able to update any field).
The code:
export function cmdUpdate_click(event) {
var id; // define variable for the record ID
// run query to grab the record for the current user.
// User selects their name in the #dbFullName dropdown box
wixData.query(“TV”)
.contains(“full”, $w(“#dbFullName”).value)
.find() // Run the query
.then(res => {
// grab the id from the current page of the query
if(res.items.length > 0){
id = res.items[res.currentPage][“_id”];
console.log(id)
}
});
wixData.get(“TV”, id)
.then( (item) => {
item.lastName = $w(“#tbLastName”).value; // updated last name.
//I’ve also tried hardcoding “Smith” for the value, but still not update…
wixData.update(“TV”, item);
} )
.catch( (err) => {
let errorMsg = err;
} );
Does anyone see a problem with the code, or if there are questions about setup of the page, etc, I can provide more info. I’ve also tried an alternative method, shown below, but still no update of the collection.
export function cmdUpdate_click(event) {
var id; // define variable for the record ID
// run query to grab the record for the current user.
// User selects their name in the #dbFullName dropdown box
wixData.query(“TV”)
.contains(“full”, $w(“#dbFullName”).value)
.find() // Run the query
.then(res => {
// grab the id from the current page of the query
if(res.items.length > 0){
id = res.items[res.currentPage][“_id”];
console.log(id)
}
});
let toUpdate = {
“id”: id,
“full”: $w(“#tbLastName”).value + “, " + $w(”#tbFirstName").value,
“firstName”: $w(“#tbFirstName”).value,
“lastName”: $w(“#tbLastName”).value,
“email”: $w(“#tbEmail”).value,
“phone”: $w(“#tbPhone”).value,
“gender”: $w(“#rbGender”).value,
“homeCourse”: $w(“#dbHomeCourse”).value
};
wixData.update(“TV”, toUpdate)
.then( (results) => {
let item = results;
})
. catch ( (err) => {
let errorMsg = err;
});
}
Can anyone help with this?