[4.1] Ad-hoc single asset indexing #11998
-
I have a piece of custom module code (from Craft 3 that I am looking to update for Craft 4) that produces an image thumbnail from a PDF, sets the resulting thumbnail as an asset in a specific volume / folder and then asks the In the Craft 3 days, this was done like this: $vol = $asset->getVolume();
$path = $asset->getFolder()->path . $new_filename;
$indexed_asset = Craft::$app->getAssetIndexer()->indexFile($vol, $path); But since Craft 4, a $indexed_asset = Craft::$app->getAssetIndexer()->indexFile($vol, $path, $sessionId); I can roughly see how a I would love an ad-hoc way of (re)indexing a single asset without the need for the Does anyone have any ideas how to do this, or can we please have a new method on the |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
I’d recommend you just stick to the normal use Craft;
use craft\elements\Asset;
use craft\helpers\Assets;
$tempPath = '/path/to/new/thumb.png';
$volumeHandle = 'volumeHandle';
$folderPath = 'the/folder/path';
$filename = Assets::prepareAssetName($tempPath);
$volume = Craft::$app->volumes->getVolumeByHandle($volumeHandle);
$folder = Craft::$app->assets->ensureFolderByFullPathAndVolume($folderPath, $volume);
$asset = Asset::find()
->volume($volume)
->folderId($folder->id)
->one();
if ($asset) {
// Replace the existing thumb with the new one
Craft::$app->assets->replaceAssetFile($asset, $tempPath, $filename);
} else {
// Save as a new asset
$asset = new Asset();
$asset->tempFilePath = $tempPath;
$asset->setFilename($filename);
$asset->newFolderId = $folder->id;
$asset->setVolumeId($volume->id);
$asset->setScenario(Asset::SCENARIO_CREATE);
if (!Craft::$app->elements->saveElement($asset)) {
// didn't work. check $asset->getErrors().
} |
Beta Was this translation helpful? Give feedback.
I’d recommend you just stick to the normal
assets
service API. Any changes made with that will automatically be indexed.