I've got a plugin that creates PDFs using Michael Rog’s Printmaker plugin. I'm able to successfully save these to a local folder and, using insertFileByLocalPath()
, add them to an asset source. Then, by finding the id
of the newly created asset, I can save the PDF to an entry.
My problem is that the asset field in the entry is setup to use dynamically-created subfolders, which I want to use to keep the assets for each entry separate from each other.
However, because the dynamically-created subfolder doesn’t exist until an asset is added to the entry, I am adding the PDF to the parent folder using insertFileByLocalPath()
.
I thought that when I added the asset to the entry and saved it, Craft would dynamically create the subfolder and move the asset into it, but it doesn’t do this. Instead, it just leaves the assets in the parent folder.
Here’s a simplified version of the code I’m using at the moment:
// Create PDF with $vars and $settings
$pdf = craft()->printmaker_pdf->pdfFromTemplate($template, $vars, $settings);
// Save PDF and get URL
$pdfUrl = $pdf->url();
// Get assets parent folder
$folder = craft()->assets->findFolder(array(
'name' => 'parent-folder'
));
...
$response = craft()->assets->insertFileByLocalPath(
$localFilePath,
$filename,
$folder->id,
AssetConflictResolution::KeepBoth
);
// Get id of pdf (newly created Asset)
$pdfId = craft()->assets->findFile(array(
'filename' => $settings['filename'].'.pdf'
))->id;
// Add PDF to entry
$entry->setContentFromPost(array(
'myAssetField' => array($pdfId)
));
if (craft()->entries->saveEntry($entry)) {
// Yay! PDF successfully saved to myAssetField
}
And here’s what the asset folder layout looks like:
parent-folder/new.pdf
Whereas what I want to achieve is this:
parent-folder/entry-slug/new.pdf
Where entry-slug
is a dynamically created subfolder for each entry.
Any ideas how I can achieve this, or if it is even possible?