I am in the middle of building a QR code generation plugin that on saving a resource, creates a QR code based on the resource url and saves it to disk, and then if a file exists for that resource, it adds a tab to the resource that includes the QR code image.
My problem is that it seems to require TWO saves to get the correct url into the image generation snippet. When I change the alias and save, the script executes and generates the image, however it contains the previous url with the old alias. If I just save a second time, the image gets replaced with the updated url with the new alias.
Is this due to some caching of the modx resource? Anyone have any tips to resolve? Some of my code is below for reference:
$webroot = $_SERVER['DOCUMENT_ROOT'];
$eventName = $modx->event->name;
$relativePath = '/content/qrcodes/';
$filePath = $webroot . $relativePath;
$filePrefix = 'qrcode.';
$fileExt = '.png';
$fullQRFile = $filePath . $filePrefix . $id. $fileExt;
$timestamp = time();
if (!is_dir($filePath)) {
if (!mkdir($filePath, 0755, true)) {
$modx->log(modX::LOG_LEVEL_ERROR, "Failed to create directory: $filePath");
}
}
if (file_exists($fullQRFile)) {
$modx->regClientStartupHTMLBlock('
<script type="text/javascript">
MODx.on("ready", function() {
MODx.addTab("modx-resource-tabs", {
title: "QR Code",
id: "qrcode-resource-tab",
width: "98%",
items: [{
html: "<div id=\'qrcode-content\'></div>"
}],
listeners: {
activate: function(tab) {
loadQRCodeContent();
}
}
});
function loadQRCodeContent() {
var contentDiv = Ext.get("qrcode-content");
var relativePath = "' . $relativePath . '";
var filePrefix = "' . $filePrefix . '";
var id = "' . $id. '";
var fileExt = "' . $fileExt . '";
var timestamp = new Date().getTime();
contentDiv.update("<a href=\"" + relativePath + filePrefix + id + fileExt + "?timestamp=" + timestamp + "\" target=\"_blank\"><img width=\"512\" height=\"512\" src=\"" + relativePath + filePrefix + id + fileExt + "?timestamp=" + timestamp + "\"></a>" +
"<br><a href=\"" + relativePath + filePrefix + id + fileExt + "\" target=\"_blank\">Click here to download the PNG of this QR Code</a>");
}
loadQRCodeContent(); // Initial load of content
});
</script>');
}
switch ($eventName) {
case 'OnBeforeDocFormSave':
break;
case 'OnDocFormSave':
if ($mode == modSystemEvent::MODE_UPD && $id > 0 && $id !== '') {
$qrcodeParams = array(
'id' => $id
);
$qrcodeImage = $modx->runSnippet('qrCode', $qrcodeParams);
}
break;
}