You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

TranslationEasyAdminSubscriber.php 2.8KB

3 jaren geleden
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. namespace Lc\SovBundle\EventSubscriber\Translation;
  3. use Doctrine\ORM\PersistentCollection;
  4. use Doctrine\ORM\Query;
  5. use EasyCorp\Bundle\EasyAdminBundle\Event\AfterCrudActionEvent;
  6. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeCrudActionEvent;
  7. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityPersistedEvent;
  8. use Gedmo\Translatable\TranslatableListener;
  9. use Lc\SovBundle\Doctrine\Extension\TranslatableInterface;
  10. use Lc\SovBundle\Doctrine\EntityManager;
  11. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  12. use function Symfony\Component\Translation\t;
  13. class TranslationEasyAdminSubscriber implements EventSubscriberInterface
  14. {
  15. protected $em;
  16. public function __construct(EntityManager $entityManager)
  17. {
  18. $this->em = $entityManager;
  19. }
  20. public static function getSubscribedEvents()
  21. {
  22. return [
  23. BeforeCrudActionEvent::class => ['setTranslatableLocale']
  24. ];
  25. }
  26. public function setTranslatableLocale(BeforeCrudActionEvent $event)
  27. {
  28. $entity = $event->getAdminContext()->getEntity()->getInstance();
  29. $_locale = $event->getAdminContext()->getRequest()->get('_locale');
  30. if($entity instanceof TranslatableInterface){
  31. //parcours les champs association pour détecter un champ de association qui est traduisible
  32. foreach ($this->em->getClassMetadata(get_class($entity))->getAssociationMappings() as $associationMapping){
  33. if (in_array(TranslatableInterface::class, class_implements($associationMapping["targetEntity"]))){
  34. if($entity->__get($associationMapping['fieldName']) instanceof PersistentCollection){
  35. foreach ($entity->__get($associationMapping['fieldName']) as $item){
  36. $item->setTranslatableLocale($_locale);
  37. $this->em->refresh($item);
  38. }
  39. }else{
  40. if($entity->__get($associationMapping['fieldName'])) {
  41. $entity->__get($associationMapping['fieldName'])->setTranslatableLocale($_locale);
  42. $this->em->refresh($entity->__get($associationMapping['fieldName']));
  43. }
  44. }
  45. }
  46. }
  47. $entity->setTranslatableLocale($_locale);
  48. $this->em->refresh($entity);
  49. }
  50. }
  51. }