Javascript REST Web Services PUT query - javascript

can anyone help me with javascript button who make PUT operation.
action : function() {
var selectedRecords = this.view.viewGrid.getSelectedRecords();
var lengthAr = selectedRecords.length;
for (var i=0; i < lengthAr ; i++){
alert(selectedRecords[i].id);
}
},
i want to update one column for all selectedRecords[all]. For this i must make PUT query like this:
http://wiki.openbravo.com/wiki/JSON_REST_Web_Services :
{data: {"_identifier":"United States","_entityName":"Country","$ref":"Country\/100","id":"100","client":
{"_identifier":"System","_entityName":"ADClient","$ref":"ADClient\/0","id":"0","active":true},"organization":
{"_identifier":"*","_entityName":"Organization","$ref":"Organization
... truncated for clarity ...
(USA)","_entityName":"ADLanguage","$ref":"ADLanguage\/192","id":"192","active":true},"currency":{"_identifier":
"USD","_entityName":"Currency","$ref":"Currency\/100","id":"100","active":true},"iBANLength":null,"iBANCode":null}}
but i'm new with javascript and i don't know how to do this. I can't undenstand this code:
What is _identifier? should not it be ID from selectedRecords[i].id?
How i can write the query in javascript?

Related

Replacing Text with replacetext() and defining said replacement as heading

I have a Google spreadsheet and a Google document. The document is a report which gets filled by the spreadsheet. The spreadsheet is also defining what comes into the report. Therefore I have a script, which gathers a bunch of placeholders depending on values in the the document.
After all the placeholders have been inserted in the document (there are a couple of pages before that) it looks kind of like this:
{{header1.1}}
{{text1.1}}//this is already a couple lines of text
{{table1.1}}
{{table.dir}}
{{blob1.1}}
{{blob.dir}}
I already have a script, which inserts all the text parts and I have set up a script, which should be capable of writing the tables at the correct position. So far I can replace the {{header1.1}}, but if I try to define it as a heading it works, but everything after the header1.1 is also a heading
I've been at this problem for quite a while and didn't get and its always one step forward one step back. Also this is my first question after a couple of years just reading on stackoverflow. I'd appreciate if someone could help.
function myUeberschriftenboi() {
doc = DocumentApp.openById('someID');
console.log(doc.getName());
var body = doc.getBody();
//formate
const plain3style = {};
plain3style[DocumentApp.Attribute.HEADING] = DocumentApp.ParagraphHeading.HEADING3;
var lvl2array = [ "{{header1.1}}" , "{{header1.2}}" ];
var fill2array = [ "Energy" , "Energyflow" ]
var lvl2count = 1;
for( var j = 0 ; j < lvl2array.length ; j++)
{
var seek = body.findText(lvl2array[j]);
if( seek != null)
{
body.replaceText(lvl2array[j] , "1.1."+lvl2count+" "+fill2array[j]+"\n");
var seek2 = body.findText("1."+lvl2count+" "+fill2array[j]);
seek2.getElement().getParent().getChild().setAttributes(plain3style);
lvl2count++;
}}}

How to add validation to existing google form items via script?

I am trying to add validation, specifically text validation, for my google form text items.
However, it looks to me like the 'setValidation()' function only works with items with known type like TextItem.
To my understanding, if I pull a form item via 'getItemById()', I would get a generic item. It still has 'TEXT' type but google script just doesn't see it as a TextItem and therefore the 'setValidation()' function is not available for it.
I have tried doing thing like .asTextItem() with no luck. Here is an example script that fails to run because of an error
'TypeError: Cannot find function setValidation in object Item. (line
10, file "Code")' on line 9.
function validationTest() {
var form = FormApp.getActiveForm();
var items = form.getItems();
var textValidation = FormApp.createTextValidation()
.requireNumberGreaterThanOrEqualTo(0)
.requireWholeNumber();
for (var i = 0; i<items.length; i++) {
items[i].asTextItem();
items[i].setValidation(textValidation);
};
}
So, is there a known solution or workaround for this issue? Thank you in advance.
SC
You should add .build() at the end of your validation builder, as it's shown here.
Also, asTextItem should be called simultaneously with setValidation:
function validationTest() {
var form = FormApp.getActiveForm();
var items = form.getItems();
var textValidation = FormApp.createTextValidation()
.requireNumberGreaterThanOrEqualTo(0)
.requireWholeNumber()
.build();
for (var i = 0; i<items.length; i++) {
items[i].asTextItem().setValidation(textValidation);
};
}

Populating a Select Box with Data from Google Sheet

I have a Google site and am currently using the following script to populate my select box with data from the google sheet that is serving as my database:
<? var stringified = getData(); ?>
<?var data = JSON.parse(stringified)?>
<select size="10" id="userChoice">
<? for (var i = 0; i < data.length; i++) { ?>
<option>
<?= data[i] ?>
<? } ?>
</select>
This loads the page with the select box populated with every entry in the database. I'm wondering if this is the best way to go about it. What I would really like to do is have the contents of the select box be a little more dynamic.
I wrote out a script to filter through (by date) the contents of the Google Sheet, but I can't quite figure out how to have those filtered results show up in the above select box. I've tried several possible solutions, but keep hitting road blocks with them. Below is the function on the client side that passes the dates to the server side (note that I realize nothing in the below scripts would pass the data back to the select box. This is just to show how I am filtering through the data):
//Takes the dates that were entered into the first two date pickers and sends them over to the server side stringified. The server side then uses these dates to filter out jobs not within the given time period.
function dateFilter(){
var date = {};
//dates pusehd into array
date[0] = document.getElementById("startDate").value;
date[1] = document.getElementById("endDate").value;
//array stringified
var dates = JSON.stringify(date);//Convert object to string
google.script.run
.getData2(dates);
Then here is the code that filters through the database on the server side:
function getData2(dates) {
var ss = SpreadsheetApp.openById('1emoXWjdvVmudPVb-ZvFbvnP-np_hPExvQdY-2tOcgi4').getSheetByName("Sheet1");
var date = JSON.parse(dates);
var dateArray = [];
for (var k in date) {//Loop through every property in the object
var thisValue = date[k];//
dateArray.push(thisValue);
};
var startDate = Date.parse(dateArray[0]);
var endDate = Date.parse(dateArray[1]);
var jobReference = [];
var job;
var dateCell1;
var dateCell;
if ((startDate==NaN) || (endDate==NaN)){
for (var i = 2; job!=""; i++){
job = ss.getRange(i,43).getValue();
jobReference.push(job);
};
}
else{
for (var i = 2; job!=""; i++){
dateCell1 = ss.getRange(i,3).getValue();
dateCell = Date.parse(dateCell1);
if (startDate<=dateCell&&endDate>=dateCell){
job = ss.getRange(i,43).getValue();
jobReference.push(job);
Logger.log("here it is"+jobReference);
}
else{
}
}
};
var jR = JSON.stringify(jobReference);
return jR;
}
Now I've tried several things, having a success handler change the line <? var stringified = getData();?> to use getData2 doesn't seem to work (it yells at me that variable I'm trying to parse is undefined on the server side). So I tried putting an if/else in that would only have it parse if the variable was != to undefined, that didn't work either. Any suggestions would be appreciated.
I figured it out! This is functional, but perhaps not best practices, so if someone has any input, feel free to chime in.
So the first bit of code on the client side for the select box I left the same.
The next bit, where I send the dates over to the server side was changed to this:
function dateFilter(){
var sdate = document.getElementById("startDate").value;
var edate = document.getElementById("endDate").value;
google.script.run.withSuccessHandler(dateSuccess)
.getData2(sdate,edate);
}
So, since it was only two variables I took out the part that pushed it to an array. This eliminated the problem of parsing on the server side and thus having an undefined variable. I also added a success handler.
The server side code was left essentially the same, however I did change the for loop slightly. Instead of having it loop through the database until it found a blank cell in a particular column, I added var last = ss.getLastRow(); and had it loop though until i<= last. This kept the code from timing out on me.
Next I added the function I used for the success handler:
function dateSuccess(jobs){
document.getElementById('userChoice').options.length = 0;
var data = JSON.parse(jobs)
for (var i = 0; i < data.length; i++) {
var option = document.createElement("option");
option.text = data[i]
var select = document.getElementById("userChoice");
select.appendChild(option);
}
}
Works like a charm!
Scriptlets i.e. <? ?> are compiled and run when the page is created using execute function. They are not for dynamic modification of the web page. To modify the options based on a server returned data, in this case from getData(). You would do something like this
Firstly you set your google.script to call modifyoptions function on success
google.script.run.withSuccessHandler(modifyOptions)
.getData2(dates);
The above will code will automatically pass the return value of getData2 i.e Jr value to modifyOptions function
function modifyOptions(jobReference){
var selOpt = document.getElementById("userChoice")
selOpt.innerHTML ="" // Remove previous options
var options = ""
var data = JSON.parse(jobReference)
for (var i = 0; i < data.length; i++) {
options += "<option>"+data[i] +</option> //New string of options based on returned data
}
selOpt.innerHTML = options //Set new options
}
You can find a working example of how to modify the select-options in javascript here
Hope that helps!

JavaScript Asp.net repeating controls

I am trying to do the folowing with Asp.net 3.5/IIS
A web form with a top level repeatable form. So basically a Order->Products->ProductsParts kinda of scenerio. Order is only one. Product is repeatable. Each product has repeatable products parts. The product and product part have a whole bunch of fields so I cannot use a grid.
So, I have add/remove buttons for Product and within each product add/remove buttons for each product part.
That is my requirement. I have been able to achieve add/remove after some research using jquery/js. How, do i capture this data on the server? Since javascript is adding and removing these controls they are not server side and I don't know how to assign name attributes correctly. I am trying following javascript but it ain't working:
function onAddProperty(btnObject){
var previous = btnObject.prev('div');
var propertyCount = jquery.data(document.body, 'propertyCount');
var newDiv = previous.clone(true).find("*[name]").andSelf().each(function () { $(this).attr("name").replace(($(this).attr("name").match(/\[[0-9]+\]/), cntr)); }); ;
propertyCount++;
jquery.data(document.body, 'propertyCount', propertyCount);
//keep only one unit and remove rest
var children = newDiv.find('#pnlUnits > #pnlUnitRepeater');
var unitCount = children.length;
var first = children.first();
for (i = 1; i < unitCount; i++) {
children[i].remove();
}
newDiv.id = "pnlPropertySlider_" + propertyCount;
newDiv.insertBefore(btnObject);
}
I need to assign name property as array so that I can read it in Request.Form
Fix for not updating ids not working:
var newDiv = previous.clone(true).find("input,select").each(function () {
$(this).attr({
'name': function () {
var name = $(this).attr('name');
if (!name) return '';
return name.replace(/property\[[0-9]+\]/, 'property' + propertyCount);
}
});
}).end().insertBefore(btnObject);
The issue looks like the following line:
$(this).attr("name").replace(($(this).attr("name").match(/\[[0-9]+\]/), cntr));
This statement doesn't do anything. Strings in JavaScript an immutable, and .replace only returns the string with something replaced.
You would then have to actually set the attr("name") to the new string that has the replaced value:
http://api.jquery.com/attr/
I can't help much more without seeing your HTML.

Using c# code in javascript

I am trying to use C# in javascript like we are using it in MVC Razor View using # sign,
like suppose an array name list is passed to the View so we can access it in View like:
View
Length of array : <input type="text" value="#Model.list.Length" />
Or we can iterate list array also like:
#for(int i=0; i< Model.list.Length; i++)
{
console.log(Model.list[i]);
}
But my question is how we can iterate or use this array in the javascript code , something similar to :
JS
for(var i=0; i<#Model.list.Length; i++)
{
$("body").append("<h1></h1>").html(#Model.list[i]);
}
Thanks !
As i posted in my comment, this is a bit tricky. However, you can try to construct a javascript object with your c#.
Something like this (i don't know how this works exactly...):
var array = [
#for(var i = 0; i < Model.list.Length-1; i++){ #Model.list[i] , }
#Model.list[length]
]
which should result in:
var array = [
val1,
val2,
val3,
valn
]
Now you have an js var array, you can work with in your entire document.
You can't do it exactly that way. What you can do is use the C# to generate the javascript code for each line like this:
//...javascript code...
#for(var i = 0; i < Model.list.Length; i++)
{
$("body").append("<h1></h1>").html('#(Model.list[i])');
}
//...more javascript code...
This should output like this:
//...javascript code...
$("body").append("<h1></h1>").html(listitem0);
$("body").append("<h1></h1>").html(listitem1);
$("body").append("<h1></h1>").html(listitem2);
//etc.
//...more javascript code...

Categories

Resources