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

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?

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) {
});

Two window.location not working togeather

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}`;

Function works as expected when called from function using XMLHttpRequest, but fails when called from a function using EventSource. Why is this?

I'm working on creating a basic messenger using Javascript. I have three functions in a separate js file called loadMessage, messageListener, and displayMessage.
The function loadMessage makes a call to my database for all existing messages, and then calls displayMessages to construct some divs which I use to show the messages I got from the server. These divs are created to appear under each other, with the bottom div being the newly created one showing the latest message.
Once all the messages have been created loadMessage then calls messageListener. This function 'listens' for any new messages which might appear on the database. If any appear then messageListener calls displayMessage. I expect this to create a new div at the bottom of my other divs as before, however when it calls displayMessage the behaviour is completely different than when loadMessage calls displayMessage.
Specifically, it does not create a new div but instead just changes the text in an existing div which appears anywhere within the newly created divs (for example, the div which displays the first message or one somewhere in the middle).
My HTML and PHP files all behave as expected, so I think my issue is somewhere in these three functions.
How can I fix this to behave as expected?
Code:
// Loads chat messages history and listens for upcoming ones.
function loadMessages(userID, contactID) {
contactIDGlobal = contactID;
//load existing messages
var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
var param = "userID="+userID+"&contactID="+contactID+"&date="+date;
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","Interface-getMessage.php?", true);
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.send(param);
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//retrives a string of all past messages
var messageString = xmlhttp.responseText;
//parse string to get messages.
var parseMessageString = messageString.split('-');
for (var i = 0; parseMessageString[i] !== null && parseMessageString[i] !== ''; i = i+5){
var contactID = parseMessageString[i];
var senderID = parseMessageString[i+1];
var message = parseMessageString[i+2];
var time = parseMessageString[i+3];
var mID = parseMessageString[i+4];
displayMessage(userID, senderID, contactID, message, date, time, mID);
}
}
};
//listen for new messages
messageListener(userID, contactID);
}
function messageListener(userID, contactID){
if(typeof(EventSource)!=="underfined") {
var newMessage = new EventSource("testerfile.php?userID="+userID+"&contactID="+contactID);
newMessage.onmessage = function(event) {
var newMessageData = event.data;
var parseNewMessage = newMessageData.split('-');
//sender ID may be different to the userID due to the way that messages are stored on the server. Received messages have a different sender.
var senderID = parseNewMessage[0];
var contactID = parseNewMessage[1];
var message = parseNewMessage[2];
var date = parseNewMessage[3];
var time = parseNewMessage[4];
var messageID = parseNewMessage[5];
console.log(event.data);
displayMessage(userID, senderID, contactID, message, date, time, messageID);
};
}else {
document.getElementById("messages").innerHTML = "Your browser does not support this";
}
}
// Displays a Message in the UI.
function displayMessage(userID, senderID, contactID, nMessage, date, time, id){
var messageListElement = document.getElementById('messages');
var messageInputElement = document.getElementById('message');
// If an element for this message already exists, then get it
var id = id;
var div = document.getElementById(id);
// If an element for that message does not exists yet we create it.
if (!div) {
var container = document.createElement('div');
if (userID == senderID){
container.innerHTML = SENDER_MESSAGE_TEMPLATE;
}else{
container.innerHTML = MESSAGE_TEMPLATE;
}
div = container.firstChild;
div.setAttribute('id', id);
for (var i = 0; i < messageListElement.children.length; i++) {
var child = messageListElement.children[i];
}
messageListElement.insertBefore(div, child);
}
var messageElement = div.querySelector('.message');
messageElement.textContent = nMessage;
// Replace all line breaks by <br>.
messageElement.innerHTML = messageElement.innerHTML.replace(/\n/g, '<br>');
}
// Template for messages.
var SENDER_MESSAGE_TEMPLATE =
'<div class="sender_message-container">' +
'<div class="message"></div>' +
'</div>';
var MESSAGE_TEMPLATE =
'<div class="message-container">' +
'<div class="message"></div>' +
'</div>';
The problem was coming from the date being returned as y-m-d, and the parser using "-". This mean I was creating a time var which was the month of my date, and the message ID as the day. I made the alteration below to fix this...
var newMessageData = event.data;
var parseNewMessage = newMessageData.split('-');
//sender ID may be different to the userID due to the way that messages are stored on the server. Received messages have a different sender.
var senderID = parseNewMessage[0];
var contactID = parseNewMessage[1];
var message = parseNewMessage[2];
var date = parseNewMessage[3]+"-"+parseNewMessage[4]+"-"+parseNewMessage[5];
var time = parseNewMessage[6];
var messageID = parseNewMessage[7];

How to print only the created columns in Sharepoint using JavaScript

I need to print only the column that has been created by me.
function retrieveFieldsOfListView(listTitle,viewName){
var context = new SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle(listTitle);
var listFields = list.get_fields();
context.load(listFields);
context.executeQueryAsync(printFieldNames,onError);
function printFieldNames() {
var e = listFields.getEnumerator();
while (e.moveNext()) {
var fieldName = e.get_title();
console.log(fieldName);
}
}
function onError(sender,args)
{
console.log(args.get_message());
}
}
But this code is printing all the pre-defined fields along with my field. I don't want the pre-defined fields like 'modified,created,etc'. I want only the coding changes. UI changes are not upto me.
How to determine whether field is system or user-defined
Probably the most reliable way to determine whether field is system or user-defined is to utilize SourceId property of a Field. For system fields it's value is set to http://schemas.microsoft.com/sharepoint/v3
Note: SP.Field object does not expose SourceId property, but it could be extracted from SP.Field.schemaXml property as demonstrated below:
function getListFields(listTitle,success,error){
var context = SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle(listTitle);
var fields = list.get_fields();
context.load(fields);
context.executeQueryAsync(
function(){
success(fields);
},
error);
}
//Usage
getListFields('Pages',
function(fields) {
//get only user defined fields
var userDefinedFields = fields.get_data().filter(function(f){
var schema = f.get_schemaXml();
if (schema.indexOf('SourceID="http://schemas.microsoft.com/sharepoint/v3"') === -1){
return f;
}
});
//print user defined fields title
userDefinedFields.forEach(function(f){
console.log(f.get_title());
});
},
function(sender,args)
{
console.log(args.get_message());
});
Like a said SourceId property is not available for Field object, the below example demonstrates a different approach for getting field properties
function getListFields(listTitle,success,error){
var context = SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle(listTitle);
var fields = list.get_fields();
context.load(fields,'Include(SchemaXml)');
context.executeQueryAsync(
function(){
var result = [];
fields.get_data().forEach(function(f){
var schema = f.get_schemaXml();
result.push(schemaXml2Json(schema));
});
success(result);
},
error);
}
function schemaXml2Json(schemaXml)
{
var jsonObject = {};
var schemaXmlDoc = $.parseXML(schemaXml);
$(schemaXmlDoc).find('Field').each(function() {
$.each(this.attributes, function(i, attr){
jsonObject[attr.name] = attr.value;
});
});
return jsonObject;
}
Then you could use SourceId property:
getListFields('Pages',
function(fields) {
//get only user defined fields
var userDefinedFields = fields.filter(function(f){
if (f.SourceID !== "http://schemas.microsoft.com/sharepoint/v3"){
return f;
}
});
//print user defined fields title
userDefinedFields.forEach(function(f){
console.log(f.DisplayName);
});
},
function(sender,args)
{
console.log(args.get_message());
});

Pass parameter in bbUI to another page failed

Based On : Blackberry Wiki Screen
With my full code : My Full Code
If i user onscreenready function to PASS MY PARAMETER from page A like this :
ondomready: function(element, id) {
if (id == 'UPDATE') {
UPDATE_initialLoad(element, params);
}
}
For pages that I would give / throw parameters (Let's just say page B), how do I win or get results / parameters provided by the previous form. I want to make a form update the data in the form, and will be filled all the time throwing fieldnya parameter data.
Im using like this in my Page B :
function UPDATE_initialLoad(element, params) {
setTimeout(UPDATE_loadAfterTimeout,100);
}
function UPDATE_loadAfterTimeout() {
var id = data_id
var nmDepan = data_depan
var nmBelakang = data_belakang
var phone = data_phone
var email = data_email
document.getElementById('txtID').value = id
document.getElementById('txtNMDEPAN').value = nmDepan
document.getElementById('txtNMBELAKANG').value = nmBelakang
document.getElementById('txtPhone').value = phone
document.getElementById('txtEmail').value = email
}
But result is failed...
Please help me
You'll want to push data to the page:
bb.pushScreen("myPage.html", "UPDATE", myParams);
Then this will fire when the page is loaded:
ondomready: function(element, id, params) {
if (id == 'UPDATE') {
UPDATE_initialLoad(element, params);
}
}
Make sure to pass the parameters to your delayed function:
function UPDATE_initialLoad(element, params) {
setTimeout(UPDATE_loadAfterTimeout(params),100);
}
function UPDATE_loadAfterTimeout(params) {
var id = params['data_id'];
var nmDepan = params['data_depan'];
var nmBelakang = params['data_belakang'];
var phone = params['data_phone'];
var email = params['data_email'];
document.getElementById('txtID').value = id
document.getElementById('txtNMDEPAN').value = nmDepan
document.getElementById('txtNMBELAKANG').value = nmBelakang
document.getElementById('txtPhone').value = phone
document.getElementById('txtEmail').value = email
}
I hope this helps.

Categories