How to Clone an custom entity in dynamics 365 using javaScript - 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) {
});

Related

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

Sharepoint 2013 Javascript - Get List Fields

I am on a double learning curve with SharePoint 2013 development and JavaScript.
Please refer to below.
function GetListFields(listname, viewname, ResultCallBackFunction)
{
var clientContext = new SP.ClientContext.get_current();
var web = clientContext.get_web();
var list = web.get_lists().getByTitle(listname);
if (viewname == "")
{
var view = list.get_views().getByTitle(viewname);
var listFields = view.get_viewFields();
}
else
{
this.listFields = list.get_fields().getByInternalNameOrTitle("Title");
}
clientContext.load(this.listFields);
clientContext.executeQueryAsync(onListFieldsQuerySucceeded, onListFieldsQueryFailed);
function onListFieldsQuerySucceeded()
{
console.log(listFields.get_fields().getByInternalNameOrTitle("Title").get_internalName());
var fldArray = new Array();
var fieldEnumerator = listFields.getEnumerator();
while (fieldEnumerator.moveNext())
{
var oField = fieldEnumerator.get_current();
fldArray.push(oField);
}
ResultCallBackFunction(fldArray);
}
function onListFieldsQueryFailed()
{
alert("Something went wrong. The End is Nigh.");
}
}
The intent is to call GetListFields to return an array with the list's fieldnames. This returns an error "Unable to get property 'get_fields' of undefined or null reference" at the line "console.log....". Please note that this is for my debugging.
If I change the code for function GetListFields as follows:
var clientContext = new SP.ClientContext.get_current();
var web = clientContext.get_web();
var list = web.get_lists().getByTitle(listname);
if (viewname == "")
viewname = "All Items";
var view = list.get_views().getByTitle(viewname);
this.listFields = view.get_viewFields();
I DO get a result but this contains a field named 'LinkTitle' which I do not have in my list because I have renamed this. What am I missing?
Further to the above, I got an error when using
var listFields = ...
which fixed by doing
this.listFields = ...
but do not understand the difference.
Thanks for any help or pointers.
I took a moment to test your code in my Sharepoint 2013 environment.
I made some changes and now it works.
You can see the resulting script bellow.
Here is some important information about the field names in the result array.
The names of the fields in the view returned by Sharepoint are the internal names and not the title of the field.
This is the reason why you get LinkTitle instead of the real title of your field.
When you create a field in the Sharepoint interface, Sharepoint create a title for the field and also an internal name based on the title.
For example, if I create a field named « my test field », Sharepoint will say the title of the field is « my test field » and the internal name is « my_x0020_test_x0020_field ».
<script>
function GetListFields(listname, viewname, ResultCallBackFunction)
{
var clientContext = new SP.ClientContext.get_current();
var web = clientContext.get_web();
var list = web.get_lists().getByTitle(listname);
var listFields;
var view;
var defaultViewName = 'All Items';
if (viewname === "")
{
viewname = defaultViewName;
}
view = list.get_views().getByTitle(viewname);
listFields = view.get_viewFields();
clientContext.load(listFields);
clientContext.executeQueryAsync(onListFieldsQuerySucceeded, onListFieldsQueryFailed);
function onListFieldsQuerySucceeded()
{
var fldArray = new Array();
var fieldEnumerator = listFields.getEnumerator();
while (fieldEnumerator.moveNext())
{
var oField = fieldEnumerator.get_current();
fldArray.push(oField);
}
ResultCallBackFunction(fldArray);
}
function onListFieldsQueryFailed()
{
alert("Something went wrong. The End is Nigh.");
}
}
function MyCallBack(fieldArray) {
for (var x=0;x<fieldArray.length;x++) {
console.log(fieldArray[x]);
}
}
</script>
<a id="callGetListFields" href="#" onclick="GetListFields('MyListName','MyViewName', MyCallBack);">Call function GetListFields</a>
Hope this help!

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?

Why won't my Google Calendar Script run?

I am using Google Script to create a form that will create an event, as you can see from the code I have used two panels. I want to create multiple event forms on the 'parent' panel, I am trying to use the 'child' to hold information about the event. I want to run createEvent() on each child panel, but when I run it the script will not run and show this error message:
"Error occured: InternalError: Cannot find method createEvent((class),(class),(class),object)."
function doGet(){
var app = UiApp.createApplication().setTitle('Create Events');
//Create a penel which holds all the form elelemnts
var parent = app.createHorizontalPanel().setId('parent');
var panelOne = app.createVerticalPanel().setBorderWidth(2);
var eventTitleLabel = app.createLabel('Event Title:');
var eventTitle = app.createTextBox();
var eventStartDateLabel = app.createLabel('Event Start Date:');
var evenStartDate = app.createDateBox();
var eventEndDateLabel = app.createLabel('Event End Date:');
var evenEndDate = app.createDateBox();
var eventDeatilLabel = app.createLabel('Event Details:');
var eventDetail = app.createTextArea().setSize('150', '100');
var eventButton = app.createButton('Create Events');
var cancelButton = app.createButton('Cancel');
panelOne.add(eventTitleLabel)
.add(eventTitle)
.add(eventStartDateLabel)
.add(evenStartDate)
.add(eventEndDateLabel)
.add(evenEndDate)
.add(eventDeatilLabel)
.add(eventDetail)
.add(eventButton)
.add(cancelButton);
var eventHandler = app.createServerClickHandler('createEvents');
eventHandler.addCallbackElement(parent);
//Add this handler to the button
eventButton.addClickHandler(eventHandler);
parent.add(panelOne);
app.add(parent);
app.close();
return app;
}
function createEvents(e){
//Get the active application
var app = UiApp.getActiveApplication();
try{
var eventTitle = e.parameter.eventTitle;
var eventStartDate = e.parameter.eventStartDate;
var eventEndDate = e.parameter.eventEndDate;
var eventDetails = e.parameter.eventDetail;
var cal = CalendarApp.getDefaultCalendar();
cal.createEvent(eventTitle, eventStartDate,eventEndDate,{description:eventDetails});
app.add(app.createLabel('Event created Successfully'));
app.getElementById('panel').setVisible(false);
return app;
}
catch(e){
app.add(app.createLabel('Error occured: '+e));
return app;
}
}
All the input widgets need a .setName() to be able to pass their values to the server function. https://developers.google.com/apps-script/guides/ui-service#ServerHandlers
Also consider using Logger.log() for debugging.
You simply forgot to set names to the widgets you want to get data from... in your example :
var eventTitleLabel = app.createLabel('Event Title:');
var eventTitle = app.createTextBox().setName('eventTitle');
var eventStartDateLabel = app.createLabel('Event Start Date:');
var evenStartDate = app.createDateBox().setName('evenStartDate');
var eventEndDateLabel = app.createLabel('Event End Date:');
var evenEndDate = app.createDateBox().setName('evenEndDate');
var eventDeatilLabel = app.createLabel('Event Details:');
var eventDetail = app.createTextArea().setSize('150', '100').setName('eventDetail');

Google Apps Script Listbox Populate based on previous ListBox I am able to get 2 to work but not 3

Need a little help figuring out how to get 3 list boxes to populate based on the previous list box. So far what I have is 1 list box that populates from a spreadsheet. Can someone help me with setting up so that the 2nd listbox will populate based off the first and a 3rd listbox that will populate based off of the first listbox? Here is the code:
function doGet(e){
var app = UiApp.createApplication();
var mainPage = app.createVerticalPanel().setId('mainPage');
var dataItemsLB = app.createListBox().setId('dataItemsLB').setName('dataItemsLB');
var dataItemsLbl = app.createLabel('Data Items');
dataItems(dataItemsLB);
mainPage.add(dataItemsLB);
app.add(mainPage);
return app;
}
function dataItems(listbox){
var app = UiApp.getActiveApplication();
var ss = SpreadsheetApp.openById('0AhraBJOts4V3dDhYbERTR0hFNUtNdEhZd2c4OElpY0E');
var list = ss.getSheetByName('dataItems');
var values = list.getRange(1,1,ss.getLastRow(),1).getValues();
for (var i in values){
listbox.addItem(values[i][0].toString());
}
return app;
}
The code above is only for 1 listbox but I thought it would help me to start from the bottom so I understand any explanation.
Thanks for any advice!
Replied on community try this code:
function doGet(e){
var app = UiApp.createApplication();
var mainPage = app.createVerticalPanel().setId('mainPage');
var dataItemsLB = app.createListBox().setId('dataItemsLB').setName('dataItemsLB'); // create a basic list box
var dataItemsLB2 = app.createListBox().setId('dataItemsLB2').setName('dataItemsLB2'); // create a basic list box
var dataItemsLB3 = app.createListBox().setId('dataItemsLB3').setName('dataItemsLB3'); // create a basic list box
var dataItemsLbl = app.createLabel('Data Items');
dataItems(dataItemsLB); // call the "dataItems" function to populate the list box
// Create Server Handlers
var sHandlerLB = app.createServerHandler("listLBSelect");
sHandlerLB.addCallbackElement(mainPage);
dataItemsLB.addChangeHandler(sHandlerLB);
dataItemsLB2.addChangeHandler(sHandlerLB);
mainPage.add(dataItemsLB);
mainPage.add(dataItemsLB2);
mainPage.add(dataItemsLB3);
app.add(mainPage);
return app;
}
function dataItems(listbox){
var app = UiApp.getActiveApplication();
var ss = SpreadsheetApp.openById('0AhraBJOts4V3dDhYbERTR0hFNUtNdEhZd2c4OElpY0E');
var list = ss.getSheetByName('dataItems');
var values = list.getRange(1,1,ss.getLastRow(),1).getValues();
for (var i in values){
listbox.addItem(values[i][0].toString());
}
return app;
}
function listLBSelect(e) {
var app = UiApp.getActiveApplication();
Logger.log(e);
Logger.log("Listbox changed: " + e.parameter.source);
// check which listbox has been changed:
switch(e.parameter.source) {
case "dataItemsLB":
var dataItemsLB2 = app.getElementById("dataItemsLB2");
dataItemsLB2.addItem("aaaaaa");
dataItemsLB2.addItem("bbbbbb");
dataItemsLB2.addItem("cccccc");
break;
case "dataItemsLB2":
var dataItemsLB3 = app.getElementById("dataItemsLB3");
dataItemsLB3.addItem("hhhhhh");
dataItemsLB3.addItem("jjjjjj");
dataItemsLB3.addItem("kkkkkk");
break;
}
return app;
}

Categories