Skip to content

Instantly share code, notes, and snippets.

@carlcs
Last active July 27, 2018 14:01
Show Gist options
  • Save carlcs/d91ec5ccdedcc1dabf56cb19ed337c59 to your computer and use it in GitHub Desktop.
Save carlcs/d91ec5ccdedcc1dabf56cb19ed337c59 to your computer and use it in GitHub Desktop.
Make asset titles non-translatable
<?php
namespace modules;
use Craft;
use craft\elements\Asset;
use yii\base\Event;
use yii\base\ModelEvent;
class Module extends \yii\base\Module
{
/**
* @var string[]
*/
private $_assetTitles = [];
/**
* Initializes the module.
*/
public function init()
{
// Set a @modules alias pointed to the modules/ directory
Craft::setAlias('@modules', __DIR__);
// Set the controllerNamespace based on whether this is a console or web request
if (Craft::$app->getRequest()->getIsConsoleRequest()) {
$this->controllerNamespace = 'modules\\console\\controllers';
} else {
$this->controllerNamespace = 'modules\\controllers';
}
parent::init();
// Custom initialization code goes here...
Event::on(Asset::class, Asset::EVENT_BEFORE_SAVE, [$this, 'overrideTranslatedAssetTitle']);
}
/**
* Makes asset titles non-translatable.
*
* @param ModelEvent $event
*/
public function overrideTranslatedAssetTitle(ModelEvent $event)
{
$asset = $event->sender;
// Save the title for later when the element is being propagated
if (!array_key_exists($asset->id, $this->_assetTitles)) {
$this->_assetTitles[$asset->id] = $asset->title;
} else {
$asset->title = $this->_assetTitles[$asset->id];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment