This is Aaron Rester's blog:

Field Notes from the Digital Prairie

Wednesday, March 26, 2014

Solving a Drupal Timestamp Problem

This is a post that will not be of interest to 99.9% of the people who see it, but since I've spent the last two months or so trying to remember how I solved the problem the first time I faced it, I feel the need to put it down in writing.

The Problem (Part 1): Drupal's webform module makes it possible for submitters to edit their previous submissions, but while it tracks when the original submission is made, it does not do so for subsequent edits.

The Solution (Part 1): I created a hidden field ['edit-submitted-timestamp'] in the form, and added a bit of javascript in a block at the bottom of the form [document.getElementById('edit-submitted-timestamp').value = Date()] so that every time the form was edited, the browser would insert the current date in the hidden field.

The Problem (Part 2): Just using "Date" meant that browsers would insert the date in an unwieldy format (usually something along the lines of "Wed, Mar 19 2014 09:24 GMT -0500 (Central Daylight Time)"), and worse, did so inconsistently (since the format seems to depend on the user's browser, operating system, etc.)

The Solution (Part 2): A bit of tweaking to the javascript was necessary to ensure a consistent and sortable date was being inserted. The final script I wound up with is:

<script>
function addDate(){
date = new Date();
var month = date.getMonth()+1;
var day = date.getDate();
var year = date.getFullYear();
var hours = date.getHours();
var minutes = date.getMinutes();

document.getElementById('edit-submitted-timestamp').value = year + '-' + month + '-' + day + ';' + hours + ':' + minutes;

}
window.onload = addDate;
</script>

UPDATE: This turned out not to be the best format for sortability (no padding 0s for numbers under 9), so here is the updated Javascript:

<script>
function addDate(){
date = new Date();
var month = date.getMonth()+1
if(month <= 9)
    month = '0'+month;
var day = date.getDate();
if(day <= 9)
    day = '0'+day;
var year = date.getFullYear();
var hours = date.getHours();
if(hours <= 9)
    hours = '0'+hours;
var minutes = date.getMinutes();
if(minutes<= 9)
    hours = '0'+minutes;

document.getElementById('edit-submitted-timestamp').value = year + '-' + month + '-' + day + ';' + hours + ':' + minutes;

}
window.onload = addDate;
</script>

No comments: