customise odoo12 JavaScript file - javascript

I want to replace the functionality of the js file. As we have widget many2many in relation_field.js in that there is one function search, that contains code for creating and edit option. I want to change this functionality as per my needs. Following is the main code that I want to change
if (create_enabled && !self.nodeOptions.no_create_edit) {
var createAndEditAction = function () {
// Clear the value in case the user clicks on discard
self.$('input').val('');
return self._searchCreatePopup("form", false, self._createContext(search_val));
};
values.push({
label: _t("Create and Edit..."),
action: createAndEditAction,
classname: 'o_m2o_dropdown_option',
});
} else if (values.length === 0) {
values.push({
label: _t("No results to show..."),
});
}
following is my code. I want to add an alert function to create and edit the option of many2many fields. For that, I have use alert function.
odoo.define('survey_inherit.create_record',function(require){
"use strict";
console.log("In js file");
var relationalField = require('web.relational_fields');
var FieldMany2One = relationalField.FieldMany2One.include({
_search: function (search_val) {
var create_enabled = self.can_create && !self.nodeOptions.no_create;
if (create_enabled && !self.nodeOptions.no_create_edit) {
var createAndEditAction = function () {
// Clear the value in case the user clicks on discard
self.$('input').val('');
**alert(‘Test’);**
//return self._searchCreatePopup("form", false, self._createContext(search_val));
};
this.values.push({
label: _t("Create and Edit..."),
action: createAndEditAction,
classname: 'o_m2o_dropdown_option',
});
} else if (this.values.length === 0) {
this.values.push({
label: _t("No results to show..."),
});
}
}
});
});
can any one please help or any other suggestion.
Thanks in advance.

I suggest you to remove assigning your code to FieldMany2One variable.
So code will be:
odoo.define('survey_inherit.create_record',function(require){
"use strict";
console.log("In js file");
var relationalField = require('web.relational_fields');
relationalField.FieldMany2One.include({
_search: function (search_val) {
var create_enabled = self.can_create && !self.nodeOptions.no_create;
if (create_enabled && !self.nodeOptions.no_create_edit) {
var createAndEditAction = function () {
// Clear the value in case the user clicks on discard
self.$('input').val('');
**alert(‘Test’);**
//return self._searchCreatePopup("form", false, self._createContext(search_val));
};
this.values.push({
label: _t("Create and Edit..."),
action: createAndEditAction,
classname: 'o_m2o_dropdown_option',
});
} else if (this.values.length === 0) {
this.values.push({
label: _t("No results to show..."),
});
}
}
});
});

Related

How to call a function in JavaScript when radio button is selected

I am new to JavaScript, I am trying to call another function but it is not working can someone tell me what am doing wrong. I have a radio button based on the selection i want to call a function.
const paymentForm = document.getElementById('paymentForm');
paymentForm.addEventListener("submit", myFunction, false);
//PaymentMethodRadio:
function myFunction() {
if (document.getElementById('Once').checked) {
payWithPaystack1.call();
}
if (document.getElementById('Reoccuring').checked) {
}
}
function payWithPaystack1(e) {
e.preventDefault();
let handler = PaystackPop.setup({
key: 'censored', // Replace with your public key
email: document.getElementById("email-address").value,
amount: document.getElementById("amount").value * 100,
ref: '' + Math.floor((Math.random() * 1000000000) + 1), // generates a pseudo-unique reference. Please replace with a reference you generated. Or remove the line entirely so our API will generate one for you
// plan: 'censored',
subaccount: 'censored',
// label: "Optional string that replaces customer email"
onClose: function () {
alert('Window closed.');
},
callback: function (response) {
let message = 'Payment complete! Reference: ' + response.reference;
alert(message);
}
});
handler.openIframe();
}
with If statement like this
if(document.getElementById('radioButtonID').checked) {
// do this
}
check this stack it may help
How can I check whether a radio button is selected with JavaScript?
Try to use on or changed events
$(document.getElementById('Reoccuring')).on('click change', function(e) {
// your checking statements.
if (document.getElementById('Reoccuring').checked) {
//checked function
} else
{
// unchecked
}
});

How to show confirmation pop up when changing page in DataTable

I am landing on the first page of DataTable, make some changes.
Then I move to the second page.
Actually, confirmation popup is shown but it navigate to the second page.
Expected: confirm pop is shown but it still landing on the first.
Here is my code:
$('#dataTable-id').on( 'page.dt', function (event) {
if( change ){
bootbox.dialog({
title: "Confirmation",
message : "Discard changes?",
buttons :{
main: {
label : "Leave",
className : "btn-primary",
callback: function (){
// To avoid broking page/length controller
// move to other pages
return true; // cancel draw
}
},
cancel: {
label : "Stay",
className : "btn-default",
callback : function() {
// stay at current page.
return true;
}
}
},onEscape: function () {return true;}
});
}
});
How to show confirmation popup before page change?
The page.dt event is only informational, it can not be canceled.
You can workaround that restriction by writing a custom preDrawCallback like discussed here: https://datatables.net/forums/discussion/25507
EDIT: You have to cancel the redraw generally and do the paging manually in the bootbox callback (as it does not work as a real modal dialog like the native javascript confirm()). I modified the above example to incorporate a bootbox confirm dialog on paging: https://jsfiddle.net/bk4nvds5/
$(document).ready(function () {
var pageLen = 10;
var originalPage = 0;
var originalPageLen = pageLen;
var gotoPage = 0;
var gotoPageLen = originalPageLen;
var fromBootbox = false;
var table = $('#example').DataTable({
"pageLength": pageLen,
"preDrawCallback": function (settings) {
if(table){ // ignore first draw
if (!fromBootbox) {
// To avoid broking page/length controller, we have to reset the paging information
gotoPage = settings._iDisplayStart;
gotoPageLen = settings._iDisplayLength;
bootbox.confirm("Are you sure?", function(result) {
console.log("goto page" + gotoPage + " (result: " + result + ")");
if (result) {
fromBootbox = true;
table.page.len(gotoPageLen);
table.page(gotoPage / gotoPageLen).draw(false);
fromBootbox = false;
}
});
settings._iDisplayStart = originalPage;
settings._iDisplayLength = originalPageLen;
$('[name="example_length"]').val(originalPageLen);
return false; // cancel draw
}else{
originalPage = settings._iDisplayStart;
originalPageLen = settings._iDisplayLength;
}
}
}
});
});

Modified code is not correct for the getvalue and setvalue

My code was working fine but they wanted to change my code....
they wanted to attach setValue and getValue added directly to
footballPanel instead of sports grid,
but after adding it the code is not working fine...
can you tell me why its not working....
providing my modified code below...
the UI action here I am performing is there are two radio buttons,
when I click each radio button two different grids open
in one of the grid we add value, when i switch back to another radio
button the values in another grid disappears but it should not
disappear...
after I modified the code the values disappear, can you tell me why?
Only part of modified code here
else {
this.setDisabled(true);
this.addCls("sports-item-disabled");
if (sportsGrid.store.getCount() > 0) {
var footballPanel = sportsGrid.up('panel');
footballPanel.holdValue = footballPanel.getValue();
footballPanel.setValue();
sportsGrid.addCls("sports-item-disabled");
}
}
Whole modified code:
sportsContainerHandler: function(radioGroup, newValue, oldValue, options) {
var sportsCustomParams = options.sportsCustomParams;
var uiPage = this.up('football-ux-sports-ui-page');
var SportsDefinition = metamodelsHelper.getSportsDefinition(
uiPage, sportsCustomParams.SportsHandlerDefinitionId);
var sportsFieldParam = SportsDefinition.params['sportsMultiFieldName'];
var sportsGrid = uiPage.queryById(sportsFieldParam.defaultValue).grid;
if (newValue[radioGroup.name] == 'sportss') {
this.setDisabled(false);
this.removeCls("sports-item-disabled");
if (sportsGrid.holdValue) {
var footballPanel = sportsGrid.up('panel');
footballPanel.setValue(sportsGrid.holdValue);
}
} else {
this.setDisabled(true);
this.addCls("sports-item-disabled");
**if (sportsGrid.store.getCount() > 0) {
var footballPanel = sportsGrid.up('panel');
footballPanel.holdValue = footballPanel.getValue();
footballPanel.setValue();
sportsGrid.addCls("sports-item-disabled");
}**
}
},
Working code without modification
sportsContainerHandler: function(radioGroup, newValue, oldValue, options) {
var sportsCustomParams = options.sportsCustomParams;
var uiPage = this.up('football-ux-sports-ui-page');
var SportsDefinition = metamodelsHelper.getSportsDefinition(
uiPage, sportsCustomParams.SportsHandlerDefinitionId);
var sportsFieldParam = SportsDefinition.params['sportsMultiFieldName'];
var sportsGrid = uiPage.queryById(sportsFieldParam.defaultValue).grid;
if (newValue[radioGroup.name] == 'sportss') {
this.setDisabled(false);
this.removeCls("sports-item-disabled");
if (sportsGrid.holdValue) {
var footballPanel = sportsGrid.up('panel');
footballPanel.setValue(sportsGrid.holdValue);
}
} else {
this.setDisabled(true);
this.addCls("sports-item-disabled");
if (sportsGrid.store.getCount() > 0) {
sportsGrid.holdValue = sportsGrid.store.data.items;
sportsGrid.store.loadData([]);
sportsGrid.addCls("sports-item-disabled");
}
}
},
getValue() is not a method of ExtJS Panel class.
The change in your code, from sportsGrid (Ext.grid.Panel) to footbalPanel (Ext.panel.Panel) won't work, because they are from different classes and therefore have different properties and methods.
If you want this code to work, you'll need to implement getValue() and setValue(). For example, something like:
On FootballPanel class:
getValue: function () {
return this.down('grid').store.data.items;
},
setValue: function (newValue) {
if (!newValue)
newValue = new Array();
this.down('grid').store.loadData(newValue);
},
And use your modified code:
sportsContainerHandler: function(radioGroup, newValue, oldValue, options) {
var sportsCustomParams = options.sportsCustomParams;
var uiPage = this.up('football-ux-sports-ui-page');
var SportsDefinition = metamodelsHelper.getSportsDefinition(
uiPage, sportsCustomParams.SportsHandlerDefinitionId);
var sportsFieldParam = SportsDefinition.params['sportsMultiFieldName'];
var sportsGrid = uiPage.queryById(sportsFieldParam.defaultValue).grid;
if (newValue[radioGroup.name] == 'sportss') {
this.setDisabled(false);
this.removeCls("sports-item-disabled");
if (sportsGrid.holdValue) {
var footballPanel = sportsGrid.up('panel');
footballPanel.setValue(sportsGrid.holdValue);
}
} else {
this.setDisabled(true);
this.addCls("sports-item-disabled");
if (sportsGrid.store.getCount() > 0) {
var footballPanel = sportsGrid.up('panel');
footballPanel.holdValue = footballPanel.getValue();
footballPanel.setValue([]);
sportsGrid.addCls("sports-item-disabled");
}
}
},

AngularJs+Bootstrap+Typehead+Ajax is working only if i put alert box but only in chrome

i am using bootsrap typehead with angularjs given at this link http://angular-ui.github.io/bootstrap/
In my controller
$scope.getUser = function(val) {
//alert("hi");
return $http.get('user/getUserNames.do', {
params: {
userName: val,
}
}).then(function(response){
return response.data;
});
};
my html code
<input type="text" ng-model="asyncSelected" typeahead-wait-ms="300" typeahead="user for user in getUser($viewValue)" class="form-control">
if remove the alert the typehead will not work
if i keep the alert the typehead will work only in chrome
if i place a break point at "return $http.get('user/getUserNames.do'" and step out using
fire bug it works in firefox
i am receiving the data in this formate ['name1','name2'] from server
some one please help
thanks in advance
thats because the time taken to close the alert the async data is recieved. you should store the data on $scope rather then calling a function on $scope
$scope.users= {};
$scope.getUser = function(val) {
return $http.get('user/getUserNames.do', {
params: {
userName: val,
}
}).then(function(response){
$scope.users= response.data;
});
};
html
<input type="text" ng-model="asyncSelected" ng-change="getUser($viewValue)"
typeahead-wait-ms="300" typeahead="user for user in users" class="form-control">
your cods logic is incorrect,you cant return data like that from a async function, that need time to complete,
dont return anything from this getUser function. you have 2 option :
1 - store the responce.data in a global variable to be used later
$scope.users = [];
$scope.getUser = function (val) {
$http.get('user/getUserNames.do', {
params: {
userName: val
}
}).then(function (response) {
$scope.users.push(response.data);
});
};
2 - call another function when get function is complete to handle the data recived
$scope.getUser = function (val) {
$http.get('user/getUserNames.do', {
params: {
userName: val
}
}).then(function (response) {
$scope.userLoaded(response.data);
});
};
By the simple hack in angular-ui-bootstrap i solved the problem
before..........
var getMatchesAsync = function(inputValue) {
var locals = {$viewValue: inputValue};
isLoadingSetter(originalScope, true);
$q.when(parserResult.source(originalScope, locals)).then(function(matches) {
//it might happen that several async queries were in progress if a user were typing fast
//but we are interested only in responses that correspond to the current view value
var onCurrentRequest = (inputValue === modelCtrl.$viewValue);
if (onCurrentRequest && hasFocus) {
if (matches.length > 0) {
scope.activeIdx = focusFirst ? 0 : -1;
scope.matches.length = 0;
//transform labels
for(var i=0; i<matches.length; i++) {
locals[parserResult.itemName] = matches[i];
scope.matches.push({
id: getMatchId(i),
label: parserResult.viewMapper(scope, locals),
model: matches[i]
});
}
scope.query = inputValue;
//position pop-up with matches - we need to re-calculate its position each time we are opening a window
//with matches as a pop-up might be absolute-positioned and position of an input might have changed on a page
//due to other elements being rendered
scope.position = appendToBody ? $position.offset(element) : $position.position(element);
scope.position.top = scope.position.top + element.prop('offsetHeight');
element.attr('aria-expanded', true);
} else {
resetMatches();
}
}
if (onCurrentRequest) {
isLoadingSetter(originalScope, false);
}
}, function(){
resetMatches();
isLoadingSetter(originalScope, false);
});
};
i just removed '&& hasFocus' this sipneet from the code
after ........
var getMatchesAsync = function(inputValue) {
var locals = {$viewValue: inputValue};
isLoadingSetter(originalScope, true);
$q.when(parserResult.source(originalScope, locals)).then(function(matches) {
//it might happen that several async queries were in progress if a user were typing fast
//but we are interested only in responses that correspond to the current view value
var onCurrentRequest = (inputValue === modelCtrl.$viewValue);
if (onCurrentRequest) {
if (matches.length > 0) {
scope.activeIdx = focusFirst ? 0 : -1;
scope.matches.length = 0;
//transform labels
for(var i=0; i<matches.length; i++) {
locals[parserResult.itemName] = matches[i];
scope.matches.push({
id: getMatchId(i),
label: parserResult.viewMapper(scope, locals),
model: matches[i]
});
}
scope.query = inputValue;
//position pop-up with matches - we need to re-calculate its position each time we are opening a window
//with matches as a pop-up might be absolute-positioned and position of an input might have changed on a page
//due to other elements being rendered
scope.position = appendToBody ? $position.offset(element) : $position.position(element);
scope.position.top = scope.position.top + element.prop('offsetHeight');
element.attr('aria-expanded', true);
} else {
resetMatches();
}
}
if (onCurrentRequest) {
isLoadingSetter(originalScope, false);
}
}, function(){
resetMatches();
isLoadingSetter(originalScope, false);
});
};

Javascript / jQuery Hide fields based on Selected Drop Down item

I have some code that I have created for an OnChange event which works perfectly.
<script type="text/javascript">
function UpdEventChanged(selectEl) {
var text = selectEl.options[selectEl.selectedIndex].text;
if (text == "Sickness" || text == "Holiday") {
$("input[id$=eventPostCode").hide();
$("#ContentPlaceHolder1_LBLUpdPCReq").hide();
$("#ContentPlaceHolder1_lblUpdPC").hide();
}
else {
$("input[id$=eventPostCode").show();
$("#ContentPlaceHolder1_LBLUpdPCReq").show();
$("#ContentPlaceHolder1_lblUpdPC").show();
}
}
</script>
I need to integrate the above code to make it work on the Page Load event. Here is my code:
// update Dialog
$('#updatedialog').dialog({
autoOpen: false,
width: 500,
buttons: {
"update": function() {
//alert(currentUpdateEvent.title);
var eventToUpdate = {
id: currentUpdateEvent.id,
//title: $("#eventName").val(),
title: $("#EventSalesPerson option:selected").text(),
description: $("#eventDesc").val(),
salesperson: $("#EventSalesPerson option:selected").text(),
eventPostCode: $("input[id$=eventPostCode]").val(),
eventname: $("#EventEventName option:selected").text()
};
{
PageMethods.UpdateEvent(eventToUpdate, updateSuccess);
$(this).dialog("close");
currentUpdateEvent.title = $("#eventName").val();
currentUpdateEvent.description = $("#eventDesc").val();
currentUpdateEvent.salesperson = $("#EventSalesPerson option:selected").text();
currentUpdateEvent.eventname = $("#EventEventName option:selected").text();
currentUpdateEvent.eventPostCode = $("input[id$=eventPostCode]").val();
$('#calendar').fullCalendar('updateEvent', currentUpdateEvent);
location.reload(true);
}
},
"delete": function() {
if (confirm("do you really want to delete this event?")) {
PageMethods.deleteEvent($("#eventId").val(), deleteSuccess);
$(this).dialog("close");
$('#calendar').fullCalendar('removeEvents', $("#eventId").val());
}
}
}
});
If #EventEventName selected text = Holiday or Sickness then I need the following items to be hidden:
"input[id$=eventPostCode"
"#ContentPlaceHolder1_LBLUpdPCReq"
"#ContentPlaceHolder1_lblUpdPC"
And obviously if they are not selected then the above should be displayed.
Thanks
It looks like you need something about like this:
var EventEventNameText = $('#EventEventName').val();
if (EventEventNameText=='Holiday' || EventEventNameText=='Sickness') {
$('#eventPostCode').hide();
$('#ContentPlaceHolder1_LBLUpdPCReq').hide();
$('#ContentPlaceHolder1_lblUpdPC').hide();
}
Let me know how that works for you.

Categories

Resources