diff --git a/Form/EventListener/TranslationsSubscriber.php b/Form/EventListener/TranslationsSubscriber.php index aa732be..a321666 100644 --- a/Form/EventListener/TranslationsSubscriber.php +++ b/Form/EventListener/TranslationsSubscriber.php @@ -30,11 +30,12 @@ public function preSetData(FormEvent $event) $fieldsOptions = $formOptions['fields']; $entity = $event->getForm()->getParent()->getData(); - foreach ($formOptions['locales'] as $locale) { $form->add($locale, TranslationItemType::class, [ 'required' => in_array($locale, $formOptions['required_locales'], true), 'fields' => $fieldsOptions, + 'entity' => $entity, + 'locale' => $locale, 'data_class' => $entity::getTranslationEntityClass(), ]); } diff --git a/Form/Type/TranslationItemType.php b/Form/Type/TranslationItemType.php index 54d6d31..4e2b5d9 100644 --- a/Form/Type/TranslationItemType.php +++ b/Form/Type/TranslationItemType.php @@ -14,11 +14,28 @@ class TranslationItemType extends AbstractType */ public function buildForm(FormBuilderInterface $builder, array $options) { + $created = false; + //For update case foreach ($options['fields'] as $fieldName => $fieldSettings) { - $fieldWidget = !empty($fieldSettings['widget_class']) ? $fieldSettings['widget_class'] : TextType::class; - $fieldOptions = !empty($fieldSettings['options']) ? $fieldSettings['options'] : []; - - $builder->add($fieldName, $fieldWidget, $fieldOptions); + foreach ($options['entity']->getTranslations() as $translation) { + if ($options['locale'] !== $translation->getLocale()) { + continue; + } + $fieldWidget = !empty($fieldSettings['widget_class']) ? $fieldSettings['widget_class'] : TextType::class; + $fieldOptions = !empty($fieldSettings['options']) ? $fieldSettings['options'] : []; + $getter = sprintf('get%s', $fieldName); + $fieldOptions['data'] = $translation->$getter(); + $builder->add($fieldName, $fieldWidget, $fieldOptions); + $created = true; + } + } + //For create case + if ($created === false) { + foreach ($options['fields'] as $fieldName => $fieldSettings) { + $fieldWidget = !empty($fieldSettings['widget_class']) ? $fieldSettings['widget_class'] : TextType::class; + $fieldOptions = !empty($fieldSettings['options']) ? $fieldSettings['options'] : []; + $builder->add($fieldName, $fieldWidget, $fieldOptions); + } } } @@ -29,6 +46,8 @@ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ 'fields' => [], + 'entity' => null, + 'locale' => null ]); } }