CRM Dynamics 2013 Javascript make a field not updatable - javascript

Hi I have a scenario where in CRM form onload, I have a function that auto-populates a random generated number. I then open a URL using a Ribbon Button, after that I save the record, My issue when I attempt to save the record the form loads again therefore overrides my random number, which causes data to be corrupt. I have attempted to lock the fiels to readonly after the page loads, but however when the page saves it still ovverrides the value, please see my code below:
function AutonumberGenerator()
{
var uniqueRandoms = [];
var numRandoms = 500000;
if (!uniqueRandoms.length) {
for (var i = 0; i < numRandoms; i++) {
uniqueRandoms.push(i);
}
}
var index = Math.floor(Math.random() * uniqueRandoms.length);
var val = uniqueRandoms[index];
// now remove that value from the array
uniqueRandoms.splice(index, 1);
Xrm.Page.getAttribute("new_opguploadidentifier").setValue(val);
Xrm.Page.getAttribute("new_opguploadidentifier").controls.get(0).setDisabled(true);
}
Please note I am using CRM Dynamics 2013 ,Please help

You could simply check the value. If it's null, fill it. If it isn't, don't.
Someting like this in your onload, where you now fill the field:
if (Xrm.Page.getAttribute("your_random_number_field").getValue() == null) {
AutonumberGenerator();
}

Related

Why doesn't Interactive Grid process save values set using the Model interface in JavaScript?

I'm writing a JavaScript function to allow users of an application built using Oracle Application Express 21.1 to paste data from Excel spreadsheets into an Interactive Grid and save the data. Using the APEX JavaScript API I can update the model of the Interactive Grid with the data; the pasted values display correctly and when I subsequently access the model the correct values are returned.
However when the Interactive Grid is saved, those values aren't saved to the underlying database table. What happens is:
Null columns updated by the JavaScript function remain null
Columns with existing data and then set by the JavaScript function become null
Null columns and columns with existing data that are then changed normally by the user are updated correctly
Columns initially set by the JavaScript function and then changed normally by the user are updated correctly
The grid is a simple Interactive Grid region based on the default EMP table, with a static ID of EmployeeGrid, and saves using the Interactive Grid process that is automatically generated when the grid was created.
I have entered the following code in the Execute when Page Loads section:
$("#EmployeesGrid_ig").on('paste', onPaste);
I have entered the following code in the Function and Global Variable Declaration section:
function onPaste(e) {
if (!e.originalEvent.clipboardData ||
!e.originalEvent.clipboardData.items) return;
let items = e.originalEvent.clipboardData.items;
let data;
for (let i = 0; i < items.length; i++) {
if (items[i].type == 'text/plain') {
data = items[i];
break;
}
}
if (!data) return;
data.getAsString(function(text) {
// Split the clipboard data into rows.
text = text.replace(/\r/g, '').trim('\n');
let rowsOfText = text.split('\n');
let rows = [];
// Iterate over each row of text and push the trimmed data into rows[]
rowsOfText.forEach(function(rowOfText) {
let row = rowOfText.split('\t').map(function(colAsText) {
return colAsText.trim().replace(/^"(.*)"$/, '$1');
});
rows.push(row);
});
// We get the focused element (i.e. where the user wants to paste).
let $focused = $('.is-focused');
// We get metadata from the Interactive Grid.
let rowId = $focused.closest('tr').data('id');
let columnIndex = $focused.index();
let headerIndex = $focused.closest('table').find('th').eq(columnIndex).data('idx');
let ig$ = apex.region("EmployeesGrid").widget();
let grid = ig$.interactiveGrid("getCurrentView");
let model = grid.model;
let columns = grid.getColumns();
let record = model.getRecord(rowId);
//Map visible columns
let visibleColumns = columns.filter(function (val) { return !val.hidden; });
visibleColumns.sort(function(a,b){return a.index - b.index;});
// Complete the Promise after the grid is out of editing mode.
rows.forEach(function(row) {
row.forEach(function(value, offset) {
if (record !== null) {
visibleColumns.forEach(function(column, visColIdx) {
if (visColIdx === (headerIndex + offset)) {
if (model.allowEdit(record)) {
model.setValue(record, column.property, Number(value));
}
}
});
}
});
// To change record, get current record index and then get next record.
let recordIndex = model.indexOf(record);
record = model.recordAt(recordIndex + 1);
});
});
}
I have created a sample application on apex.oracle.com to demonstrate the behaviour, please note that I have set the grid to allow updates to existing rows only and that only the Sal and Comm number columns can be updated.
I found a similar question raised on Oracle Communities where user Woodrow could visually see values that were automatically updated in an Interactive Grid column but those values weren't present when the page was submitted.
The answer they found was to set the value as a string:
model.setValue(record, column.property, value);
instead of a number:
model.setValue(record, column.property, Number(value));
This was necessary even if the column was declared as a 'Number' column in APEX.
Another approach is to use apex.locale JSAPI, is more APEX native way and won't cause issues in the future with APEX upgrades
var number = apex.locale.toNumber( "1,234.56" );
number = apex.locale.toNumber( "$1,234.56", "FML999G999G990D00" );
number = apex.locale.toNumber( "$1234.56", "FML999G999G990D00" );
Check this out
https://docs.oracle.com/en/database/oracle/application-express/21.2/aexjs/apex.locale.html#.toNumber

Why won't the makeCopy portion of my script execute properly in Google Apps Script?

I am a very novice coder and am trying to accomplish the following using a Google Form:
Rename file uploaded by user based on name defined by combination of form fields
Create a copy of the uploaded file to a specific folder in GDrive, based on answer to particular form question
So far, I have managed to get Part 1 working, but Part 2 doesn't seem to function properly (no error message, just no action). Anyone able to guide me where I'm going wrong?
function fileRename() {
var form = FormApp.getActiveForm()
// returns the total number of form submissions
var length=form.getResponses().length;
//retrieve fileID of document uploaded by user in Question 6 of the form (i.e. Index 5)
var id=form.getResponses()[length-1].getItemResponses()[5].getResponse();
//getResponses()[length-1] retrieves the last form response, accounting for the fact that the first index is zero and hte last length-1
//gets the form answers used to concatenate the file name
var fileUploadEntity=form.getResponses()[length-1].getItemResponses()[0].getResponse();
var fileUploadDate=form.getResponses()[length-1].getItemResponses()[3].getResponse();
var fileUploadType=form.getResponses()[length-1].getItemResponses()[1].getResponse();
//accesses the uploaded file
var file=DriveApp.getFileById(id);
var name = file.getName();
//changes the file name
var name = fileUploadEntity+'_'+fileUploadDate+'_'+fileUploadType
file.setName(name);
//creates a copy and saves it to the relevant regional shared drive depending on which array the entity belongs to, using its four-letter identifier
var APAC = ["WRAU", "WRNZ", "WRSG", "WRMY", "WRHK"];
var NORAM = ["WRCA", "WRCC", "WRCW", "WRUS"];
var MEA = ["WRKE", "WRUG", "WRSO", "WRSA", "WRRW", "WRTZ", "WRZW"];
var LATAM = ["WRMX"];
var EEA = ["WRBE", "WRUK"];
var folderAPAC = DriveApp.getFolderById('1IKIDSEEGHf802WaF4l4ntN9uiUO5jJpa');
var folderNORAM = DriveApp.getFolderById('1BitldN3Uw7453wxnnI1X5PUmbmTiQn5O');
var folderMEA = DriveApp.getFolderById('18tWR1C-mdO7moAtktOHJsvXjx_V0kdg0');
var folderLATAM = DriveApp.getFolderById('1cG0iPocn3KyXK8XgaxnZNWVU-HKJ97dX');
var folderEEA = DriveApp.getFolderById('1N8tB8AjMkR7gRarcwd4NYmry_wh0WVkY');
if (fileUploadEntity.indexOf(APAC)>-1) {
file.makeCopy(name, folderAPAC);
}
else if (fileUploadEntity.indexOf(NORAM)>-1) {
file.makeCopy(name, folderNORAM);
}
else if (fileUploadEntity.indexOf(LATAM)>-1) {
file.makeCopy(name, folderLATAM);
}
else if (fileUploadEntity.indexOf(MEA)>-1) {
file.makeCopy(name, folderMEA);
}
else if (fileUploadEntity.indexOf(EEA)>-1) {
file.makeCopy(name, folderEEA);
}
}
You code is using indexOf the wrong way.
Instead of
fileUploadEntity.indexOf(APAC)
try
APAC.indexOf(fileUploadEntity)
Do the same or the other places where indexOf is used
Reference
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

Parsing out muiltipicker in javascript

I have created a form that pulls a person's (peoplepicker) office location automatically from AD via SharePoint's UPS and populates it in the entry field. What I'm having trouble with is pulling multiple individual's office locations and having that parse each individual's respective office location to place that in the field as well. Any ideas or help would be greatly appreciated.
Here is the form, and as you can see it can populate one person's office, but not the other individuals:
After further research, I want to give a thanks to the author of this useful JavaScript SharePoint library: http://spjsfiles.com/index.php?dir=SharePoint%20JavaScripts/spjs-utility/
This library gets a user's information from a SharePoint Master list. You get this with the following function: function fillFieldDemo(){
setFieldValue('Date', '1/1/2017');
setFieldValue('MM','Boston;London');
var userInfo = getUserInfo_v2(_spPageContextInfo.userId);
setFieldValue('Person', userInfo.Name);
setTimeout(function(){
var title = getFieldValue('Person');
setFieldValue('Title', title);
}, 2000);
}
_spBodyOnLoadFunctionNames.push("fillFieldDemo");
Now you can find the users' name, office, etc.
In order to parse through multiple names in an input text box and pull their offices respectively, you can alter this function, like so:
function fillFieldDemo() {
$('.button').on('click', function() {
var subjects = $('.ms-entity-resolved');
var offices = [];
for (var i = 0; i < subjects.length; i++) {
var s = $(subjects[i]).prop("title");
var print = $('.name').val(s);
var userInfo = **getUserInfo_v2**(s);
for (var key in userInfo) {
var value = userInfo.**Office**;
}
offices.push(value);
}
var input = $('.parse').val(offices);
});
}
_spBodyOnLoadFunctionNames.push("fillFieldDemo");
This will allow a user to input multiple names in an input text box and it will parse the names and grab the offices of each of those individuals.

Import google spreadsheet data into google forms with app script

I searched the internet and I can't find a response to this nor the documentation for it.
I need to dynamically generate Google forms questions with data from a Google spreadsheet using app script, but I don't know how to reference and read a spreadsheet.
In your spreadsheet select Tools > Script Editor and adapt this to your needs:
/**
After any change in the sheet, update the combobox options in the Form
*/
function onChange(e) {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
var range = sheet.getDataRange();
var values = range.getValues();
var comboValues = []; // <-- cheddar will go here
// in this example we are interested in column 0 and discarding row 1 (the titles)
for (var i = 1; i <= values.length; i++) {
var v = values[i] && values[i][0];
v && comboValues.push(v)
}
// Sort the values alphabetically, case-insensitive
comboValues.sort(
function(a, b) {
if (a.toLowerCase() < b.toLowerCase()) return -1;
if (a.toLowerCase() > b.toLowerCase()) return 1;
return 0;
}
);
Logger.log(comboValues);
// Use your form ID here. You can get it from the URL
var form = FormApp.openById('<my-form-id>');
/*
Uncomment this to display the item IDs
and pick the one that you want to modify
var items = form.getItems();
for (i = 0; i < items.length; i++) {
Logger.log("ID: " + items[i].getId(), ': ' + items[i].getType());
}
*/
form.getItemById(807137578).asListItem().setChoiceValues(comboValues);
};
To debug, select the script in the combobox and click either "play" or "debug". The first time you will have to give it permissions to interact with your spreadsheet and form.
Once you are satisfied with the result, in the editor select Resources > Triggers for the active project and add this method to be triggered with any modification on the spreadsheet (on change, not on edit).
After this, your form options will be changed in real time after any change in your spreadsheet.
It's pretty straightforward, see here: https://developers.google.com/apps-script/guides/sheets#reading
You just need to open the sheet by its doc key, select the data and read the cells as a JS object.
Here is an example which works for me, pls kindly check:
function getSpreadsheetData(sheetId) {
// This function gives you an array of objects modeling a worksheet's tabular data, where the first items — column headers — become the property names.
var arrayOfArrays = SpreadsheetApp.openById(sheetId).getDataRange().getValues();
var headers = arrayOfArrays.shift();
return arrayOfArrays.map(function (row) {
return row.reduce(function (memo, value, index) {
if (value) {
memo[headers[index]] = value;
}
return memo;
}, {});
});
}
function makeOurForm() {
var sheetId='input_your_sheet_id'
getSpreadsheetData(sheetId).forEach(function (row) {
// Set your form template as follows
var formName=row.Name
// Create your form programmatically, each row means one form
var form = FormApp.create(formName)
form.setDescription('xxx');
var capitalizedName = row.Name.charAt(0).toUpperCase() + row.Name.slice(1);
form.addSectionHeaderItem().setTitle(capitalizedName);
var item = form.addMultipleChoiceItem();
item.setTitle('xxx')
.setChoices([
item.createChoice('xxx'),
]);
form.addParagraphTextItem().setTitle('xxx');
});
}
You can get your sheet Id from url, for example:
https://docs.google.com/spreadsheets/d/YourSheetId/edit#gid=0
Let me know if you have any further questions.

javascript update controls onload

iv'e got 2 html pages
one performs a "get" method on the other
these pages are duplicates in that they own they both poses a form with the same control types
and control names
when i submit my form from the source page my url string consist of the values appended together after a '?' char
....?txtName=era&txtAge=28&gender=male&langHe=on&langEn=on&select=1
in the detestation page onload i call a function which splits the control names and their values and sets them
// this is called from <body onload="f();">
function f() {
var st = new String(location.search);
st = st.substring(1, st.length);
var input = st.split('&');
var value;
var ctrl;
var val;
var _control;
for (var i = 0; i < input.length; i++)
{
value = input[i].substring(0, input[i].length);
ctrl = value.substring(0, value.indexOf('='));
val = value.substring(value.indexOf('=') + 1, value.length);
_control = document.getElementsByName(ctrl);
_control.value = val;
}
}
i debugged this function and checked that every thing is put in to place as it should
the problem is that after the value are set to the controls
they do not appear on the page , as if they didn't get set at all
additionally in Google chrome i get a "Aw,Snap!" Error after these actions (Aw Snap happens only when i debug )
i'm new to java-script and i'm guessing there's a problem with the way i'm assigning these values , i tried also just the first control which is a text type input and it also does not get updated .
any idea's on why this doesn't work ?
thanks in advance
eran.
Try changing the last line to:
_control[0].value = val;
UPDATE:
It would be a lot easier if you used jQuery:
$('[name='+ctrl+']').val(val);

Categories