Two window.location not working togeather - javascript

I have two functions what sets a window.location.href tag in the url, but when I set the first one and then select the other one, the first one disappears. So how should I do? These functions are in a form that makes a selection of 1. project name and 2. package. And then you submit the form (php) the fields adds to the database.
function jsFunction(){
var myselect = document.getElementById("projektnamn");
window.location.href = "?projektnamn=" + myselect.options[myselect.selectedIndex].value;
}
function services(){
var select = document.getElementById("paket");
window.location.href = "?paket=" + select.options[select.selectedIndex].value;
}
I want the result to be like this:
domain.com?projektnamn=Something?paket=Something
What I get today is:
domain.com?projektnamn=Something
Or I get:
domain.com?paket=Something

I would store the link in a variable
let query = "";
function jsFunction(){
var myselect = document.getElementById("projektnamn");
query += "?projektnamn=" + myselect.options[myselect.selectedIndex].value;
}
function services(){
var select = document.getElementById("paket");
query += "?paket=" + select.options[select.selectedIndex].value;
window.location.assign(query);
}

Both of your functions are resetting the URL.
What you can do is use URLSearchParams to generate the query string.
function jsFunction(params) {
var myselect = document.getElementById("projektnamn");
params.set('projektnamn', myselect.options[myselect.selectedIndex].value);
}
function jsFunction2(params) {
var select = document.getElementById("paket");
params.set('paket', select.options[select.selectedIndex].value);
}
const params = new URLSearchParams();
jsFunction(params);
jsFunction2(params);
window.location.href = `${location.pathname}?${params}`;
From what it looks like you are trying to build a single function, not two separate functions. I would replace these 2 functions with one generic.
function jsFunction(params, id, name) {
var myselect = document.getElementById(id);
params.set(name, myselect.options[myselect.selectedIndex].value);
}
const params = new URLSearchParams();
jsFunction(params, "projektnamn", 'projektnamn');
jsFunction(params, "paket", 'paket');
window.location.href = `${location.pathname}?${params}`;

Related

How to Clone an custom entity in dynamics 365 using javaScript

I came across an scenario where I have to clone my custom entity.
Then I have started doing using with JavaScript by placing a custom duplicate button in the ribbon which triggers my JavaScript.
I used the following code:
function duplicateOrder(primaryControl){
var formContext = primaryControl;
var city = formContext.getAttribute('new_city').getValue();
var country = formContext.getAttribute('new_country').getValue();
var state = formContext.getAttribute('new_state').getValue();
var postal_code = formContext.getAttribute('new_zipcodepostalcode').getValue();
// var formItem = formContext.ui.formSelector.items.get();
// alert(`the form item value is ${formItem}`);
formContext.data.entity.save('saveandnew');
sleep(3000);
var city1 = formContext.getAttribute('new_city').getValue();
var country1 = formContext.getAttribute('new_country').getValue();
var state1 = formContext.getAttribute('new_state').getValue();
var postal_code1 = formContext.getAttribute('new_zipcodepostalcode').getValue();
alert(`${city1},${country1},${state1},${postal_code1}`);
if(city1==null){
formContext.getAttribute('new_city').setValue(city);
}
if(country1==null){
formContext.getAttribute('new_country').setValue(country);
}
if(state1==null){
formContext.getAttribute('new_state').setValue(state);
}
if(postal_code1==null){
formContext.getAttribute('new_zipcodepostalcode').setValue(postal_code);
}
alert(`${city},${country},${state},${postal_code}`);
}
function sleep(milliseconds) {
const date = Date.now();
let currentDate = null;
do {
currentDate = Date.now();
} while (currentDate - date < milliseconds);
}
I tried using the save and new logic to open a new entity form.
The New entity form opens but the field values do not get copied in the new how.
Please help me how to solve this.
Thanks and advance!
You need to call Xrm.Navigation.openForm with your cloneid record.
// Load newly copy record
var entityFormOptions = {};
entityFormOptions["entityName"] = "stdseries";
entityFormOptions["entityId"] = cloneId;
// Open the form.
Xrm.Navigation.openForm(entityFormOptions).then(
function (success) {
formContext.data.refresh();
},
function (error) {
});

How to concatenate values from a pop-up window choice with values from a database?

I am developing a project with the Kendo UI Framework, using more specically the Scheduler widget and I have the current issue:
On my database I have two tables one called Events and the other one called TypeOfEvents. Each type of event has got a specific color, a specific title plus defined values for startHour and endHour fields.
When the pop-up window to create an event is called, I can choose on two kendoMultiSelect the correspondent user and the type of event.
I can also choose the startDate and endDate. The default behavior of a Scheduler widget has got two datetimepickers also, however, I don't want that option on my pop-up window because the events will have defined hours that an user can't change.
My idea would be the following one:
Once I click save after choosing a specific event on my MultiSelectList, there would be some way to concatenate the startHour and endHour values I have defined in my database with the startDate and endHour field that I choosed on the pop-up window.
Right now, all my events startDate/endDate fields are saved on my DB with this format: 2015-03-01 00:00:00.000
I would like to substitute all those zeros with the values I defined in advance in my startHour/endHour fields of my TypeOfEvents table.
Here's my current CREATE script:
create: function (createEvent) {
var typeOfEventID = $("#selectEvent").val();
var usernameID = $("#selectUsername").val();
var dataStartTemp = $("#dataStart").val();
var dataEndTemp = $("#dataEnd").val();
var note = $("#note").val();
var res = $("#customViewScheduler").data("kendoScheduler");
var res1 = res.resources[1].dataSource.data();
var dataStart = convertToJSONDate(dataStartTemp);
var dataEnd = convertToJSONDate(dataEndTemp);
var changeSet = [];
var id = 0;
usernameID.forEach(function (userID) {
typeOfEventID.forEach(function (eventID) {
var titletemp = $.grep(res1, function (elem) {
if (elem.TypeOfEventID == eventID) {
return true;
}
})
if (titletemp.length > 0) {
note = titletemp[0].title;
}
var entityChange = {};
entityChange.Id = id;
entityChange.Entity = {
'__type': "Events:#BlahBlahWeb",
'UsernameID': userID,
'TypeOfEventID': eventID,
'startDate': dataStart,
'endDate': dataEnd,
'Title': note
};
entityChange.Operation = 2;
changeSet.push(entityChange);
id++
})
})
var changesetPayload = JSON.stringify({
"changeSet": changeSet
});
//Create jQuery ajax request
var Params = {}
Params.type = "POST";
Params.url = "./../Services/BlahBlahWeb-BlahDomainService.svc/JSON/SubmitChanges";
Params.dataType = "json";
Params.data = changesetPayload;
Params.contentType = "application/json";
Params.error = function (httpRequest, textStatus, errorThrown) {
//SendErrorByEmail(errorThrown, httpRequest.responseText)
}
Params.success = function (data) {
//createEvent.success(data);
var scheduler = $("#customViewScheduler").data("kendoScheduler");
var elem = tratanewelem(data.SubmitChangesResult[0].Entity)
scheduler.dataSource.read();
}
//Make the ajax request
$.ajax(Params);
},
Any idea of how can I accomplish that?

How to return more than one row from HANA database using XS?

I'm trying to retrieve all data from a db table into json object, like so:
function getTableData()
{
var vals = {};
var data = [];
try {
var dbCon = $.db.getConnection();
var query = 'SELECT * FROM SAPPRD.ZUSERDATATAB';
var pstmt = dbCon.prepareStatement(query);
var rs = {};
rs = pstmt.executeQuery();
while (rs.next()) {
vals.team = rs.getString(1);
vals.fname = rs.getString(3);
vals.lname = rs.getString(2);
data.push(vals);
$.response.status = $.net.http.OK;
}
$.response.setBody(JSON.stringify(data));
// $.response.contentType = contentType;
// $.response.headers.set('Content-Disposition', 'filename=' + filename);
} catch (e) {
$.response.setBody('errors: ' + e.message);
}
}
The query works only partially, because in data I get number of rows x last row content, like so:
[{"team":"I313766","fname":"0","lname":"LEGOWSKI"},
{"team":"I313766","fname":"0","lname":"LEGOWSKI"},
etc. etc.]
How would I make it retrieve all the data instead of one row number of times?
Okay, I got the solution. Moving a single line declaring array vals into the while statement solved the problem - the array vals was initialized as an empty array each time, therefore allowing the proper .push of each row, instead of pushing last row from db table into data multiple times. Thanks to everybody who took time and tried answering.
function getTableData()
{
var data = [];
try {
var dbCon = $.db.getConnection();
var query = 'SELECT * FROM SAPPRD.ZUSERDATATAB';
var pstmt = dbCon.prepareStatement(query);
var rs = pstmt.executeQuery();
while (rs.next()) {
var vals = {}; // this is the moved line of code...
vals.team = rs.getString(1);
vals.fname = rs.getString(3);
vals.lname = rs.getString(2);
data.push(vals);
$.response.status = $.net.http.OK;
}
$.response.setBody(JSON.stringify(data));
// $.response.contentType = contentType;
// $.response.headers.set('Content-Disposition', 'filename=' + filename);
} catch (e) {
$.response.setBody('errors: ' + e.message);
}
}
solution above just in case someone needs it in future.
This is XSJS(server side JS) and not SAPUI5. The read of DB is pretty similar to the JDBC framework in Java to read DB tables and the result set collection will have the data and you iterate over them and move them to a local object.
There is only call to the DB during execute_query and rs.next() is just a loop to read each row.

listbox does not pass string to google script

When I select a user from listbox, the onChange() event triggers a function. It should pass a string to the function. Then the code finds the user's password and returns it for comparison. The following is the code which works fine if I hard code the user value, but not when I select it from the listbox.
function addClients(clients){
$('#customer').empty();
$('#customer').append('<option> ---- Choose a user ----</option>');
for (var i in clients) {
$('#customer').append('<option>'+clients[i]+'</option>');
$('#customer').trigger("chosen:updated");
}
}
getval function:
function getval(sel){
var usrpass = google.script.run.getuserpass(sel.value);
alert(usrpass);
}
the function in code.gs is as follows
function getuserpass(userval){
var usrpass = "";
var doc = SpreadsheetApp.openById("spreadsheet id");
var sheet = doc.getActiveSheet();
var data = sheet.getRange(3, 3, sheet.getLastRow(),5).getValues();;
for(n=0;n<data.length;++n){
// iterate row by row and examine data in column A
if(data[n][0].toString().match(userval)==userval){ usrpass = data[n][4]};
}
return usrpass;
}
Why does the return value come back as undefined rather than the password.
If I hardcode username in the function and run the function, then the return value is the value in the fifth column.
Try structuring the code like this:
<script>
function onSuccess(returnVal) {
alert('Success! ' + returnVal);
};
function getval(sel){
var selectValue = sel.value;
console.log('selectValue: ' + selectValue);
google.script.run
.withSuccessHandler(onSuccess)
.getuserpass(sel.value);
};
</script>
You can iterate through the object to see what is really in it, as a debugging test.
for (var propertyVal in sel) {
console.log('this property: ' + propertyVal);
console.log('this value: ' + sel[propertyVal]);
};
And see what is really in the object.

Sammy js optional parameters

I'm using ajax for paging so Sammy.js is great choice. But I'm also using checkboxes which filters results. This is ok for Sammy: I have to define route which Sammy will intercept. Problem is :I don't want some filters(parameters) to show on URL if they are not checked but Sammy does not support optional parameters.
var samm = $.sammy(function () {
this.defaultCheckFormSubmission = this._checkFormSubmission;
this._checkFormSubmission = function (form) {
var $form, path, verb;
$form = $(form);
path = $form.attr("action");
verb = this._getFormVerb($form);
var index = path.indexOf("#");
if (verb === "get" && path.indexOf("#") == -1) {
return true;
}
else {
return this.defaultCheckFormSubmission(form);
}
};
this.get('#/Page=:page', function (context) {
alert("sammy");
});
});
samm.run('#');
I don't want all my URLs look like www.something.com#/Page=5%Filter1=0?Filter2=0?Filter3=0?Filter4=1...........
If you don't want Sammy to handle extra filters (like unchecked checkbox values), just don't put them in your route. Instead just grab the parameters from the controls via jquery and do the ajax request like that. So Something like this:
this.get('#/Page=:page', function (context) {
var page = this.params['page'];
var filter1 = $("#chkFilter1").is(':checked');
var filter2 = $("#chkFilter2").is(':checked');
var filter3 = $("#chkFilter3").is(':checked');
//etc..
//do work here
});
If you need the URL to be different for deep linking or google tracking and you know the max number of variables you need, then you can plan out your routes for the amount of variables you have. You must put the most variables first, because otherwise Sammy will match the URLs incorrectly. This is how you would make the URL only show checked values but still grab the unchecked values via JQuery:
this.get('#/Page=:page%filter1=:filter1?filter2=:filter2?filter3=:filter3', function (context) {
var page = this.params['page'];
var filter1 = this.params['filter1'];
var filter2 = this.params['filter2'];
var filter3 = this.params['filter3'];
});
this.get('#/Page=:page%filter1=:filter1?filter2=:filter', function (context) {
var page = this.params['page'];
var filter1 = this.params['filter1'];
var filter2 = this.params['filter2'];
var filter3 = $("#chkFilter1").is(':checked');
});
this.get('#/Page=:page%filter1=:filter1', function (context) {
var page = this.params['page'];
var filter1 = this.params['filter1'];
var filter2 = $("#chkFilter1").is(':checked');
var filter3 = $("#chkFilter2").is(':checked');
});
Another option is to ditch the querystring variables and just use a URL structure like this www.something.com#/5/0/1/0/1. Which would look like this:
this.get('#/:page/:filter1/:filter2/:filter3/:filter4', function (context) {
var page = this.params['page'];
var filter1 = this.params['filter1'];
var filter2 = this.params['filter2'];
var filter3 = this.params['filter3'];
var filter4 = this.params['filter4'];
});
Having said all those options, if you have an unknown possible variables you would have to do something more dynamic which is explained here: sammyjs optional parameters

Categories