Utilising knp translatable doctrine extension with sonata admin.
When you have a translated entity with a collection of entities that are also translated, is it possible to get the translated item to appear in sonata_type_collection?
: e.g. CategoryEntity
has a oneToMany association with ArticleEntity
, both have translation tables configured. In the CategoryAdmin
, a property articles
with type sonata_type_collection
is defined, however no values appear (The translations are definitely working otherwise).
I have experienced this situation and end up with this solution,
Simply just add mergeNewTranslations() on prePersist() and preUpdate()
The sample code look like,
<?php
namespace Website\CategoryBundle\Admin;
use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Form\FormMapper;
class CategoryAdmin extends AbstractAdmin
{
/**
* @inheritdoc
*/
public function configureFormFields(FormMapper $formMapper)
{
...
$formMapper
->with('config.label_category', ['class' => 'col-md-12'])
->add('name', TextType::class, [
'label' => 'config.label_name'
]
)
->end()
->with('config.label_article', ['class' => 'col-md-12'])
->add('articles', CollectionType::class,
[
'label' => false,
'required' => false,
'by_reference' => false,
],
[
'edit' => 'inline',
'inline' => 'table',
'sortable' => 'position',
]
)
->end()
}
/**
* @inheritdoc
*/
public function prePersist($obj)
{
foreach ($obj->getArticles() as $article) {
// $article->translate();
$article->mergeNewTranslations();
}
}
/**
* @inheritdoc
*/
public function preUpdate($obj)
{
foreach ($obj->getArticles() as $article) {
// $article->translate();
$article->mergeNewTranslations();
}
}
}