Question. I’d made an add-on for openingtimes. Now I’d like to add a field to track when it was last modified.
I was thinking in a more general add-on, that add a modification field to a field with a timestamp if that field is changed.
I’ve found the triggers overview , but where can I find the information passed.
I’d like to check if a field has been changed. How do I get access to the previous entry, because I currently get the current entry.
This code is based on the slug field that is generated based on title from @raffaelj
Time stamp is added correctly, but I only want to add it when the contents of the openinghours field are changed.
$col = "locations";
$field = "openinghours";
$trackModifications = function($name, &$entry, $isUpdate) use ($app, $col, $field, $slugName) { $entry[$field][modified] = time();
};
$app->on("collections.save.before.$col", $trackModifications);
You can check the original entry inside the collections.save.before
event. Something like this (not tested):
<?php
$app->on('collections.save.before'), function ($name, &$entry, $isUpdate) {
if (!$isUpdate) return;
$collection = 'locations';
$field = 'openinghours';
if ($name !== $collection) return;
if (!isset($entry[$field])) return;
$filter = [
'_id' => $entry['_id'];
];
$origEntry = $this->module('collections')->findOne($collection, $filter);
if ($entry[$field] !== $origEntry[$field]) {
$entry["{$field}_modified"] = time();
}
});
1 Like
Thanks @raffaelj for your helpful response. This did the track after some small bug fixes.
I’ve made a more generic add-on out of it, so it can be used for multiple collections and fields. It also distinguishes if a field is an object (so modified is added to that object) or just a value/array, so an additional field is added to the collection (thanks to that part of the example as well).