Send Email Checkbox on Attendee Sublist user event script - javascript

In NetSuite I have a custom record for keeping track of our safety meetings, from the record, I have a user-event script, BEFORE SUBMIT FUNCTION, running to create an event record. On the Event record -> attendee sublist, I am able to add the attendees, but I am unable to set the sendemail checkbox. Any insight would be appreciated.
/*
user event script
before record submit
creates a new event record based off this safety meeting record.
*/
function createSafetyMeetingEventRec(type){
if(type=="create")
{
try
{
//get values from the safety meeting record
var altName = nlapiGetFieldValue('altname');
var message = nlapiGetFieldValue('custrecord53');
var local = nlapiGetFieldValue('custrecord56');
var date = nlapiGetFieldValue('custrecord51');
var time = nlapiGetFieldValue('custrecord52');
//name of the event record
var eventTitle = 'SM-' + altName;
//create the event record
var eventRec = nlapiCreateRecord('calendarevent');
//set the event record field values
eventRec.setFieldValue('title', eventTitle);
//script search for the Safety Committee group members in netsuite
var entitygroupSearch = nlapiSearchRecord("entitygroup",null,
[
["internalid","anyof","120147"]
],
[
new nlobjSearchColumn("entityid","groupMember",null),
new nlobjSearchColumn("internalid","groupMember",null)
]
);
//get who created the event, this user is automatically on the attendee list, and cannot be added again.
var eventUserSet = eventRec.getLineItemValue('attendee', 'attendee', 1);
for(var i = 0; i < entitygroupSearch.length; i++){
var newAt = eventRec.getLineItemCount('attendee') + 1;
var intIDuser = entitygroupSearch[i].getValue("internalid","groupMember",null);
if(intIDuser != eventUserSet){
eventRec.setLineItemValue('attendee', 'sendemail', newAt, 'T');
eventRec.setLineItemValue('attendee', 'attendee', newAt, intIDuser);
}else{
continue;
}
}
//set the resource calendar to Service Calendar, 3 is the internal id of the service calendar resource
var newAtResource = eventRec.getLineItemCount('resource') + 1;
eventRec.setLineItemValue('resource', 'resource', newAtResource, '3');
var eventId = nlapiSubmitRecord(eventRec, true);
}catch(err)
{
nlapiLogExecution("error","Error Creating Event Record From Safety Record ","Details: " + err.message);
}
}//end if
}

I think you also need
eventRec.setFieldValue('sendemail', 'T');
before the submit

Related

How to make sure that the PDF attached to the auto email is to the newest information?

This is the flow I created through Google Apps Script.
Someone writes their information in google form
The information is stored into spreadsheet
Invoice is created within spreadsheet with the newest information received
The invoice is turned into PDF format automatically
The newest invoice is attached to the auto sending email
The person receives an auto-email with the invoice attached as soon as they submit the google form
The problem is that, when someone submits the google form, they receive an invoice but what they receive is the invoice from the information one before. This then repeats. When someone submits, the information inside the invoice is from the person one before.
I am a starter at Google Script so I have no idea why this is happening.
This is the code I use to send the auto email. I have minimized the code.
function for_users2() {
var title = "【お問い合わせありがとうございます】";
var name = '名前';
var mail = 'メールアドレス';
var address = "";
var sheet = SpreadsheetApp.getActiveSheet();
var row = sheet.getLastRow();
var column = sheet.getLastColumn();
var range = sheet.getDataRange();
var TIMESTAMP_LABEL = 'タイムスタンプ';
for (var i = 1; i <= column; i++ ) {
var item = range.getCell(1, i).getValue();
var value = range.getCell(row, i).getValue();
if ( item === TIMESTAMP_LABEL ) {
item = 'お問い合わせ日時';
}
if ( item === 'お問い合わせ日時' ) {
value = Utilities.formatDate(value, 'Asia/Tokyo',"YYYY'年'MM'月'dd'日'HH'時'mm'分'ss'秒'");
}
body += "■"+item+"\n";
body += value + "\n\n";
if ( item === name ) {
body = value+" 様\n\n"+body;
}
if ( item === mail ) {
address = value;
}
}
body += body2;
var token = ScriptApp.getOAuthToken();
var pdf = UrlFetchApp.fetch("https://docs.google.com/spreadsheets/d/OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO/export?exportFormat=pdf&format=pdf&size=A4&portrait=true&fitw=true&sheetnames=false&printtitle=false&pagenumbers=false&gridlines=false&fzr=false&gid=00000000000", {headers: {'Authorization': 'Bearer ' + token}}).getBlob().setName('請求書');
GmailApp.sendEmail(
address,
title,
body,
{
attachments: [pdf],
name: 'Automatic Emailer Script'
}
);
}
There is no error. It's just that the invoice attached is from one previous customer.
Thank you to the people who have answered my question. Special thanks to Tanaike who have suggested a workaround where I was able to use as a starter to GAS.
As I used Utilities.sleep(5000), whenever someone submits google form, the invoice produced (PDF format) is updated to the newest info. Since the program I created isn't aimed for very heavy processes, it may be the reason why it worked perfectly fine.
If SpreasheetApp.flush() doesn't seem to be working then you should certainly move to the onFormSubmit - Installable Trigger.
Triggers - Form Submit
This way you can process the exact values from the form and use the same function you are using now. Instead of fetching the last row values, you can fetch the values from the form submission using this.
var name = e.namedValues['Name'][0]; var email = e.namedValues['Email'][0];

Automatically Filtering Items By Vendor During Creation of a Record

I have a set of scripts that I'm using that interact with each other. I use a client, user event and suitelet script to create a button that, when pressed, opens a popup with a list of items filtered by vendor.
It works fine when I'm in edit however when I use it while creating a record problems arise. Since the record to be created has no vendor or id I can't retrieve an item by vendor. What I'm trying to do is to have the Suitelet retrieve the info from the vendor field that is entered prior to it being saved. Therefore I can filter all the items by vendor and add the necessary items in one go. Is this possible? Am I able to access the info before it is submitted.
Below are the Client and Suitelet. The User Event is just a call to the suitelet so for the sake of brevity I left it out.
Client Script
function addItemButtonCallback(data){
nlapiSelectNewLineItem('item');
nlapiSetCurrentLineItemValue('item', 'item', data);
nlapiCommitLineItem('inventoryitem');
}
function addItemButton() {
var id = nlapiGetFieldValue('id');
if (id != "") {
var url = nlapiResolveURL('SUITELET', 'customscript_val', 'customdeploy1') + '&poId='+id;
window.open(url, '_blank', 'width=500,height=500');
}
}
Suitelet
function suitelet(request, response){
if(request.getMethod() == 'GET') {
var form = nlapiCreateForm('Add Item');
form.addSubmitButton('Submit');
var itemfield = form.addField('custpage_val', 'select', 'Item');
var id = request.getParameter('id');
var rec = nlapiLoadRecord('purchaseorder', id);
var vend = rec.getFieldValue('entity');
var search = nlapiSearchRecord(...search parameters...);
for (result in search){
if (search[result].getValue('vendor') == vend){
itemfield.addSelectOption(search[result].id, nlapiLookupField('inventoryitem', search[result].id, 'itemid'));
}
}
response.writePage(form);
} else {
var data = request.getParameter('custpage_item');
response.write('<html><body><script>window.opener.addItemButtonCallback("'+data+'"); window.close();</script></body></html>');
}
}
Use nlapiGetFieldValue('entity') on the clientscript and pass it to the Suitelet using a query parameter just like you are doing with poId (if you do this you might not even need poId after all + no need to load the record on the suitelet).
Also, you might want to optimize your code by running one search passing an array of itemids instead of calling nlapiLookupField for each item.
You might need to modify your beforeLoad so the entity is inserted dynamically when the button is pressed (I cant remember if clientscript button does this) . Something like this:
var suiteletURL = nlapiResolveURL('SUITELET', 'customscript_val', 'customdeploy1');
var script = "var entity = nlapiGetFieldValue('entity'); var url = '" + suiteletURL + "'&entityId=' + entity;window.open(url, '_blank', 'width=500,height=500')";
var button = form.addButton('custpage_addItemButton', 'Add Item', script);

How do I return a list from a custom object in Salesforce using javascript on a button?

I have a custom object in Salesforce called Website_Role__c. This object has a list of people associated with a store with different roles (Owner, Mentor, etc.).
Using JavaScript in a Salesforce button on Account:
The desired behavior is a user clicks the button and a dialog pops up with the list of people in the Website_Role__c for that Account. There would be a checkbox next to each person allowing the user to select them.
We are using eSign (formerly EchoSign). This button is a "Send with eSign" button that will be used to send an agreement to the list of people from Website_Role__c.
This is where I am at now:
/*My Attempt*/
{
!REQUIRESCRIPT("/soap/ajax/19.0/connection.js")
} //adds the proper code for inclusion of AJAX toolkit
var url = parent.location.href; //string for the URL of the current page
var records = {!GETRECORDIDS($ObjectType.Website_Role__c)
}; //grabs the Website Role records for the currently selected store
var updateRecords = []; //array for holding records that this code will ultimately update
if (records[0] == null) { //if the button was clicked but there was no record selected
alert("Please select at least one person to send to."); //alert the user that they didn't make a selection
} else { //otherwise, there was a person selected
for (var a = 0; a < records.length; a++) { //for all records
var update_Website_Role__c = new sforce.SObject("Website_Role__c"); //create a new sObject for storing updated record details
//This is where I get lost. Not sure if this is even the correct approach
}
//??
parent.location.href = url; //refresh the page
}
I would greatly appreciate any help you can provide.
Thank you
Try something like this:
{!REQUIRESCRIPT("/soap/ajax/29.0/connection.js")}
var query = sforce.connection.query("SELECT Owner__c, Mentor__c FROM Website_Role__c WHERE Account__c ='{!Account.Id}'");
var records = query.getArray("records");
alert("Owner is: " + records[0].Owner__c);
This assumes you have a reference field on your Website_Role object that points to the Account.
Check here for some more examples
https://developer.salesforce.com/docs/atlas.en-us.ajax.meta/ajax/sforce_api_ajax_more_samples.htm

lookup username using getactiveuser using Google Spreadsheet script

I have been trying to lookup username using activeuser. Only the first part works and the last part doesnt. My goal is to unhide the sheet based on the username of the active user (sheetname is based on username). Below is the code I am using.
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var menuEntries = [];
menuEntries.push({name: "Test getActiveUser/getEmail", functionName: "onTest"});
ss.addMenu("Rep Drowndown", menuEntries);
testGetEmail("onOpen");
}
function onTest() {
testGetEmail("menu function");
};
function testGetEmail(callerId) {
var userEmail = "";
var activeUser = Session.getActiveUser();
if (activeUser == null)
Browser.msgBox("Session.getActiveUser() returned null", "called by " + callerId, Browser.Buttons.OK);
else
userEmail = activeUser.getEmail();
if (userEmail == "")
Browser.msgBox("Your Email returned an empty string", "called by " + callerId, Browser.Buttons.OK);
else
var ss = SpreadsheetApp.getActiveSpreadsheet();
var lookup = Session.getActiveUser().getEmail();
var range = ss.getRange('$A$3:$B$8').getValues();
var lookupRange = [];
for (var i = 0; i < range.length; i++)
lookupRange.push(range[i][0]);
var index = lookupRange.indexOf(lookup);
if (index == -1) {
// implicit no-op
}
else {
var link = range[index][2]
var sheet = ss.getSheetByName(link);
sheet.showSheet();
};
}
You need to set up an installable trigger. This allows the script to run with authorization, whereas normally "onOpen()" is run as a Simple Trigger. Since Simple Triggers can't authorize as users, you'll never get an email address.
The simplest solution is to set testGetEmail() to be run on open. Do this within the Script Editor by choosing Resources > Current Project's Triggers in the menu. Then click "No triggers set up. Click here to add one now." Finally, set up your trigger:
Choose your function's name (testGetEmail) from the first dropdown under "Run."
Choose "From spreadsheet" in the second dropdown under "Events."
Choose "On Open" in the third dropdown.
Then test to be sure I didn't commit a typo :-)

Retrieving Start/End Time fields with SharePoint Client Object Model

I have some experience using the SharePoint Client Object Model to retrieve text fields and URLs/images from lists in SP 2013. I'm currently trying to do something similar with a calendar. I have been able to successfully retrieve Title and Location fields without any issue, but the Start and End Time fields I am not able to retrieve. I cannot figure out what exactly the issue is. Additionally, I can read Created and Modified with no problems. Here is the relevant code:
function retrieveListItemsCal() {
var clientContextCal = new SP.ClientContext.get_current();
var oListCal = clientContextCal.get_web().get_lists().getByTitle('Calendar');
var camlQueryCal = new SP.CamlQuery.createAllItemsQuery();
AllItemsCal = oListCal.getItems(camlQueryCal);
clientContextCal.load(AllItemsCal);
clientContextCal.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceededCal), Function.createDelegate(this, this.onQueryFailedCal));
}
function onQuerySucceededCal(sender, args) {
var listItemInfo = '';
var listItemEnumeratorCal = AllItemsCal.getEnumerator();
var htmlCal = '';
htmlCal+="<div id='CalHeader'>Upcoming Events</div>\
<div id='CalDivider'></div>\
<div id='CalContainer'>";
while(listItemEnumeratorCal.moveNext()) {
var oListItemCal = listItemEnumeratorCal.get_current();
/*htmlCal+="<div class='CalItem'>\
"oListItemCal.get_item('Start Time')"\
</div>";*/
alert(oListItemCal.get_item("Start Time").format("MMMM d, yyyy"));
}
htmlCal+="</div>";
$("#CalSpace").append(htmlCal);
}
function onQueryFailedCal(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
$(document).ready(function(){
SP.SOD.executeFunc("sp.js", "SP.ClientContext", retrieveListItemsCal);
});
And here is a screenshot of the list columns: http://i.imgur.com/8IK4KTO.png
I have resolved my issue. I ran the following PowerShell queries (found here http://techtrainingnotes.blogspot.com/2012/10/sharepointfinding-column-display-and.html):
$web = Get-SPWeb SiteUrl
$list = $web.Lists["Announcements"]
$list.fields | select Title, InternalName, Hidden, CanBeDeleted | sort title | ft -AutoSize
The internal names of the Start Time and End Time fields are EventDate and EndDate, respectively.

Categories