Updating the query data in cloud firestore nested map fields - javascript

I'm trying to update the data in nested map fields in firestore, my form is a window form that has 4 sides (wSide1,wSide2,wSide3,wSide4), what my form is doing is if customer select 1 field which is wSide1 and it needs to be updated then only this field only be updated but in my case it is updating all 4 sides, the one which is selected for example side 1 only that has the correct updated values other 3 sides updates with the false values. as my form is dynamic it only shows the field which is selected.
I only want to update the field which is selected, all other has to be null.
js & firestore query
function updateWindowForm(form, type){
var name = $('#name_'+type).val();
var type = $('#type_'+type).val();
const taskformWindow = document.getElementById("taskformWindow");
let editStatus = false;
let id = '';
const updateTask = (id, updatedTask) => db.collection('Buildings').doc(buildingID).collection('rooms').doc(roomID).collection('objects').doc(objectID).update(updatedTask);
window.addEventListener("DOMContentLoaded", async (e) => {
id = doc.id;
editStatus = true;
btnsEdit.forEach((btn) => {
btn.addEventListener("click", async (e) => {
try {
const doc = await getTask(e.target.dataset.id);
const task = doc.data();
editStatus = true;
id = doc.id;
taskformWindow["btn-update-data"].innerText = "Update";
} catch (error) {
console.log(error);
}
});
});
});
taskformWindow.addEventListener("click", async (e) => {
e.preventDefault();
var name_Window = document.getElementById('name_Window').value;
var wAluminium = document.getElementById('wAluminium').checked;
var wColorMeasurement = document.getElementById('wColorMeasurement').value;
var wComments = document.getElementById('wComments').value;
var wForEnd1 = document.getElementById('wForEnd1').checked;
var wForEnd2 = document.getElementById('wForEnd2').checked;
var wSideOfWindows = document.getElementById('wSideOfWindows').value;
var wHardwareManufacturer = document.getElementById('wHardwareManufacturer').value;
var wPlastic = document.getElementById('wPlastic').checked;
//Side 1
var wAxis1_1 = document.getElementById('wAxis1_1').checked;
var wAxis1_2 = document.getElementById('wAxis1_2').checked;
var wBackSet1 = document.getElementById('wBackSet1').value;
var wDirectionLR1_1 = document.getElementById('wDirectionLR1_1').checked;
var wDirectionLR1_2 = document.getElementById('wDirectionLR1_2').checked;
var wHandleHeight1 = document.getElementById('wHandleHeight1').value;
var wOverlapWidth1 = document.getElementById('wOverlapWidth1').value;
var wSashRebateHeight1 = document.getElementById('wSashRebateHeight1').value;
var wSashRebateWidth1 = document.getElementById('wSashRebateWidth1').value;
//Side 2
var wAxis2_1 = document.getElementById('wAxis2_1').checked;
var wAxis2_2 = document.getElementById('wAxis2_2').checked;
var wBackSet2 = document.getElementById('wBackSet2').value;
var wDirectionLR2_1 = document.getElementById('wDirectionLR2_1').checked;
var wDirectionLR2_2 = document.getElementById('wDirectionLR2_2').checked;
var wHandleHeight2 = document.getElementById('wHandleHeight2').value;
var wOverlapWidth2 = document.getElementById('wOverlapWidth2').value;
var wSashRebateHeight2 = document.getElementById('wSashRebateHeight2').value;
var wSashRebateWidth2 = document.getElementById('wSashRebateWidth2').value;
//Side 3
var wAxis3_1 = document.getElementById('wAxis3_1').checked;
var wAxis3_2 = document.getElementById('wAxis3_2').checked;
var wBackSet3 = document.getElementById('wBackSet3').value;
var wDirectionLR3_1 = document.getElementById('wDirectionLR3_1').checked;
var wDirectionLR3_2 = document.getElementById('wDirectionLR3_2').checked;
var wHandleHeight3 = document.getElementById('wHandleHeight3').value;
var wOverlapWidth3 = document.getElementById('wOverlapWidth3').value;
var wSashRebateHeight3 = document.getElementById('wSashRebateHeight3').value;
var wSashRebateWidth3 = document.getElementById('wSashRebateWidth3').value;
//Side 4
var wAxis4_1 = document.getElementById('wAxis4_1').checked;
var wAxis4_2 = document.getElementById('wAxis4_2').checked;
var wBackSet4 = document.getElementById('wBackSet4').value;
var wDirectionLR4_1 = document.getElementById('wDirectionLR4_1').checked;
var wDirectionLR4_2 = document.getElementById('wDirectionLR4_2').checked;
var wHandleHeight4 = document.getElementById('wHandleHeight4').value;
var wOverlapWidth4 = document.getElementById('wOverlapWidth4').value;
var wSashRebateHeight4 = document.getElementById('wSashRebateHeight4').value;
var wSashRebateWidth4 = document.getElementById('wSashRebateWidth4').value;
try {
if (!editStatus) {
await updateTask(id, {
name:name_Window,
Form:{
wAluminium: wAluminium,
wColorMeasurement: wColorMeasurement,
wComments: wComments,
wForEnd1: wForEnd1,
wForEnd2: wForEnd2,
wHardwareManufacturer: wHardwareManufacturer,
wPlastic: wPlastic,
wSide1:{
wAxis1_1: wAxis1_1,
wAxis1_2: wAxis1_2,
wBackSet1: wBackSet1,
wDirectionLR1_1: wDirectionLR1_1,
wDirectionLR1_2: wDirectionLR1_2,
wHandleHeight1: wHandleHeight1,
wOverlapWidth1: wOverlapWidth1,
wSashRebateHeight1: wSashRebateHeight1,
wSashRebateWidth1: wSashRebateWidth1,
},
wSide2:{
wAxis2_1: wAxis2_1,
wAxis2_2: wAxis2_2,
wBackSet1: wBackSet2,
wDirectionLR2_1: wDirectionLR2_1,
wDirectionLR2_2: wDirectionLR2_2,
wHandleHeight2: wHandleHeight2,
wOverlapWidth2: wOverlapWidth2,
wSashRebateHeight2: wSashRebateHeight2,
wSashRebateWidth2: wSashRebateWidth2,
},
wSide3:{
wAxis3_1: wAxis3_1,
wAxis3_2: wAxis3_2,
wBackSet1: wBackSet3,
wDirectionLR3_1: wDirectionLR3_1,
wDirectionLR3_2: wDirectionLR3_2,
wHandleHeight3: wHandleHeight3,
wOverlapWidth3: wOverlapWidth3,
wSashRebateHeight3: wSashRebateHeight3,
wSashRebateWidth3: wSashRebateWidth3,
},
wSide4:{
wAxis4_1: wAxis4_1,
wAxis4_2: wAxis4_2,
wBackSet4: wBackSet4,
wDirectionLR4_1: wDirectionLR4_1,
wDirectionLR4_2: wDirectionLR4_2,
wHandleHeight4: wHandleHeight4,
wOverlapWidth4: wOverlapWidth4,
wSashRebateHeight4: wSashRebateHeight4,
wSashRebateWidth4: wSashRebateWidth4,
},
wSideOfWindows: wSideOfWindows,
}
})
editStatus = false;
id = '';
taskformWindow['btn-update-window-data'].innerText = 'Daten aktualisiert';
swal("", "Daten wurden aktualisert!", "success");
}
taskformWindow.reset();
} catch (error) {
console.log(error);
}
});
}

I can't see the code you use for updating your data but I can ausme that you probably did not set the merge to true while saving the data.
Take a look at this code snipped:
var cityRef = db.collection('cities').doc('BJ');
var setWithMerge = cityRef.set({
capital: true
}, { merge: true });
By setting that we ensure to udate only the fields we want to and leave the rest as it is. Still make sure not to send fields with a null value because that is a valid value for firestore and it doesn't mean that those fields will by skipped in the update process. You can find more about it here.

Related

How can I access data from loaded from an IndexedDB objectStore?

Here is my code I want to return getConn.result and use it in my js page. Could you help me?
function readObjectStore(storeName) {
// Open (or create) the database
var open = indexedDB.open("Publisher", 1);
open.onupgradeneeded = function () {}
open.onsuccess = function () {
var db = open.result;
var tx = db.transaction(storeName, "readwrite");
var store = tx.objectStore(storeName);
if (storeName == "connectionStrings") {
var getConn = store.getAll();
getConn.onsuccess = function () {
return getConn.result;
}
}
}
}

JavaScript Web Resource issue: getGrid() suddenly started failing

I have a few different JavaScript web resources that use the getGrid(), all of which started failing this week after I enabled the 2020 Wave 1 Updates in D365. The error message shows:
"Error occurred :TypeError: Unable to get property 'getGrid' of undefined or null reference"
Here is my code:
function GetTotalResourceCount(executionContext) {
console.log("function started");
var execContext = executionContext;
var formContext = executionContext.getFormContext();
var resourceyescount = 0;
try {
var gridCtx = formContext._gridControl;
var grid = gridCtx.getGrid();
var allRows = grid.getRows();
var duplicatesFound = 0;
//loop through rows and get the attribute collection
allRows.forEach(function (row, rowIndex) {
var thisRow = row.getData().entity;
var thisRowId = thisRow.getId();
var thisResource = "";
var thisResourceName = "";
var thisResourceID = "";
console.log("this row id=" + thisRowId);
var thisAttributeColl = row.getData().entity.attributes;
thisAttributeColl.forEach(function (thisAttribute, attrIndex) {
var msg = "";
if (thisAttribute.getName() == "new_resource") {
thisResource = thisAttribute.getValue();
thisResourceID = thisResource[0].id;
thisResourceName = thisResource[0].name;
console.log("this resource name=" + thisResourceName)
}
});
var allRows2 = formContext.getGrid().getRows();
//loop through rows and get the attribute collection
allRows2.forEach(function (row, rowIndex) {
var thatRow = row.getData().entity;
var thatRowId = thatRow.getId();
var thatAttributeColl = row.getData().entity.attributes;
var thatResource = "";
var thatResourceName = "";
var thatResourceID = "";
thatAttributeColl.forEach(function (thatAttribute, attrIndex) {
if (thatAttribute.getName() == "new_resource") {
thatResource = thatAttribute.getValue();
thatResourceID = thatResource[0].id;
thatResourceName = thatResource[0].name;
if (thatResourceID == thisResourceID && thatRowId != thisRowId) {
duplicatesFound++;
var msg = "Duplicate resource " + thatResource;
console.log("duplicates found= " + duplicatesFound);
}
}
});
});
});
if (duplicatesFound > 0) {
console.log("duplicate found");
Xrm.Page.getAttribute("new_showduplicateerror").setValue(true);
Xrm.Page.getControl("new_showduplicateerror").setVisible(true);
Xrm.Page.getControl("new_showduplicateerror").setNotification("A duplicate resource was found. Please remove this before saving.");
} else {
Xrm.Page.getAttribute("new_showduplicateerror").setValue(false);
Xrm.Page.getControl("new_showduplicateerror").setVisible(false);
Xrm.Page.getControl("new_showduplicateerror").clearNotification();
}
} catch (err) {
console.log('Error occurred :' + err)
}
}
Here is a separate web resource that triggers the function:
function TriggerSalesQDResourceCount(executionContext){
var formContext = executionContext.getFormContext();
formContext.getControl("s_qd").addOnLoad(GetTotalResourceCount);
}
Any ideas how I can fix this? Is this a known issue with the new D365 wave 1 update?
Thanks!
This is the problem with unsupported (undocumented) code usage, which will break in future updates.
Unsupported:
var gridCtx = formContext._gridControl;
You have to switch to these supported methods.
function doSomething(executionContext) {
var formContext = executionContext.getFormContext(); // get the form Context
var gridContext = formContext.getControl("Contacts"); // get the grid context
// Perform operations on the subgrid
var grid = gridContext.getGrid();
}
References:
Client API grid context
Grid (Client API reference)

How to show popup error in Point of Sale in odoo 12

I want to restrict the user from adding more product to sell if the order is tag as booked order
I want to show popup error message when it is booked order and the user still click the product
here is my code
odoo.define('tw_pos_inherit_model.attemptInherit', function (require) {
"use strict";
var POSInheritmodel = require('point_of_sale.models');
var ajax = require('web.ajax');
var BarcodeParser = require('barcodes.BarcodeParser');
var PosDB = require('point_of_sale.DB');
var devices = require('point_of_sale.devices');
var concurrency = require('web.concurrency');
var config = require('web.config');
var core = require('web.core');
var field_utils = require('web.field_utils');
var rpc = require('web.rpc');
var session = require('web.session');
var time = require('web.time');
var utils = require('web.utils');
var gui = require('point_of_sale.gui');
var orderline_id = 1;
var QWeb = core.qweb;
var _t = core._t;
var Mutex = concurrency.Mutex;
var round_di = utils.round_decimals;
var round_pr = utils.round_precision;
var _super_order = POSInheritmodel.Order.prototype;
POSInheritmodel.Order = POSInheritmodel.Order.extend({
add_product: function(product, options){
var can_add = true;
var changes = this.pos.get_order();
var self = this;
try{
if(changes.selected_orderline.order.quotation_ref.book_order){
can_add= false;
}
}catch(err){}
if (can_add){
if(this._printed){
this.destroy();
return this.pos.get_order().add_product(product, options);
}
this.assert_editable();
options = options || {};
var attr = JSON.parse(JSON.stringify(product));
attr.pos = this.pos;
attr.order = this;
var line = new POSInheritmodel.Orderline({}, {pos: this.pos, order: this, product: product});
if(options.quantity !== undefined){
line.set_quantity(options.quantity);
}
if(options.price !== undefined){
line.set_unit_price(options.price);
}
//To substract from the unit price the included taxes mapped by the fiscal position
this.fix_tax_included_price(line);
if(options.discount !== undefined){
line.set_discount(options.discount);
}
if(options.discount_percentage !== undefined){
line.set_if_discount_percentage(options.discount_percentage);
}
if(options.discount_amount !== undefined){
line.set_if_discount_amount(options.discount_amount);
}
if(options.extras !== undefined){
for (var prop in options.extras) {
line[prop] = options.extras[prop];
}
}
var to_merge_orderline;
for (var i = 0; i < this.orderlines.length; i++) {
if(this.orderlines.at(i).can_be_merged_with(line) && options.merge !== false){
to_merge_orderline = this.orderlines.at(i);
}
}
if (to_merge_orderline){
to_merge_orderline.merge(line);
} else {
this.orderlines.add(line);
}
this.select_orderline(this.get_last_orderline());
if(line.has_product_lot){
this.display_lot_popup();
}
}else{
self.gui.show_popup('error',{
title :_t('Modification Resctricted'),
body :_t('Booked Order cannot be modified'),
});
}
},
});
});
but im getting an error
Uncaught TypeError: Cannot read property 'show_popup' of undefined
http://localhost:8071/web/content/554-cbfea6c/point_of_sale.assets.js:475
Traceback:
TypeError: Cannot read property 'show_popup' of undefined
at child.add_product (http://localhost:8071/web/content/554-cbfea6c/point_of_sale.assets.js:475:116)
at Class.click_product (http://localhost:8071/web/content/554-cbfea6c/point_of_sale.assets.js:326:257)
at Object.click_product_action (http://localhost:8071/web/content/554-cbfea6c/point_of_sale.assets.js:325:951)
at HTMLElement.click_product_handler (http://localhost:8071/web/content/554-cbfea6c/point_of_sale.assets.js:320:1738)
im sorry im really confuse do i still need to initialized the this.gui first?
even though i have var gui = require('point_of_sale.gui'); initialized already
when i log the this.gui to my console the output is undefined
You can access gui via posModel.
self.pos.gui.show_popup('error',{
title :_t('Modification Resctricted'),
body :_t('Booked Order cannot be modified'),
});
You can check an example at connect_to_proxy

How can I make changing text with Firebase Database?

I have this code to get some text from Firebase Database
var reviewID = 0;
var dataRef = firebase.database().ref("reviews/" + reviewID);
function getReview() {
dataRef.once("value").then(function (snapshot) {
const reviewName = snapshot.val().name;
const reviewText = snapshot.val().text;
const reviewDate = snapshot.val().date;
$('#reviewName').html(reviewName);
$('#reviewText').html(reviewText);
$('#reviewDate').html(reviewDate);
});
};
getReview();
And I have this structure in Firebase.
I want button to change reviewID so I must get different values of reviewName, reviewText and reviewDate. Here is code for this button:
$('#reviewButtonRight').click(function () {
reviewID += 1;
getReview();
});
But it doesn't work. So how can I fix it?
You need to create a new ref each time
var reviewID = 0;
var reviewRef = firebase.database().ref("reviews");
function getReview() {
const review = reviewRef.child(reviewID);
review.once("value").then(function (snapshot) {
const reviewName = snapshot.val().name;
const reviewText = snapshot.val().text;
const reviewDate = snapshot.val().date;
$('#reviewName').html(reviewName);
$('#reviewText').html(reviewText);
$('#reviewDate').html(reviewDate);
});
};
getReview();

How to ignore empty fields in Ionic / Firebase?

I have a function for the user to be able to change his own details in his account like his description or social links etc...
However, when I submit the form, it replaces everything and the empty values just erase the field in the database.
Any way to submit the form and replace ONLY the values that have been entered in the field and ignore the empty ones ?
Here is my controller :
var database = firebase.database();
var userId = firebase.auth().currentUser.uid;
var nameInput = document.querySelector('#name');
var descriptionInput = document.querySelector('#description');
var cityInput = document.querySelector('#city');
var ageInput = document.querySelector('#age');
var hobbiesInput = document.querySelector('#hobbies');
var facebookInput = document.querySelector('#facebook');
var twitterInput = document.querySelector('#twitter');
var instagramInput = document.querySelector('#instagram');
var youtubeInput = document.querySelector('#youtube');
var snapchatInput = document.querySelector('#snapchat');
var linkedinInput = document.querySelector('#linkedin');
var emailInput = document.querySelector('#email');
var passwordInput = document.querySelector('#password');
var saveButton = document.querySelector('#save');
saveButton.addEventListener("click", function() {
var name = nameInput.value;
var description = descriptionInput.value;
var city = cityInput.value;
var age = ageInput.value;
var hobbies = hobbiesInput.value;
var facebook = facebookInput.value;
var twitter = twitterInput.value;
var instagram = instagramInput.value;
var youtube = youtubeInput.value;
var snapchat = snapchatInput.value;
var linkedin = linkedinInput.value;
var email = emailInput.value;
var password = passwordInput.value;
firebase.database().ref('accounts/' + userId).set({
name: name,
description: description,
city: city,
age: age,
hobbies: hobbies,
facebook: facebook,
twitter: twitter,
instagram: instagram,
youtube: youtube,
snapchat: snapchat,
linkedin: linkedin,
email: email,
password: password,
});
receiveNewData();
function receiveNewData() {
// check if there's new data added
firebase.database().ref('accounts/' + userId).on('child_added', function(msg) {
var data = msg.val();
// your new data
console.log(data);
$state.go("tab.account");
});
}
});
var firebase_data = {};
var userID = firebase.auth().currentUser.uid;
var input_data = {
nameInput: document.querySelector('#name'),
descriptionInput: document.querySelector('#description'),
cityInput: document.querySelector('#city'),
ageInput: document.querySelector('#age'),
hobbiesInput: document.querySelector('#hobbies'),
facebookInput: document.querySelector('#facebook'),
twitterInput: document.querySelector('#twitter'),
instagramInput: document.querySelector('#instagram'),
youtubeInput: document.querySelector('#youtube'),
snapchatInput: document.querySelector('#snapchat'),
linkedinInput: document.querySelector('#linkedin'),
emailInput: document.querySelector('#email'),
passwordInput: document.querySelector('#password'),
saveButton: document.querySelector('#save')
}
for(var key in input_data) {
if(input_data.hasOwnProperty(key) && input_data[key].value.length) {
firebase_data[key] = input_data[key].value
}
}
firebase.database().ref('accounts/' + userId).set(firebase_data)
For the people, like me, that are new to this, here is the solution I found : Autocomplete the fields that have a value already so when I submit the form it is saved again with the same value.
The code :
var database = firebase.database();
var userId = firebase.auth().currentUser.uid;
var nameInput = document.querySelector('#name');
var descriptionInput = document.querySelector('#description');
var cityInput = document.querySelector('#city');
var ageInput = document.querySelector('#age');
var hobbiesInput = document.querySelector('#hobbies');
var facebookInput = document.querySelector('#facebook');
var twitterInput = document.querySelector('#twitter');
var instagramInput = document.querySelector('#instagram');
var youtubeInput = document.querySelector('#youtube');
var snapchatInput = document.querySelector('#snapchat');
var linkedinInput = document.querySelector('#linkedin');
var emailInput = document.querySelector('#email');
var passwordInput = document.querySelector('#password');
var saveButton = document.querySelector('#save');
var database = firebase.database().ref('/accounts/' + userId);
// Retrieve information into the fields already filled in Database
database.on('value', function(snapshot) {
var displayName = snapshot.val().name;
var description = snapshot.val().description;
var displayCity = snapshot.val().city;
var displayAge = snapshot.val().age;
var displayHobbies = snapshot.val().hobbies;
var displayFacebook = snapshot.val().facebook;
var displayTwitter = snapshot.val().twitter;
var displayInstagram = snapshot.val().instagram;
var displayYoutube = snapshot.val().youtube;
var displaySnapchat = snapshot.val().snapchat;
var displayLinkedin = snapshot.val().linkedin;
var displayEmail = snapshot.val().email;
var displayPassword = snapshot.val().password;
$scope.$apply(function() {
$scope.displayName = displayName;
$scope.description = description;
$scope.displayCity = displayCity;
$scope.displayAge = displayAge;
$scope.displayHobbies = displayHobbies;
$scope.displayFacebook = displayFacebook;
$scope.displayTwitter = displayTwitter;
$scope.displayInstagram = displayInstagram;
$scope.displayYoutube = displayYoutube;
$scope.displaySnapchat = displaySnapchat;
$scope.displayLinkedin = displayLinkedin;
$scope.displayEmail = displayEmail;
$scope.displayPassword = displayPassword;
});
document.getElementById("name").value = displayName;
document.getElementById("description").value = description;
document.getElementById("city").value = displayCity;
document.getElementById("age").value = displayAge;
document.getElementById("hobbies").value = displayHobbies;
document.getElementById("facebook").value = displayFacebook;
document.getElementById("twitter").value = displayTwitter;
document.getElementById("instagram").value = displayInstagram;
document.getElementById("youtube").value = displayYoutube;
document.getElementById("snapchat").value = displaySnapchat;
document.getElementById("linkedin").value = displayLinkedin;
document.getElementById("email").value = displayEmail;
document.getElementById("password").value = displayPassword;
});;

Categories

Resources