Add client field validation Odoo's POS - javascript

I want to add validations for data that I've added to Odoo's POS client model.
By the moment I've created the following code:
screens.ClientListScreenWidget.include({
// Client save alerts
save_client_details: function (partner) {
if (!fields.custom_field) {
this.gui.show_popup('error', 'Missing custom_field!')
}
this._super(partner)
}
})
If my custom_field is empty it raises the popup and that's fine. The problem is that even if the user fills the field, the popup appears too.
Checking Odoo's code I've found that they check what the user filled in the window "fields" with the following code:
save_client_details: function(partner) {
var self = this;
var fields = {};
this.$('.client-details-contents .detail').each(function(idx,el){
if (self.integer_client_details.includes(el.name)){
var parsed_value = parseInt(el.value, 10);
if (isNaN(parsed_value)){
fields[el.name] = false;
}
else{
fields[el.name] = parsed_value
}
}
else{
fields[el.name] = el.value || false;
}
});
if (!fields.name) {
this.gui.show_popup('error',_t('A Customer Name Is Required'));
return;
}
I'm not used to javascript so I didn't manage mimic this code for my custom field.
How can I achieve this? How should my code look like for this?

Related

Disabling Form fields the use the SelectStatic widget in netbox v3 with javascript

I have a problem where i am trying to disable certain forms fields which use the SelectStatic Widget based on a tick box, i have included the javascript below.
const vlan = document.querySelector('#id_vlan');
const physical_facing = document.querySelector('#id_physical_facing');
const service_type = document.querySelector('#id_service_type');
const bd_function = document.querySelector('#id_function');
function vlan_enable(){
vlan.disabled = false;
};
function vlan_disable(){
vlan.disabled = true;
};
function service_function_enable() {
service_type.disabled = false;
bd_function.disabled = false;
};
function service_function_disable() {
service_type.disabled = true;
bd_function.disabled = true;
};
(function() {
service_function_enable();
vlan_enable();
if(physical_facing.checked){
service_function_disable();
} else {
vlan_disable();
}
})();
function pf_event() {
if(physical_facing.checked) {
vlan_enable();
service_function_disable();
} else {
vlan_disable();
service_function_enable();
}
};
physical_facing.addEventListener('change', pf_event)
When on the Page, the VLAN field is a DynamicModelFormField and will never disable, but when toggling the switch on and off the fields do not re-enable, i know the event is getting fired because i can see it in the developer tools, the disabled tag gets applied and removed with no change on the page, This may be a simple mistake but would like if someone can point me in the right direction.
below is what the page looks like
Netbox Page
Has anybody had any success doing this with the new version of netbox as it worked fine in V2 with the SelectStatic2 widget.

Disable "Changes you made may not be saved" pop-up window

I use the following frontend code to export a .csv document.
HTML
<form id="tool-export" method="post" action="export/">{% csrf_token %}
<a id="export-link" class="btn btn-sm btn-primary" href="#">DOWNLOAD</a>
</form>
JS
$('#export-link').click(function(e) {
e.preventDefault();
var link = $(this);
var form = link.closest('form');
var project_id = proj_id.find(":selected").val();
var input = $('<input>').attr('type', 'hidden').attr('name', 'project_id').val(project_id);
form.append($(input));
var project_type = proj_type.val();
input = $('<input>').attr('type', 'hidden').attr('name', 'project_type').val(project_type);
form.append($(input));
form.submit();
});
Export works well and I get the correct document. But also I receive the Changes you made may not be saved message after clicking on the export link. How to disable this message? I don't want to see it.
#Dekel helped me to get it.
The message is the beforeunload event.
And I can disable it with window.onbeforeunload = null;.
JS
$('#export-link').click(function(e) {
window.onbeforeunload = null;
e.preventDefault();
var link = $(this);
var form = link.closest('form');
var project_id = proj_id.find(":selected").val();
var input = $('<input>').attr('type', 'hidden').attr('name', 'project_id').val(project_id);
form.append($(input));
var project_type = proj_type.val();
input = $('<input>').attr('type', 'hidden').attr('name', 'project_type').val(project_type);
form.append($(input));
form.submit();
});
In jQuery simply use :
$(window).off('beforeunload');
I had the same problem.
window.onbeforeunload = function () {
// Your Code here
return null; // return null to avoid pop up
}
I've had the same error with embedding Google-Form in Chrome,
I can verify that none of the found solutions helped me. Here is the screenshot of my pop-up:
The only solution I've managed to implement was hiding the element and then unhiding/creating the new iframe with the current embed. Here's the part of my code:
if (oldvalue !== value) { // checks the id of the form (value) is not the same
// set value of the id
$('#info').text(value);
// check the element exists
let exists = value;
if($("#" + value).length == 0) {
//it doesn't exist
exists = false;
}
// hide all child elements of the div for forms
parent.children().hide();
// create new node if needed
if (!exists)
{
// create new form element and embed the form
$("#google-form").clone().attr("id",value).attr('src', record.url).appendTo(parent);
}
// unhide error element
$("#" + value).show();
}
The full code of my solution is here.

Testing jQuery Geocomplete Plugin (Autocomplete) with casperJS

We have written several test cases with casperjs now. In comparison to other testing frameworks it works like charm. But there is one crucial part of our app, where we fail to write a suitable test case.
In our app we have integrated a type of autocomplete plugin which is called Geocomplete (http://ubilabs.github.io/geocomplete/) which makes it possible to fetch geodata from the Google Maps Api.
There is the following workflow. On the start page of our site there is a form with one single input field, which is used for the autocomplete functionality. There the user can enter the name of a specific city and Google returns the data. In the background a backbone model is populated with that data.
Here is the code of the testcase:
casper.test.begin('Test User Login Form', 4, function suite(test) {
casper.options.verbose = true;
casper.options.logLevel = 'debug';
var url = 'http://localhost:8889/';
var session;
casper.start(url);
casper.test.comment('Start Testing');
casper.waitFor(function check() {
return this.evaluate(function() {
return document.getElementById('page-wrap');
});
}, function then() {
casper.waitForSelector('#landingForm', function() {
this.echo('waiting');
});
});
// input is populated with a some letters
casper.then(function() {
casper.sendKeys('#landingForm input[name="location.name"]', 'Klag', {
keepFocus: true
});
});
// .pac-item container whill show the autocomplete suggestions
casper.then(function() {
casper.waitUntilVisible('.pac-item', function() {
// we have tried several methods here like mouse_over + click etc.
this.sendKeys('#landingForm input[name="location.name"]', casper.page.event.key.Down, {
keepFocus: true
});
this.sendKeys('#landingForm input[name="location.name"]', casper.page.event.key.Enter, {
keepFocus: true
});
// form is submitted
this.click('#landingForm > div > div > div > span > button');
});
});
casper.then(function() {
// wait until next page is visible
casper.waitUntilVisible('div.activity-pic', function() {
// get backbone session model
session = casper.evaluate(function() {
return require('model/session');
});
// test if model was populated correctly with the data from google
test.assertEquals(session.filterModel.attributes.location.name, 'Klagenfurt', 'Name equals expected values.');
});
});
casper.run(function() {
casper.test.comment('Ending Testing');
test.done();
});
});
The test
test.assertEquals(session.filterModel.attributes.location.name, 'Klagenfurt', 'Name equals expected values.');
always fails and tells me that the name-attribute is undefined. The input field is filled in correclty with the name of the city. We have used the evaluate-method in other testcases to check the values and attributes of our models too, there it worked.
Does anybody has the same problem?
There are two possible approaches to this. Based on this comment you can add an event listener through evaluate and waitFor its execution (here as a reusable casper function):
casper.waitForGeocodeResult = function(){
this.thenEvaluate(function(){
// TODO: initialize $input
$input.bind('geocode:result', function(event, result) {
window._myGeocodeResultArrived = true;
}
});
this.waitFor(function check(){
return this.evaluate(function(){
return "_myGeocodeResultArrived" in window && window._myGeocodeResultArrived;
});
});
this.thenEvaluate(function(){
window._myGeocodeResultArrived = false;
});
};
You may call it like this:
casper.waitForGeocodeResult();
casper.then(function() {
// get backbone session model
session = casper.evaluate(function() {
return require('model/session');
});
// test if model was populated correctly with the data from google
test.assertEquals(session.filterModel.attributes.location.name, 'Klagenfurt', 'Name equals expected values.');
});
If this doesn't work for you may directly check the session model repeatedly (again as a reusable casper function):
casper.getBackboneModel = function(name, keyFunc){
var oldRetry;
this.then(function(){
oldRetry = this.options.retryTimeout;
// set retry timeout a little higher in case the require is a time intensive function
this.options.retryTimeout = 500;
});
this.waitFor(function check(){
var model = casper.evaluate(function(modelName){
return require(modelName);
}, name);
return keyFunc(model);
}, null, function onTimeout(){
this.echo("warning: geocomplete was unsuccessful");
});
this.then(function(){
// reset timeout
this.options.retryTimeout = oldRetry;
});
};
Call it like this:
casper.getBackboneModel(function(session){
try {
var temp = session.filterModel.attributes.location.name;
return "name" in session.filterModel.attributes.location;
} catch(e){
return false;
}
});
casper.then(function() {
// get backbone session model
session = casper.evaluate(function() {
return require('model/session');
});
// test if model was populated correctly with the data from google
test.assertEquals(session.filterModel.attributes.location.name, 'Klagenfurt', 'Name equals expected values.');
});

"Unable to load http://url status:0" error in onbeforeunload-method

may someone of you can help me to find this problem?
I've got an xpage with client-side js-code included which should be executed when you decide to leave the page. In the client-side js you refer to a button and click it automatically. This button got some server-side js code included and change the flag from a document from ("opened by ..." to "").
The thing is that somehow the client-side js did not work in all different browsers except the current IE (10.0.5) and throws the error:
unable to load http://urlofthedocument/... status:0
The funny thing about this is, when I insert an alert()-method right after the click()-method everything works fine in every browser. But as I don't want to include this alert statement I figure out there must be something different to avoid this. (A short pause instead of the alert-method also did not work.)
My CS JS-Code:
window.onbeforeunload = WarnEditMode;
function WarnEditMode(){
if(needUnloadConfirm == true){
var el = window.document.getElementById("#{id:Hidden4SSJS}");
el.click();
//document.open();
//document.write(el);
//document.close();
//alert("You're about to leave the page");
//pause(5000);
}
}
function pause(millis){
var date = new Date();
var curDate = null;
do { curDate = new Date(); }
while(curDate-date < millis)
}
This refers to to button, which executes following SS JS code, after it is clicked:
try{
print("Hidden4SSJS-Button-Test # Person");
var db:NotesDatabase = database;
var agt:NotesAgent;
var doc:NotesDocument = XPPersonDoc.getDocument()
agt = db.getAgent("(XPUnlockDocument)");
agt.run(doc.getNoteID());
}catch(e){
_dump(e);
}
May you guys can help me with this?
I would do this using the XSP object with a hidden computed field (and not your special button)...
Something like this:
function WarnEditMode(){
if(needUnloadConfirm == true){
XSP.partialRefreshGet("#{id:unlockDocCF1}", {
params: {
'$$xspsubmitvalue': 'needToUnlock'
},
onComplete: function () {
alert('You are about to leave this page and the document has been unlocked.');
},
onError : function (e) {
alert('You are about to leave this page and the document has NOT been unlocked.\n' + e);
}
);
}
pause(5000);
}
Then the computed field's javascript would be something like this:
try{
var sval = #Explode(context.getSubmittedValue(), ',');
if (sval == null) return result + " no action.";
if (!"needToUnlock".equals(sval[0])) return result + " no action.";
print("Hidden4SSJS-Button-Test # Person");
var db:NotesDatabase = database;
var agt:NotesAgent;
var doc:NotesDocument = XPPersonDoc.getDocument()
agt = db.getAgent("(XPUnlockDocument)");
agt.run(doc.getNoteID());
return 'document unlocked.';
}catch(e){
_dump(e);
}

Javascript Regular expression for image file to FileUpload control in asp.net

I am trying to verify image file which is choose by user in FileUpload control in web page at client side by using javascript.
Can anybody tell me how can i make it.
I am trying this code for that which is not working :
function validateFileExtension()
{
var re =/\.(gif|jpg|JPEG|tiff|png)$/i;
var temp = document.getElementById('<%=FileUpload1.ClientID %>').value;
if (re.test(temp))
{
return ("Invalid image file type.");
return false;
}
return "";
}
Check this its working for me...
function validateImage() {
var uploadcontrol = document.getElementById('<%=imgUploader.ClientID%>').value;
//Regular Expression for fileupload control.
var reg = /^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.jpg|.jpeg|.png|.gif)$/;
if (uploadcontrol.length > 0) {
//Checks with the control value.
if (reg.test(uploadcontrol)) {
return true;
}
else {
//If the condition not satisfied shows error message.
alert("Only .jpg, .jpeg,.png, .gif files are allowed!");
return false;
}
}
} //End of function validate.
private final String IMAGE_PATTERN = "([^\\s]+(\\.(?i)(jpg|png|gif|bmp))$)";

Categories

Resources