Im trying to create a list of categories that need to be translated and display them as a tree structure. But so far no luck, i got tree structure going but when ever i create new category it adds up to the tree but wont display the name because its being translated with i18n and stores in diffirent table...
$categories_list = $this->Categories->find('treeList')->toArray();
This var stores tree it self with names that i have in Categories Table...
$categories_list = $this->Categories->find('translations')->toArray();
And this one gives me the actual translated categories, anyone has any idea how to combine them, CakePhp3 is a new thing for me and i cant find to much documentation about combining those two behaviors.
In order to get translated fields into tree list you need to add TranslateTrait into Category entity, it should look like this:
Link to CookBook about Translate behaviour and TranslateTrait
/src/Model/Entity/Category.php
<?php
namespace App\Model\Entity;
use Cake\ORM\Behavior\Translate\TranslateTrait;
use Cake\ORM\Entity;
class Category extends Entity{
use TranslateTrait;
//translation field must be accessible
protected $_accessible = [
'translations' => true,
];
}
Then you should stack multiple finder methods to achieve your goal, one for Translation Behaviour and one Tree Behaviour
Link to CookBook about how to stack multiple finder methods
/src/Controller/ArticlesController.php
use Cake\I18n\I18n;
public function foo(){
/***
*
* 1) use translation finder
* 2) use treeList finder
* 3) give to treeList finder the translated value to use in the output array as valuePath param
*
***/
$tree_list = $this->Articles->Categories
->find('translations')
->find('treeList', ['valuePath' => '_translations.' . I18n::getLocale() . '.title'])
->toArray();
}
You can leave I18n::getLocale() as it is to automatically get the tree list in current language or replace it with the language you prefer.