how to get navigated to a custom record from a button with some field sourced?(suitescript 2.0) - suitescript

i m doing this in my Client script which is being called by the function of UE script button.
var createEstimatorURL = url.resolveRecord({
recordType: 'customrecord_awt_estimator_hdr',
recordId: '',
isEditMode: true,
params: {
'project': project,
'customer': customer,
'createdBy': createdBy,
'projectStatus': projectStatus,
'subsid': subsid,
'awtEstRef': awtEstRef
}
});
After getting the URL from resolve record, I m doing newWindow = window.open(createEstimatorURL);
The record is getting opened in create mode (not saved yet), but how to source the fields that I sent as params? please help

They are in the request parameters of your context on the new page that opens.
You can use this bit
context.request.parameters['*'],
where * is the name of your parameter, to get them.

Related

Netsuite - Check a box from a Saved Search button

Some progress made here thanks to answer from Suitestar.
Managed to make a suitelet which performs the task. However:
Only works by putting an absolute item ID in the script itself.
The var rec_ID to pull through the ID of the item from the search does not work. I get a 'Missing Argument' error.
Opens a blank window and the saved search page defaults to a blanket item search. I just want a popup to say 'Approved' and for the search to stay the same.
How do I pull through the field ID from the search as well?
Suite URL and code below:
<button onclick=window.open(/app/site/hosting/scriptlet.nl?script=602&deploy=1&rec_id=2958);>Approve
/**
* #NApiVersion 2.x
* #NScriptType Suitelet
* #NModuleScope SameAccount
*/
define (['N/record'], function (record) {
function onRequest(scriptContext) {
var rec_Id=scriptContext.request.parameters.rec_Id; //getting parameter
var itemRecObj= record.load({ type: record.Type.INVENTORY_ITEM, id: '2958', isDynamic:true });
itemRecObj.setValue({ fieldId: 'custitem_aamac_custom_approved', value: true });
itemRecObj.save();
}
return {
onRequest: onRequest
};
});
You can write a backend logic in suitelet script for checking the check box.
Load the record with internal id of item
Use setValue with value "true" for check box fieldID .
And then save the record.
deploy the suitelet in release mode, copy the external url put it in button onclick function.as in screenshot you did.
pass the parameter using &rec_Id something like this in the last of url
https://tstdrv1911674.extforms.netsuite.com/app/site/hosting/scriptlet.nl?script=6030&deploy=1&compid=TSTDRV1911674&h=e3ac9c7644c25b4dded1&rec_Id=
and get the parameter in suitelet script using
var rec_Id=scriptContext.request.parameters.rec_Id; //getting parameter
var itemRecObj= record.load({
type: record.Type.INVENTORY_ITEM,
id: rec_Id,
isDynamic:true
});
itemRecObj.setValue({
fieldId: 'checkboxfieldId',
value: true
});
itemRecObj.save();

Google Form make POST request on submission

Is there a way to call an external API Endpoint on Google Forms every time the form is filled out?
First:
you'll need to set up your App script project and you'll do that by:
Visit script.google.com to open the script editor. (You'll need to be signed in to your Google account.) If this is the first time you've been to script.google.com, you'll be redirected to a page that introduces Apps Script. Click Start Scripting to proceed to the script editor.
A welcome screen will ask what kind of script you want to create. Click Blank Project or Close.
Delete any code in the script editor and paste in the code below.
This video and the doc will help
Second
you'll need to create an installable trigger, you can add it to the form directly or to the spreadsheet that has the responses
function setUpTrigger(){
ScriptApp.newTrigger('sendPostRequest') /* this has the name of the function that will have the post request */
.forForm('formkey') // you'll find it in the url
.onFormSubmit()
.create();
}
Check the doc
Third
create the sendPostRequest function and add the UrlFetchApp to it
function sendPostRequest(e){
// Make a POST request with form data.
var resumeBlob = Utilities.newBlob('Hire me!', 'text/plain', 'resume.txt');
var formData = {
'name': 'Bob Smith',
'email': 'bob#example.com',
'resume': resumeBlob
};
// Because payload is a JavaScript object, it is interpreted as
// as form data. (No need to specify contentType; it automatically
// defaults to either 'application/x-www-form-urlencoded'
// or 'multipart/form-data')
var options = {
'method' : 'post',
'payload' : formData
};
UrlFetchApp.fetch('https://httpbin.org/post', options);
}
Check the doc
Try something like this in your app script:
var POST_URL = "enter your webhook URL";
function onSubmit(e) {
var form = FormApp.getActiveForm();
var allResponses = form.getResponses();
var latestResponse = allResponses[allResponses.length - 1];
var response = latestResponse.getItemResponses();
var payload = {};
for (var i = 0; i < response.length; i++) {
var question = response[i].getItem().getTitle();
var answer = response[i].getResponse();
payload[question] = answer;
}
var options = {
"method": "post",
"contentType": "application/json",
"payload": JSON.stringify(payload)
};
UrlFetchApp.fetch(POST_URL, options);
};
Be sure to replace the POST_URL variable with your webhook, you can use requestcatcher.com to test this out.
Add a trigger to the script by clicking "Triggers" in the side menu
Open the menu (top-right dots)
Click in Script Editor
Paste the above code (changing the POST_URL)
Click in the clock icon (left-side menu), which means Triggers.
On the right-bottom corner, click in the blue Add trigger button (a form will show as the image below).
It should show onSubmit under Choose which function to run.
Make sure Select event type is set as On form submit.
Click Save button.
After that, submit your form and watch for the request to come in.
This is pretty straightforward with Google Scripts.
Just create a new project bound to your spreadsheet and create 2 elements:
A function that will contain all relevant data to make the call (see docs for making a HTTP request from Google Apps Script)
A trigger linked to the spreadsheet. You can set it to run each time an edit occurs or form is submitted
VoilĂ , your sheet will call whatever endpoint you wish on submission. You can even parse the spreadsheet to return that data to your endpoint

Set email body content in google appmaker

I want to send an email with a content related to my data such as in following piece of code I found on Datasource script of Google AppMaker Project Tracker template. But I don't understand how it works. How that data.modifiedBy reflect to the record in my datasource?
Any help from the floors? Thanks ..
Look at the Notifications server side script in the template.
It has method notifyAboutItemChanges_ which is passing the data to this record.
function notifyAboutItemChanges_(changes) {
var settings = getAppSettingsRecord_()[0];
if (!settings.EnableEmailNotifications) {
return;
}
var data = {
appUrl: settings.AppUrl,
itemType: changes[0].Type,
itemKey: changes[0]._key,
itemName: changes[0].Name,
modifiedBy: changes[0].ModifiedBy,
changes: changes
};
// Email subject.
var subjectTemplate =
HtmlService.createTemplate(settings.NotificationEmailSubject);
}
This function is passing this data to your settings record.
So no magic here :) You need to pass the data to your record which will be replaced at run time with the values.
For more details on Email refer this sample app.

Where is spreadsheet with data

Is it possible to access the Google drive table as which contains the data for an app maker model? I mean - is it possible to open it as a Spreadsheet?
Yes. You can use a spreadsheet as a datasource. I used a simple spreadsheet just to collect 3 items. I was playing with the Email Sender tutorial and I wanted to collect a list of the emails I'd already sent. I created the fields and went into the datasources tab and added this code to the queryRecords() function.
var ss=SpreadsheetApp.openById('id');
var sh=ss.getSheetByName('RecentEmails');
var rg=sh.getRange(2,1,sh.getLastRow(),sh.getLastColumn());
var vA=rg.getValues();
var reRecords=[];
for(var i=0;i<vA.length;i++){
var reRecord=app.models.RecentEmails.newRecord();
reRecord.Recipient=vA[i][0];
reRecord.Date=vA[i][1].toString();
reRecord.Message=vA[i][2];
reRecords.push(reRecord);
}
return reRecords;
The above function loads the datasource.
Then I connected a table upto the datasource and the data will update whenever the page is loaded.
I loaded the data into the table with a function like this:
function archiveSentEmails(to,when,what)
{
var ss=SpreadsheetApp.openById('id');
var sh=ss.getSheetByName('RecentEmails');
sh.appendRow([to,when,what]);
}
It gets placed inside the serverside script where the MailApp.sendMail function is located.
When you push the Send EMail button it calls this clientside function which calls the serverside function via google.script.run.
function sendMessage(to, subject, msg){
var status = app.pages.Email.descendants.EmailStatus;
google.script.run
.withFailureHandler(function(error) {
// An error occurred, so display an error message.
status.text = error.message;
})
.withSuccessHandler(function(result) {
// Report that the email was sent.
status.text = 'Email sent...';
clearEmailForm();
loadDebugElements();
app.datasources.RecentEmails.load();//this lines refreshes the widgets attached to the datasource
})
.sendEmailMessage(to, subject, msg);
}
and I placed the command app.datasources.RecentEmails.load in the withSuccessHandler so that the table of recent emails will update everytime it sends an email and that way you don't have to have a button to initiate updating the table after every email is sent.

Refreshing page with meteor iron router

Here is the problem :
I am currently programming a chatapp based on what i found on github (https://github.com/sasikanth513/chatDemo)
I am refactoring it with iron-router.
When I go to the page (clicking on the link) I get an existing chatroom (that's what I want)
When I refresh the page (F5) I get a new created chatroom ! (what i want is getting the existing chatroom ...)
Here is the code in ironrouter :
Router.route('/chatroom', {
name: 'chatroom',
data: function() {
var currentId = Session.get('currentId'); //id of the other person
var res=ChatRooms.findOne({chatIds:{$all:[currentId,Meteor.userId()]}});
console.log(res);
if(res){
Session.set("roomid",res._id);
}
else{
var newRoom= ChatRooms.insert({chatIds:[currentId, Meteor.userId()],messages:[]});
Session.set('roomid',newRoom);
}
}
});
You can find my github repo with the whole project : https://github.com/balibou/textr
Thanx a lot !
Your route data depends on Session variables which will be erased after a refresh. You have a few options but the easiest would be to put the room id directly into the route: '/chatroom/:_id'. Then you can use this.params._id to fetch the appropriate ChatRooms document. Note that you could still keep '/chatroom' for cases where the room doesn't exist, however you'd need to redirect to '/chatroom/:_id' after the insert.
In meteor, the Session object is empty when the client starts, and loading/refreshing the page via HTTP "restarts" the client. To deal with this issue, you could persist the user's correspondent id in a Meteor.user attribute, so that you could easily do:
Router.route('/chatroom', {
name: 'chatroom',
data: function() {
var currentId = Meteor.user().profile.correspondentId;
var res=ChatRooms.findOne({chatIds:{$all:[currentId,Meteor.userId()]}});
console.log(res);
if(res){
Session.set("roomid",res._id);
}
else{
var newRoom= ChatRooms.insert({chatIds:[currentId, Meteor.userId()],messages:[]});
Session.set('roomid',newRoom);
}
}
});
This would work, with the proper permissions, but I would recommend not allowing the direct update of that value on the client (I don't know if you want users to be able to override their correspondentId). So if you want to secure this process, replace all that code with a server method call, where your updates are safer.
Another (and more common case) solution was given by David Weldon, if you don't mind having ids in your URL (and therefore not a single url)

Resources