Now that Craft keeps track of which user uploaded an asset, I'm wondering if it's possible to set this information when an asset is uploaded via a frontend entry form. I have a form that includes an asset field and I would like the assets that are created to be "owned" by the current user. Can this be done via a hidden input, or would I need to hook into an asset event?
1 Answer
I ended up using an event to accomplish this:
use yii\base\Event;
use craft\elements\Asset;
use craft\events\AssetEvent;
Event::on(Asset::class, Asset::EVENT_BEFORE_HANDLE_FILE, function (AssetEvent $event) {
$asset = $event->sender;
// This does not work because it doesn't set the `uploaderId` property on the asset
// $asset->setUploader(Craft::$app->getUser()->getIdentity()); // Doesn't work, bug?
// So I just set the `uploaderId` directly
if (is_null($asset->uploaderId)) {
$asset->uploaderId = Craft::$app->getUser()->getId();
}
});