Skip to content

Instantly share code, notes, and snippets.

@jacksleight
Last active November 20, 2021 20:01
Show Gist options
  • Save jacksleight/ee9506d6f16af7346f0848741de317cb to your computer and use it in GitHub Desktop.
Save jacksleight/ee9506d6f16af7346f0848741de317cb to your computer and use it in GitHub Desktop.
Statamic Replace Asset Action

Statamic Replace Asset Action

Replace an asset with a new file. Also renames the asset to the new name (Statamic will update references).

Known Issues

  1. The asset Browse button doesn't seem to work inside an action modal (statamic/cms#4785). Not a huge issue as you'll probably be uploading a new file anyway, but if it did work you could replace one asset with another, which might be useful.
  2. If you upload a new file and then click Cancel instead of Run the new file will remain at the root of the container.
  3. If you select multiple assets only the first will be replaced.
<?php
namespace App\Actions;
use Statamic\Actions\Action;
use Statamic\Contracts\Assets\Asset as AssetContract;
use Statamic\Facades\Asset;
class Replace extends Action
{
public function visibleTo($item)
{
return $item instanceof AssetContract;
}
protected function fieldItems()
{
return [
'file' => [
'type' => 'assets',
'container' => $this->context['container'],
'validate' => 'required',
'max_files' => 1,
],
];
}
public function run($items, $values)
{
/*
Order of operations looks a bit weird here but by doing it
this way the asset gets renamed as well as replaced, which
is important if the extension is different. Then references
to the original are updated. There's probably still a better
way to acheive that, but it works! ¯\_(ツ)_/¯
*/
$originalAsset = $items[0];
$newAsset = Asset::find($values['file'][0]);
$originalPath = $originalAsset->resolvedPath();
$newPath = $newAsset->resolvedPath();
$newName = $newAsset->filename();
unlink($originalPath);
copy($newPath, $originalPath);
$newAsset->delete();
$originalAsset->rename($newName);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment