Generate PDF only when entry has changed
Closed this issue · 1 comments
vaelu commented
Is there any way to trigger the PDF creation via PHP, for example in a EVENT_AFTER_SAFE
? I think of a method which allows passing in a template and returns the asset.
This would be awesome, because the PDF would only generate when a new entry is created or an entry has changed.
amici-infotech commented
Hey @vaelu It is possible yes. All you need to do is to create a custom plugin/module or use "modules/Module.php" file to add EVENT_AFTER_SAVE event. What I would do is:
- Enable Module.php class from config/app.php
- Go to Super PDF backend settings and set Default Behaviour to Ignore.
- Add this code in init method of Module.php (and classes at start of the file.)
NOTE: Use settings, variables and template source file what you have. Make sure you use resaveBehaviour
as "override" to generate your PDF.
use yii\base\Event;
use craft\elements\Entry;
use craft\events\ModelEvent;
use craft\helpers\ElementHelper;
use amici\SuperPdf\SuperPdf;
Event::on(Entry::class, Entry::EVENT_AFTER_SAVE, function (ModelEvent $event) {
if(
$event->sender->enabled &&
$event->sender->id &&
!ElementHelper::isDraft($event->sender) //&&
// $event->sender->section->id = MY_PDF_SECTION
) {
$template = "_invitaion";
$settings = [
'filename' => "My_PDF",
'dpi' => 150,
'resaveBehaviour' => 'override',
'type' => 'object',
];
$vars = [
'entry' => $event->sender,
];
$view = Craft::$app->getView();
$mode = $view->getTemplateMode();
$view->setTemplateMode($view::TEMPLATE_MODE_SITE);
$ret = SuperPdf::$plugin->pdf->template($template, $settings, $vars);
$view->setTemplateMode($mode);
if(! $ret->url) {
// ERROR. Return error or save log
}
}
});