1

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
  • 1
    This is actually a bug in Craft. Fixed as of 3.5.8 or 3.4.30. Commented Sep 7, 2020 at 14:34

1 Answer 1

1

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();
    }
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.