I'm trying to enforce unique values based on 3 columns. i'm trying for SharePoint online.
Lookup column
Choice
Calendar (only date)
I tried with below code, able to retrieve the existing values from the list but Calendar date selection is getting failed. not able to figure out what can be done. can anyone help on this,
<script type="text/javascript" src="/sites/Mysite/SiteAssets/jquery.min.js"></script><script type="text/javascript">
//variable to hold Ajax result
var dataResults;
var call = $.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/GetByTitle('Mylist')/Items?" + "$select=Title,Engagement,Period",
//Title is a lookup column
type: "GET",
dataType: "json",
async:false,
headers: {
Accept: "application/json;odata=verbose"
},
success: function(data) {
dataResults = data.d;
}
});
function PeriodValue(fullDate){
var orderDateString = "2016-10-19T22:00.00Z"; //UTC datetime value from REST response
var orderDate = new Date(orderDateString);
var value= TimeZoneUtilities.utcToLocalTime(_spPageContextInfo.webAbsoluteUrl,orderDate);
alert(value);
var dateValue=null,twoDigitDate=null,twoDigitMonth=null,twoDigitYear,currentDate=null;
dateValue = fullDate.split("T")[0];
twoDigitDate = dateValue.split("-")[2];
twoDigitMonth = dateValue.split("-")[1];
twoDigitYear = dateValue.split("-")[0];
currentDate = twoDigitDate + "/" + twoDigitMonth + "/" + twoDigitYear;
return currentDate;
}
//function to compare user input and existing data
function PreSaveAction(){
var ClientName = document.querySelector('[title="Client Name Required Field"]');
var engagement = document.querySelector('[title="Engagement Required Field"]');
var period = document.querySelector('[title="Period Required Field"]');
ClientName=ClientName.options[ClientName.selectedIndex].text;
engagement=engagement.options[engagement.selectedIndex].text;
period=period.value;
var c = null;
$.each(dataResults, function(i, item){
c = true;
$.each(item, function(i, dt){
console.log(dt.Engagement + ' ' + dt.Period + ' ' +dt.Title);
if (dt.Engagement == engagement && dt.Period == period && dt.Title==ClientName){
c = false;
alert("Already exist");
return c;
}
});
});
return c;
}
</script>
Related
Here is the GS code which will fetch the email id and and subject and the table.
var EMAIL_DRAFTED = "EMAIL DRAFTED";
function draftMyEmails() {
var sheet = SpreadsheetApp.getActiveSheet(); // Use data from the active sheet
var startRow = 2; // First row of data to process
var numRows = sheet.getLastRow() - 1; // Number of rows to process
var lastColumn = sheet.getLastColumn(); // Last column
var dataRange = sheet.getRange(startRow, 1, numRows, lastColumn) // Fetch the data range of the active sheet
var data = dataRange.getValues(); // Fetch values for each row in the range
// Work through each row in the spreadsheet
for (var i = 0; i < data.length; ++i) {
var row = data[i];
// Assign each row a variable
var clientName = row[0]; // Col A: Client name
var clientEmail = row[1]; // Col B: Client email
var sub = row[2]; // Col C: subject
var body = row[3]; // Col D: emailbody
var emailStatus = row[lastColumn - 1]; // Col E: Email Status
var range = sheet.getRange(2, 6, 1, 5).getDataRegion(SpreadsheetApp.Dimension.ROWS);
var values = range.getValues();
// Prevent from drafing duplicates and from drafting emails without a recipient
if (emailStatus !== EMAIL_DRAFTED && clientEmail) {
// Build the email message
var emailBody = '<p>Hi ' + clientName + ',<p>';
//emailBody += '<p>We are pleased to match you with your vegetable: <strong>' + veg + '</strong><p>';
//emailBody += '<h2>About ' + veg + '</h2>';
emailBody += '<p>' + values + '</p>';
// emailBody += '<p>' + clientName + ', we hope that you and ' + veg + ' have a wonderful relationship.<p>';
// Create the email draft
GmailApp.createDraft(
clientEmail, // Recipient
sub, // Subject
'', // Body (plain text)
{
htmlBody: emailBody // Options: Body (HTML)
}
);
sheet.getRange(startRow + i, lastColumn).setValue(EMAIL_DRAFTED); // Update the last column with "EMAIL_DRAFTED"
SpreadsheetApp.flush(); // Make sure the last cell is updated right away
}
}
}
What i am getting is by using this code:
Body
7 & 8,9 & 10,IOS,5 & 6,,a,b,c,d,,1,2,3,4,,1,2,3,4,,1,2,3,4,,1,2,3,4,,1,2,3,4,,1,2,3,4,,1,2,3,4,,1,2,3,4,
expected result should be like this.
This how the google sheet looks like.
Try this:
function draftMyEmails() {
var sh=SpreadsheetApp.getActiveSheet();
var startRow=2;
var lastCol=sh.getLastColumn();
var dataRange=sh.getRange(startRow,1,sh.getLastRow()-startRow+1,lastCol);
var data=dataRange.getValues();
for (var i=0;i<data.length;i++) {
var row=data[i];
var clientName=row[0];
var clientEmail=row[1];
var sub=row[2];
var body=row[3];
var emailStatus=row[lastCol-1];
var range=sh.getRange(2, 6, 1, 5).getDataRegion(SpreadsheetApp.Dimension.ROWS);
var values=range.getValues();
if (emailStatus!="EMAIL DRAFTED" && clientEmail) {
var emailBody= Utilities.formatString('<p>Hi %s </p>,<br />',clientName);
emailBody+='<style>td{border:1px solid black;)</style><table>';
values.forEach(function(r,j){
emailbody+='<tr>
r.foreach(function(c,k){
emailBody+=Utilities.formatString('<td>%s</td>',c);
});
emailBody+='</tr>';
});
emailBody+='</table>';
GmailApp.createDraft(clientEmail,sub,'',{htmlBody: emailBody});
sh.getRange(startRow + i, lastColumn).setValue("EMAIL_DRAFTED");
}
}
}
Please provide me with an image of your spreadsheet so I can see what your table looks like and I'll debug the table area for you or you can do it yourself.
This is a follow up to my last question How to loop an onEdit function to send emails from multiple rows in Google Sheets? Now to finish this project, I need to be able to send SMS based on a cell's contents.
I'm using Twilio, and the code from their example https://www.twilio.com/blog/2016/02/send-sms-from-a-google-spreadsheet.html allows me to send texts to ALL numbers in the spreadsheet when I run the function. There is some help at this question Send SMS from Google Sheet however since I'm using Twilio instead of carrier emails I'm still getting stuck.
As of right now, this first block of code allows all texts to be send at the same time I run the function (sendSMS contains all API info and is not shown):
function sendAll() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('HIVE');
var startRow = 2;
var width = 16;
var numRows = sheet.getLastRow() - 1;
var dataRange = sheet.getRange(startRow, 2, numRows, width)
var data = dataRange.getValues();
for (i in data) {
var row = data[i];
try {
response_data = sendSms(row[4], row[12]);
status = "sent";
} catch(err) {
Logger.log(err);
status = "error- Not Sent";
}
sheet.getRange(startRow + Number(i), 2).setValue(status);
}
}
I tried replicating the pattern used to send the emails in my last question by inserting:
if (sheet.getSheetName() == sheetname && range.columnStart == 1) {
var data = sheet.getRange(range.getRow(), 1, 1, 21).getValues()[0];
var object = {
to: data[5] // Column "E"
if (e.value == "Appt. Set (send text)") {
object.subject = "Appt. Confirmation";
object.body = apptText; // variable containing body text
if (object.subject) sendSms(object);
I've updated the code to where it will trigger onEdit, but only for the first IF statement:
function onEditText(e) {
var sheetname = "HIVE";
var sheet = e.range.getSheet();
var range = e.range;
var timezone = "GMT-5";
var timestamp_format = "MMMM dd 'at' HH:mm";
var date = Utilities.formatDate(new Date(), timezone, timestamp_format);
var twilioNumber = 1234567890;
if (sheet.getSheetName() == sheetname && range.columnStart == 1) {
var data = sheet.getRange(range.getRow(), 1, 1, 21).getValues()[0];
var object = {
to: data[5] // Column "E"
};
var apptText = "Hey " + data[9] + "! 😊\n\nThanks...;
var leadText = "Hey " + data[9] + "! 👋\n\nThanks so...;
var followText = "Hey " + data[9] + "! 😊 \n\nAre...;
var confirmText = "Hey " + data[9] + "! ⏰ \n\nYour appointment...;
if (e.value == "Appt. Set (send text)") {
object.subject = "Appt. Confirmation";
object.body = apptText; //
SpreadsheetApp.getActiveSheet().getRange(range.getRow(),2,1,1).setValue('Appt. Set Text sent on ' + date);
} else if (e.value == "Lead (send 1st text)") {
object.subject = "Lead";
object.body = leadText; //
SpreadsheetApp.getActiveSheet().getRange(range.getRow(),2,1,1).setValue('Lead 1st Text sent on ' + date);
} else if (e.value == "3rd Text") {
object.subject = "Follow Up";
object.body = followText;
SpreadsheetApp.getActiveSheet().getRange(range.getRow(),2,1,1).setValue('3rd Text sent on ' + date);
}else if (e.value == "Day of Confirm (send text)") {
object.subject = "Can't wait to meet you!";
object.body = confirmText;
SpreadsheetApp.getActiveSheet().getRange(range.getRow(),2,1,1).setValue('Confirmation Text sent on ' + date);
}
if (object.subject) sendSms(data[5], twilioNumber);
}
}
I have a geoLocation app for a Firefox OS device (ZTE Open v1.1), that broadcasts to a web server its location details.
However, my code doesn't run if I minimise the app and turn the screen off.
I thought adding the following requestWakeLocks to the code would sort the problem, but it doesn't seem to help:
var lock = window.navigator.requestWakeLock('gps');
var lock = window.navigator.requestWakeLock('wifi');
Do you have any idea what I am doing wrong?
Code:
function init() {
document.addEventListener("DOMContentLoaded", watchPosition, false); // to test on web browser
//document.addEventListener("deviceready", watchPosition, false); // deviceready is a cordova event
}
/* ---------------------------------- Local Variables ---------------------------------- */
var checkPeriodically;
var watchPositionOutput = document.getElementById('watchPositionOutput');
var ajaxVars; // HTTP POST data values
/* ---------------------------------- Local Functions ---------------------------------- */
function watchPosition() {
var lock = window.navigator.requestWakeLock('gps'); // FireFox-OS only - keeps the gps active when screen is off
var lock = window.navigator.requestWakeLock('wifi');
checkPeriodically = setInterval(checkTime, 10000);
var watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);
var options = {
enableHighAccuracy: true,
}
function onSuccess(position) {
ajaxVars =
"lt=" + position.coords.latitude +
"&lg=" + position.coords.longitude +
"&ac=" + position.coords.accuracy +
"&sp=" + position.coords.speed +
"&ts=" + position.timestamp +
"&sec=SEC_TOKEN";
var dt = new Date(position.timestamp);
date_time =
dt.getFullYear() + '-' +
(dt.getMonth() + 1) + '-' +
dt.getDate() + ' ' +
dt.getHours() + ':' +
dt.getMinutes() + ':' +
dt.getSeconds();
watchPositionOutput.innerHTML =
'Latitude: ' + position.coords.latitude + '<br>' +
'Longitude: ' + position.coords.longitude + '<br>' +
'Accuracy: ' + position.coords.accuracy + '<br>' +
'Speed: ' + position.coords.speed + '<br>' +
'Timestamp: ' + date_time + '<br>';
}
function onError(error) {
watchPositionOutput.innerHTML = 'code: ' + error.code + '<br>' +'message: ' + error.message + '<br>';
}
}
// update the server with location data
function ajax_post(postData){
// when there is no data in postData
if (typeof(postData) === 'undefined') { return false; } // exit the function
var req = new XMLHttpRequest(); // Create XMLHttpRequest object
var url = "http://example.com/locate-me/post.php";
//var url = "http://localhost/locate-me/post.php";
req.open("POST", url, true);
// Set content type header info for sending url encoded variables in the request
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
req.onreadystatechange = function() {
if(req.readyState == 4 && req.status == 200) {
var return_data = req.responseText; // return whatever php echos
var date_time = new Date(return_data * 1000); // php is currently returning the time (timestamp)
document.getElementById("status").innerHTML = "Server time: " + date_time;
}
}
// Send data to PHP, and wait for response to update the status div
req.send(postData); // execute the request
document.getElementById("status").innerHTML = "processing...";
}
// schedule to post the position data to a php script during certain times on certain days
function checkTime(){
// for example a day (day 0 == Sun) between 06:00 abd 23:45
var d = new Date();
var today = d.getDay();
var hms = d.getHours()+":"+d.getMinutes();
// mon - thurs
if( (today === 1 || today === 2 || today === 3 || today === 4) && hms > "10:23" && hms < "15:40") {
ajax_post(ajaxVars);
}
// friday
else if( today === 5 && hms > "13:00" && hms < "13:40") {
ajax_post(ajaxVars);
}
// testing: run all the time
else if( today < 7 ) {
ajax_post(ajaxVars);
}
else {
document.getElementById("status").innerHTML = "Data not scheduled to be posted to the server yet";
}
}
init();
Have you tried?
navigator.requestWakeLock('cpu');
If that still does not work, maybe you should follow the discussion in:
Firefox OS Background services
I'm having some trouble getting the value of a column in a saved search via SuiteScript. Below is my code:
function KW_AutoCloseOldRA() {
var search = nlapiLoadSearch('transaction', 'customsearchopen_ras', null, null);
var columns = search.getColumns();
for (i = 0; i < columns.length; i++) {
nlapiLogExecution('DEBUG', 'Column #' + i + ' is ' + columns[i].getName());
}
var results = search.runSearch();
if (results) {
results.forEachResult(getResults);
}
}
function getResults(res) {
var message = res.getValue('tranid');
nlapiLogExecution('DEBUG', 'Result ' + message);
return true;
}
The search produces two columns, and the name of those columns output as expected in the DEBUG entry (internalid is column 0 and tranid is column 1). When looping through the results however, res.getValue('tranid') is always null. I can't seem to find what I'm doing wrong here.
Try getting the value using the columns object and its index like this:
function KW_AutoCloseOldRA() {
var search = nlapiLoadSearch('transaction', 'customsearchopen_ras', null, null);
var columns = search.getColumns();
for (i = 0; i < columns.length; i++) {
nlapiLogExecution('DEBUG', 'Column #' + i + ' is ' + columns[i].getName());
}
var results = search.runSearch();
if (results) {
results.forEachResult(getResults);
}
}
function getResults(res) {
var cols = res.getAllColumns();
var message = res.getValue(cols[1]);
nlapiLogExecution('DEBUG', 'Result ' + message);
return true;
}
Passing few values through querystring, to testFn() in controller using below code. But in testFn, I am getting null values. When I keep alert on companyName, rdVal,etc. it is showing correct values. but those are not passing to controller. Please let me know what went wrong.
View:
#Html.ActionLink("Search", null, null, new { id = "lnkSearchMaster", #class = "btn btn-success", onclick = "return lnkgotoAction();" })
function lnkgotoAction() {
$('#grdSearchResults').show();
$('#searchdetails').show();
var rdVal = $("input[name = SearchType]:checked").attr("id");
if (rdVal == "CompanyList" || rdVal == "CompanyHistory" || rdVal == "ApplicationSatatus" || rdVal == "Certificates") {
$('#grdSearchResults').show();
var companyName = $('#companyname').val();
var status = $('#status').val();
var regNo = $('#registrationno').val();
var appRegNo = $('#applicationrefferenceno').val();
var url = '#Url.Content("~/")' + "Search/testFn?test='" + rdVal + "'&companyName='" + $('#companyname').val() +
"'®Num='" + $('#registrationno').val() + "'&appRegNum='" + $('#applicationrefferenceno').val() + "'";
alert(url);
}
$('#grdSearchResults').load(url + ' #grdSearchResults');
TempData.clear();
$('#grdSearchResults').show();
$('#searchdetails').show();
return false;
}
Controller:
public ActionResult testFn(string test, string companyName, string regNum, string appRegNum)
{}
Try as below, it will help you, also always take care the variable name passed to querystring must match controller action parameter names.
#Html.Raw(Url.Action("testFn", "Search"), new{ test= rdVal , companyName= companyName , regNum= regNo , appRegNum= appRegNo })