Save translations in a relation modal
0
Update March 2019: Issue #209 that caused this problem has been solved. Starting from October Build 449 you should no longer have to take care of the translations yourself.
==============
Due to issue #209 translations in a relation modal are not saved correctly.
To fix this problem, do the following:
- Create the following trait in
plugins/yourvendor/yourplugin/classes/TranslatableRelation.php
.
namespace YourVendor\YourPlugin\Classes;
use Illuminate\Support\Facades\DB;
/**
* @see https://github.com/rainlab/translate-plugin/issues/209#issuecomment-362088300
*/
trait TranslatableRelation
{
/**
* This is a temporary fix until
* https://github.com/rainlab/translate-plugin/issues/209
* is resolved.
*/
protected function setTranslatableFields()
{
if ( ! post('RLTranslate')) {
return;
}
$translatableIndexes = [];
$translatableAttributes = [];
foreach (post('RLTranslate') as $key => $value) {
foreach ($this->translatable as $translatableAttribute) {
if (isset($translatableAttribute['index'])) {
$translatableIndexes[$translatableAttribute[0]] = '';
$translatableAttributes[$translatableAttribute[0]] = '';
} else {
$translatableAttributes[$translatableAttribute] = '';
}
}
$data = collect($value)->intersectByKeys($translatableAttributes);
$indexes = collect($value)->intersectByKeys($translatableIndexes);
$obj = DB::table('rainlab_translate_attributes')
->where('locale', $key)
->where('model_id', $this->id)
->where('model_type', get_class($this->model));
if ($obj->count() > 0) {
$obj->update(['attribute_data' => $data->toJson()]);
} else {
DB::table('rainlab_translate_attributes')
->insert([
'locale' => $key,
'model_id' => $this->id,
'model_type' => get_class($this->model),
'attribute_data' => $data->toJson(),
]
);
}
foreach ($indexes as $item => $value) {
$obj = DB::table('rainlab_translate_indexes')
->where('locale', $key)
->where('model_id', $this->id)
->where('model_type', get_class($this->model))
->where('item', $item);
if ($obj->count() > 0) {
$obj->update(['value' => $value]);
} else {
DB::table('rainlab_translate_indexes')
->insert([
'locale' => $key,
'model_id' => $this->id,
'model_type' => get_class($this->model),
'item' => $item,
'value' => $value,
]
);
}
}
}
}
public function afterSave()
{
$this->setTranslatableFields();
}
}
- Use the trait in the model you are editing via the relation (the modal that is loaded in the modal).
class RelatedModel extends Model
{
use YourVendor\YourPlugin\Classes\TranslatableRelation;
}
Hello, very useful but i had a problem, I was trying to implement this trait to a nested relation modal, and it returned me always 'get_class() expects parameter 1 to be object null given at line 42 in plugins/yourvendor/yourplugin/classes/TranslatableRelation.php', i solved this by changing all '$this->model' in the file by '$this'. and now it works