Render a template in a onchage of text field in odoo 14 - odoo

I am trying to render a template in onchange of a input field.
Here is the onchange method.
*.js
_onClickBasketInputChange: function(){
console.log('inside input change',this.basketVerificationId);
var self = this;
var barcode = $('.basket_barcode_input').val();
console.log('barcode',barcode);
// var rec = this._rpc({
return this._rpc({
model: 'mobile.basket.verification',
method: 'get_picking_details',
args: [this.basketVerificationId,barcode],
}).then(function(res){
// console.log('this',self);
console.log('picking_id',res);
var $body = this.$el.filter('.o_barcode_lines');// Here i am getting the error ' Uncaught (in promise) TypeError: this is undefined'
console.log('body',$body);
if (res['status'] == true){
console.log('successs');
var $lines = $(Qweb.render('basketVerificationLines', {
picking:res['picking_id'],
customer:res['partner_id'],
lines:res['line_ids']
}));
$body.prepend($lines);
}
// $('.basket_barcode_input').val('');
var message = res['result'];
if (res['status'] == false){
Dialog.alert(self, message);
}
});
},
But i am getting following error
Uncaught (in promise) TypeError: this is undefined
Update:
When change this to self, the value of $body is
body
Object { length: 0, prevObject: {…} }
​
length: 0
​
prevObject: Object { 0: div.o_action, length: 1 }
​
And the template not prepend to the body.
Please help to resolve this.

I got the solution,
I replace the .filter with .find then it works.
var $body = self.$el.find('.o_barcode_lines');

Related

Karma TypeError: Cannot set properties of undefined (setting 'pageSize')

Below is my Angular code,
#ViewChild('commandtable') commandtable!: NgbdTableComplete;
processResponse(): void {
this.searchService
.getCommandsID(this.url, this.commandtable.pageSize)
.subscribe((res) => {
let response: CommmandsQuery = JSON.parse(JSON.stringify(res));
this.readCommands(response);
this.display_cards = true;
});
}
processLoadMoreResponse (token: string, size: number) {
this.commandtable.pageSize = size;
this.processResponse();
}
In karma test file :
it('processLoadMoreResponse ', () => {
(component as any).commandtable.pageSize = 1;
spyOn((component as any),'processResponse');
component.processLoadMoreResponse ('tocken', 3);
expect((component as any).processResponse).toHaveBeenCalled();
expect((component as any).processResponse).toHaveBeenCalledTimes(1);
});
when I run the test I get the below error
TypeError: Cannot set properties of undefined (setting 'pageSize')

Uncaught TypeError: datapoints.data.map is not a function at XMLHttpRequest.xmlhttp.onreadystatechange

Can anyone help me? I'm really bad at programming
Error :Uncaught TypeError: datapoints.data.map is not a function at XMLHttpRequest.xmlhttp.onreadystatechange
const xmlhttp = new XMLHttpRequest();
const url = '//url//';
xmlhttp.open('GET', url, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
const datapoints = JSON.parse(this.responseText);
//console.log(datapoints);
const labelsboy = datapoints.data.map(function(item){
return item.boy;
});
console.log(labelsboy);
}
}
file JSON API
{
"status": true,
"row": 2,
"data": {
"boy": 10,
"girl": 15
}
}
map is an array function but datapoints.data is an object. It seems like you are just trying to get one value from the object so you can just access it directly.
const labelsboy = datapoints.data.boy;
console.log(labelsboy);

JavaScript - Uncaught ReferenceError: KEY is not defined

I'm reading a book on creating games with HTML5 and have problem with this code.no matter what i do i can't make it work.i removed descriptions from code so it's less to read.and all the code here is copied from book.
I get the error " Uncaught ReferenceError: KEY is not defined " for UP KEY on line 23.and if i remove that block of code entirely i get the same error for DOWN KEY so what do you think is the problem?
var pingpong = {}
pingpong.pressedKeys = [];
$(function(){
pingpong.timer = setInterval(gameloop,30);
$(document).keydown(function(e){
pingpong.pressedKeys[e.which] = true;
});
$(document).keyup(function(e){
pingpong.pressedKeys[e.which] = false;
});
});
function gameloop() {
movePaddles();
}
function movePaddles() {
pressed.
if (pingpong.pressedKeys[KEY.UP]) {
var top = parseInt($("#paddleB").css("top"));
$("#paddleB").css("top",top-5);
}
if (pingpong.pressedKeys[KEY.DOWN]) {
var top = parseInt($("#paddleB").css("top"));
$("#paddleB").css("top",top+5);
}
if (pingpong.pressedKeys[KEY.W]) {
var top = parseInt($("#paddleA").css("top"));
$("#paddleA").css("top",top-5);
}
if (pingpong.pressedKeys[KEY.S]) {
var top = parseInt($("#paddleA").css("top"));
$("#paddleA").css("top",top+5);
}
}
KEY should be defined somewhere in your tutorial
Probably like this:
KEY = {
UP: 38,
DOWN: 40,
...
}

JSON Store in worklight v6.0

I am trying to integrate the JSONStore standalone app in my multipage application. When I am trying to initialize the collection I am getting the following error "Uncaught TypeError: undefined is not a function". One thing I want to know is, in Worklight version 6.0 I observed that underscore (Lo-Dash) templating was used. But nowhere I found the reference given to the lodash. Also, I didn't find the lodash file anywhere. can anyone please tell me how to do this?
Here is my javascript code
window.$ = window.jQuery = WLJQ;
currentPage = {};
currentPage.init = function(WL, jQuery, lodash) {
alert("current page ::init called");
'use strict';
//Dependencies
var $ = jQuery,
_ = lodash;
//CONSTANTS
var PEOPLE_COLLECTION_NAME = 'people',
KEY_VALUE_COLLECTION_NAME = 'keyvalue',
INIT_FIRST_MSG = 'PERSISTENT_STORE_NOT_OPEN',
NAME_FIELD_EMPTY_MSG = 'Name field is empty',
AGE_FIELD_EMPTY_MSG = 'Age field is empty',
ID_FIELD_EMPTY_MSG = 'Id field is empty',
EMPTY_TABLE_MSG = 'No documents found',
DESTROY_MSG = 'Destroy finished succesfully',
INIT_MSG = 'Collection initialized',
ADD_MSG = 'Data added to the collection',
REPLACE_MSG = 'Document replaced succesfully, call find.',
REMOVE_MSG = 'Documents removed: ',
COUNT_MSG = 'Documents in the collection: ',
CLOSE_ALL_MSG = 'JSONStore closed',
REMOVE_COLLECTION_MSG = 'Removed all data in the collection',
LOAD_MSG = 'New documents loaded from adapter: ',
PUSH_MSG_FAILED = 'Could not push some docs, res: ',
PUSH_MSG = 'Push finished',
PASS_CHANGED_MSG = 'Password changed succesfully';
$('#init').click(initCollection);
$('#destroy').click(destroy);
$('#add-data').click(addData);
$('#find-name').click(findByName);
$('#find-age').click(findByAge);
$('#find-all').click(findAll);
$('#find-id-btn').click(findById);
$('#replace').click(replace);
$('#remove-id-btn').click(removeById);
//Log messages to the console and status field
var _logMessage = function (msg, id) {
//Get reference to the status field
var status = _.isUndefined(id) ? $('div#status-field') : $(id);
//Put message in the status div
status.text(msg);
//Log message to the console
WL.Logger.info(msg);
};
//Show JSONStore document in a table
var _showTable = function (arr) {
if (_.isArray(arr) && arr.length < 1) {
return _logMessage(EMPTY_TABLE_MSG);
}
//Log to the console
WL.Logger.ctx({stringify: true, pretty: true}).info(arr);
var
//Get reference to the status field
status = $('div#status-field'),
//Table HTML template
table = [
'<table id="user_table" >',
'<tr>',
'<td><b>_id</b></td>',
'<td><b>name</b></td>',
'<td><b>age</b></td>',
'<td><b>json</b></td>',
'</tr>',
'<% _.each(people, function(person) { %>',
'<tr>',
'<td> <%= person._id %> </td>',
'<td> <%= person.json.name %> </td>',
'<td><%= person.json.age %></td>',
'<td><%= JSON.stringify(person.json) %></td>',
'</tr>',
'<% }); %>',
'</table>'
].join(''),
//Populate the HTML template with content
html = _.template(table, {people : arr});
//Put the generated HTML table into the DOM
status.html(html);
};
//Scroll to the top every time a button is clicked
$('button').on('click', function () {
$('html, body').animate({scrollTop: 0}, 'slow');
});
function initCollection() {
console.log("init collection method called");
alert("init collection method called");
//Get references to the input fields DOM elements
var usernameField = $('input#init-username'),
passwordField = $('input#init-password');
//Get values from the input fields
var username = usernameField.val() || '',
password = passwordField.val() || '';
//Create the optional options object passed to init
var options = {};
//Check if a username was passed
if (username.length > 0) {
options.username = username;
}
//If if a password was passed
if (password.length > 0) {
options.password = password;
}
//JSONStore collections metadata
var collections = {};
//Define the 'people' collection and list the search fields
collections[PEOPLE_COLLECTION_NAME] = {
searchFields : {name: 'string', age: 'integer'},
//-- Start optional adapter metadata
adapter : {
name: 'people',
add: 'addPerson',
remove: 'removePerson',
replace: 'replacePerson',
load: {
procedure: 'getPeople',
params: [],
key: 'peopleList'
}
}
//-- End optional adapter metadata
};
//Define the 'keyvalue' collection and use additional search fields
collections[KEY_VALUE_COLLECTION_NAME] = {
searchFields : {},
additionalSearchFields : { key: 'string' }
};
//Initialize the people collection
WL.JSONStore.init(collections, options)
.then(function () {
_logMessage(INIT_MSG);
_callEnhanceToAddKeyValueMethods();
})
.fail(function (errorObject) {
_logMessage(errorObject.msg);
});
}
Thanks in advance
regards
V.H.C
I observed that underscore(loadash) templating was used. But nowhere I
found the reference given to the loadash. Also, I didn't find the
loadash file anywhere. can anyone please tell me how to do this?
You can build your own version of lodash or use underscore.
The version of lodash used by worklight is in the WL_ variable. Looking at your code, maybe you want to replace _ = lodash with _ = WL_. Alternatively when you bring your own version lodash or underscore it will be assigned to the _ variable automatically.
Alternatively, you can use other string template libraries like Handlebars.js or basic string interpolation by modifying the String prototype.

IBM Worklight 6.0 - Getting "Uncaught type error cannot call method 'initCollection' of undefined"

I'm working with Worklight to build an application which uses a local storage. I declared a function createCollection() in common/js/myApp.js.
However when I run it on the browser simulator, the console JavaScript shows:
Uncaught TypeError: Cannot call method 'initCollection' of undefined.
Any suggestions?
My JavaScript:
function wlCommonInit(){
// Common initialization code goes here
}
// inizializzazione json
window.onload = createCollection;
var isOpen = true;
var menuboxw = $("#menubox").css("width");
$("#contentbox").css("left",menuboxw);
var headerh = $("#header").height();
$("#contentbox").css("top", headerh);
$("#menu_btn").click(function(){menu()});
// apertura/chiusura menu principale
function menu() {
if(isOpen){
$('#contentbox').animate({ left: -5 }, 1);
$("#menubox").css("visibility", "hidden");
isOpen = false;
}
else{
$('#contentbox').animate({ left: menuboxw }, 1);
$("#menubox").css("visibility", "visible");
isOpen = true;
}
}
// creazione collection 'canti' e 'categorie'
function createCollection(){
WL.Logger.debug("Called createCollection");
WL.SimpleDialog.show("Message", "createCollection called", [{text: "Ok"}]);
var collectionCanti = "canti";
var searchFieldsCanti = {titolo: "string", autore: "string", id_categoria: "string", testo: "string"};
var collectionCategorie = "categorie";
var searchFieldsCategorie = {titolo: "string", attiva: "number"};
var success = function(data){
logMessage("Collection created successfully " + data);
};
var failure = function(data){
logMessage("Collection doesn't created " + data);
};
var options = {onSuccess: success, onFailure: failure};
canti = WL.JSONStore.initCollection(collectionCanti, searchFieldsCanti, options);
categorie = WL.JSONStore.initCollection(collectionCategorie, searchFieldsCategorie, options);
}
Do the following:
Remove window.onload = createCollection;
Add createCollection(); inside wlCommonInit()
BTW, that logMessage produces errors. Should probably be changed to WL.Logger.debug (which you are already utilizing in the code...).
Please go over the IBM Worklight Getting Started training material. No skipping.