Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions src/TranslateableBehavior.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ class TranslateableBehavior extends Behavior
public function events()
{
return [
ActiveRecord::EVENT_INIT => 'addTranslations', // populate translations on new object
ActiveRecord::EVENT_AFTER_FIND => 'addTranslations', // populate translations on find object
ActiveRecord::EVENT_AFTER_VALIDATE => 'afterValidate',
ActiveRecord::EVENT_AFTER_INSERT => 'afterSave',
ActiveRecord::EVENT_AFTER_UPDATE => 'afterSave',
Expand Down Expand Up @@ -118,6 +120,27 @@ public function hasTranslation($language = null)

return false;
}

/**
* Auto populate translation attributes
*
* @return void
*/
public function addTranslations()
{
$this->owner->{$this->translationRelation};

/* @var ActiveRecord $class */
$class = $this->owner->getRelation($this->translationRelation)->modelClass;

/* If method create or update - populate attributes */
$className = (new \ReflectionClass($class))->getShortName();
foreach (Yii::$app->request->post($className, []) as $language => $data) {
foreach ($data as $attribute => $translation) {
$this->owner->translate($language)->$attribute = $translation;
}
}
}

/**
* @return void
Expand Down