-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTranslatableControlTrait.php
More file actions
66 lines (58 loc) · 2.43 KB
/
Copy pathTranslatableControlTrait.php
File metadata and controls
66 lines (58 loc) · 2.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<?php
namespace ADT\Utils\Translatable;
use ADT\DoctrineForms\Entity;
use ADT\DoctrineForms\EntityFormMapper;
use ADT\DoctrineForms\Form;
use ADT\Forms\DynamicContainer;
use Gedmo\Translatable\Entity\Repository\TranslationRepository;
use Nette\Forms\Controls\BaseControl;
trait TranslatableControlTrait
{
public function addTranslation(Form $form, $name, $containerFactory)
{
$container = $form->addDynamicContainer($name, $containerFactory);
$form
->setComponentFormMapper($container, function (EntityFormMapper $mapper, DynamicContainer $container, Entity $entity) {
$meta = $mapper->getMetadata($entity);
/** @var TranslationRepository $repository */
$repository = $mapper->getEntityManager()->getRepository('Gedmo\Translatable\Entity\Translation');
foreach ($repository->findTranslations($entity) as $_locale => $_translation) {
$translationEntity = new $entity;
foreach ($_translation as $field => $value) {
$meta->setFieldValue($translationEntity, $field, $value);
}
$mapper->load($translationEntity, $container[$_locale]);
$container[$_locale]['locale']->setDefaultValue($_locale);
}
})
->setComponentEntityMapper($container, function (EntityFormMapper $mapper, DynamicContainer $container, Entity $entity) {
// delete removed locales
$locales = [];
foreach ($container->getComponents(false) as $_toOneContainer) {
$locales[$_toOneContainer['locale']->getValue()] = $_toOneContainer['locale']->getValue();
}
/** @var TranslationRepository $repository */
$repository = $mapper->getEntityManager()->getRepository('Gedmo\Translatable\Entity\Translation');
$repository->createQueryBuilder('e')
->where('e.objectClass = :objectClass')
->andWhere('e.locale NOT IN (:locales)')
->andWhere('e.foreignKey = :foreignKey')
->setParameter('objectClass', get_class($entity))
->setParameter('locales', $locales)
->setParameter('foreignKey', $entity->getId())
->delete()
->getQuery()
->execute();
// create new locales / update existing locales
foreach ($container->getComponents(false) as $_toOneContainer) {
/** @var BaseControl $_control */
foreach ($_toOneContainer->getControls() as $_control) {
if ($_control->getName() === 'locale') {
continue;
}
$repository->translate($entity, $_control->getName(), $_toOneContainer['locale']->getValue(), $_control->getValue());
}
}
});
}
}