How to set default date to today in google form? - forms

I need to set in a google form response the today date (Not hardcoded) when submited
I'm accesing the form, adding a date question, setting the title and the help text, but nothing more
function myFunction() {
var myForm = FormApp.openById("MyFormID");
var formDate = myForm.addDateItem();
formDate.setTitle('Ciclo');
formDate.setHelpText('Ciclo de registro');
//This is doing nothing at all
//var formDateResponse = formDate.createResponse(new Date());
}
Im only getting the date question unfilled

A FormResponse has a getTimestamp() function built into it.
If you are using an onSubmit Trigger you can get it by:
function onSubmit(e){
var response = e.response;
var timestamp = response.getTimestamp(); //Date Object!
}
It's important to note that if you have an onSubmit Trigger in Google Sheets it does not provide the e.response FormResponse object, but instead a values array, namedValues array, or range object.

Related

Conditional formatting for dates

I'm trying to come up with a simple conditional format formula for highlighting cells that have a date that is greater than three months older than today's date. It seems though that the "Date is before" option only gives a few options, none of them seem to allow what I'm looking for. Is there a custom formula that could accomplish this?
Edit: attaching a snip of the column in question:
Formula :
=DAYS(now(),B2)>90
Go to the custom formula in the conditional formating rules and use this:
=DATEDIF(A1,TODAY(),"D")<90
try:
=1*C2>DATE(YEAR(TODAY()), MONTH(TODAY())+3, DAY(TODAY()))
also make sure you have valid dates and not plain text dates. you can test this with ISDATE formula
You can use Apps Script and a Custom Menu in order to solve your issue with setting the color in the cell depending on the date. Go to Tools->Script Editor and paste this code:
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Custom Menu')
.addItem('Check Difference', 'dateDifference')
.addToUi();
}
function dateDifference(){
var sheet = SpreadsheetApp.getActiveSheet().getActiveRange(); // Get the selected range on the sheet
var dates = sheet.getValues(); // Get the values in the selected range
var oneDay = 1000*60*60*24;
var row = 1;
var re = /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/; // This will help you to check if it's really a date
dates.forEach(function(el){ // Iterate over each value
if(typeof el[0] == 'object'){ // Check if it's really a date
var gmtZone = el[0].toString().split(" ")[4].split(":")[0]; // Take the date's GMT
var dateFormatted = Utilities.formatDate(el[0], gmtZone, "dd/MM/yyyy"); // Format the date
if(re.test(dateFormatted)){ // Test if it's the right format
// This part will calculate the difference between the current date and the future date
var futureDateMs = new Date(el[0]);
var todayDateMs = (new Date()).getTime();
var differenceInMs = futureDateMs - todayDateMs;
var differenceInDays = Math.round(differenceInMs/oneDay);
if(differenceInDays >= 91.2501){ // Test if the difference it's greater to 91.2501 days (3 motnhs)
sheet.getCell(row, 1).setBackground("#00FF00"); // Set the color to the cell
}
row++;
}
}
});
Save it by clicking on File->Save.
Then you can select a range in a column and click on Custom Menu->Check Difference as you can see in the next image:
As you can see, you will get the desired result:
Notice
It's really important to be careful with what you consider to be a "month", I mean how many days you are going to take into consideration. In my code, I took Google's suggestion of 1 = 30.4167.
Docs
These are other Docs I read to be able to help you:
Utilities.formatDate()
Working with Dates and Times.
I hope this approach can help you.

How to send a conditional email based on the value of a cell from a form response?

I have a formula that calculates a number based on the response from a google form. Depending on what this number I want to send an email using details from the from as well as a pre typed email in another cell.
In Col1 is a time stamp, in col14 is an employee start date. My formula in Col33 works out how many days they have been employed at the time of submitting the form.
I want to send an email to the person if the number of days is less than 182.
I have an email pre typed out and can place this anywhere. At the moment I have it in all cells in col36. The email address will be in column32.
I have tried a number of different codes and none of them are sending the email no matter what the trigger I have set up is. I have very basic knowledge on apps script so my current code might be completely wrong, but it should show roughly what I'm getting at.
function sendEmail() {
var values = SpreadsheetApp.getActiveSheet().getDataRange().getValues()
for (i in values.length) {
var data = values[i][33];
var emailAddress = values[i][32];
var message = values[i][36];
if (data < 182); {
MailApp.sendEmail(emailAddress, "Flexible Working Request", message);
}
}
}
The current results have just been deleting the data in col33, Col34 & Col36 on the new form response row only.
Sorry if this question has been answered elsewhere, any other answer I found to similar issues I could not get to work.
I got someone who is much better at google apps script at work to give me a hand
It is to do with google forms pushing down formulas to the side
So we had to move the formula calculating the number of days to another sheet and then used this formula which worked
function sendEmailv2() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Form responses
1');
var scrip = Session.getScriptTimeZone();
var date = sheet.getRange(sheet.getLastRow(),14).getValue();
var sub = sheet.getRange(sheet.getLastRow(),1).getValue();
Logger.log(date);
var fortmat = Utilities.formatDate(new Date(date), scrip, "dd/MM/yyyy");
var Subfortmat = Utilities.formatDate(new Date(sub), scrip, "dd/MM/yyyy");
var emailAddress = sheet.getRange(sheet.getLastRow(),32).getValue();
var sheet2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet4');
var message = sheet2.getRange(1,1).getValue();
var days = sheet2.getRange(sheet2.getLastRow(),2).getValue();
if (days<182){
MailApp.sendEmail(emailAddress, "Flexible Working Request", message,{noReply:true});
}
}
Thanks!
You don’t need to go over all the columns to get a single cell value, so there is no need for a for loop. You can do it directly with:
var sheet = SpreadsheetApp.getActiveSheet().getSheets[0];
var cell = ["A33"];
var days_value = sheet.getRange(cell).getValue();
Then you can just make an if condition to send the email:
if (days_value < 182){
MailApp.sendEmail(emailAddress, "Flexible Working Request", message);
}
Hope this helps

Prefill current date in Google Form with Google Apps Script

I have a Google Form to a spreadsheet and I need a date field pre-filled with the current date.
Something like an "onOpen trigger", which updates the date field or a date field with now().
Is this possible in Google Apps Script?
In your case, some of the points of using the Form remain unclear. Suppose that you have the ability to edit a link to the Form or your users agree to add the bookmarklet to their browser.
Common code
let id='1FAIpQLScx-1H1moCzBfkTEOZnVgBScbJeHZ4YE5E6IY2mNZvMuVcOXA';
window.open(
`https://docs.google.com/forms/d/e/${id}/viewform?usp=pp_url&entry.1000000=`+
(new Date()).toISOString().split('T')[0]
);
Bookmarklet
Just add the next string to the bookmarks bar
javascript:let id = '1FAIpQLScx-1H1moCzBfkTEOZnVgBScbJeHZ4YE5E6IY2mNZvMuVcOXA'; window.open(`https://docs.google.com/forms/d/e/${id}/viewform?usp=pp_url&entry.1000000=` + (new Date()).toISOString().split('T')[0]);
I put a static HTML page on S3 with a few line of Javascript for redirecting. See https://jsfiddle.net/barryku/3etd8qf0/
var formId = "1FAIpQLSc_acGSzp2VeJIyG0tNJwqcNdUPOweLROGenY0Fe56I635VGQ";
var dateField = "entry.1608430301";
var formsUrl = "https://docs.google.com/forms/d/e/"+ formId + "/viewform?usp=pp_url&" + dateField + "=$$today&entry.747437339=Yes";
var today = new Date();
var redirectUrl = formsUrl.replace("$$today", new Date(today.getTime() - (today.getTimezoneOffset() * 60000)).toISOString().split('T')[0]);
window.location.replace(redirectUrl);

How to return a normal javascript date object?

Is it possible to return a javascript date object from this? I have an text input field with the calendar and want to return a standard date object from it's value... Is this possible?
Is this what you are looking for?
var date = '2016-06-12'; // Can be document.getElementById('myField').value that points to your date field.
var date_parts = date.split('-');
var date_obj = new Date(date_parts[0],date_parts[1],date_parts[2]);
console.log(date_obj);
You can also simply use
new Date(document.getElementById('myField').value)
and see if it works. The date function is smart enough to parse based on browser's locale. This should work for time as well. Eg. new Date('2016-06-12 04:15:30')

Kendo date picker custom date format

I have an application which allows the customer to set the date format by setting screen.
I change the current thread culture date format, and set the date and parsing format in the kendo date picker.
DateTimeFormatInfo datetimeFormat = new DateTimeFormatInfo();
datetimeFormat.FullDateTimePattern = "MM.dd.yyyy hh:mm tt"; //(set static for testing)
Thread.CurrentThread.CurrentCulture.DateTimeFormat = datetimeFormat;
My problem is when I change the date format a client side validation error returns says that the field should be a date.
I tried to set custom rule in the kendo validator but that not helps me because when I change the date this rule not fired.
$("myForm").kendoValidator(
{
rules: {
dateValidation: function(input)
{
if (input.is("[data-role=datepicker]")) {
// My code should be here
}
return true;
}
}});
Anyone can help me to solve this issue.
There is no need to add custom rule you need to set the custom format in the kendo validator as following:
kendo.ui.validator.rules.mvcdate = function (input) {
return input.val() === "" || kendo.parseDate(input.val(), "dd/MM/yyyy") !== null;
}
This code will return true (valid) if the date picker has a value and the value is in the correct format (dd/MM/yyyy in the above)