Created
July 21, 2013 14:52
-
-
Save doup/6048770 to your computer and use it in GitHub Desktop.
FormType to use with Sonata + KNP DoctrineBehaviours translatable trait
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\PlaceBundle\Admin; | |
use App\PlaceBundle\Form; | |
use Sonata\AdminBundle\Admin\Admin; | |
use Sonata\AdminBundle\Datagrid\ListMapper; | |
use Sonata\AdminBundle\Datagrid\DatagridMapper; | |
use Sonata\AdminBundle\Form\FormMapper; | |
class PlaceAdmin extends Admin | |
{ | |
protected function configureFormFields(FormMapper $formMapper) | |
{ | |
$formMapper | |
->add('telephone') | |
->add('address') | |
->add('translations', new Form\Type\TranslationType($this), array( | |
'type' => new Form\PlaceTranslationType(), | |
)) | |
; | |
} | |
// ... | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\PlaceBundle\Form\Type; | |
use App\PlaceBundle\Form; | |
use Symfony\Component\Form\AbstractType; | |
use Symfony\Component\Form\FormBuilderInterface; | |
use Symfony\Component\Form\FormEvents; | |
use Symfony\Component\Form\FormEvent; | |
use Symfony\Component\OptionsResolver\OptionsResolverInterface; | |
class TranslationType extends AbstractType | |
{ | |
protected $class; | |
public function __construct($admin) | |
{ | |
$this->class = $admin->getClass() . 'Translation'; | |
} | |
/** | |
* {@inheritDoc} | |
*/ | |
public function buildForm(FormBuilderInterface $builder, array $options) | |
{ | |
$builder->addEventListener(FormEvents::PRE_SET_DATA, function(FormEvent $event) use ($builder) { | |
$form = $event->getForm(); | |
$entity = $form->getParent()->getData(); | |
// Initialize | |
foreach (['es', 'eu', 'it'] as $locale) { | |
$entity->translate($locale); | |
} | |
$entity->mergeNewTranslations(); | |
}); | |
} | |
/** | |
* {@inheritDoc} | |
*/ | |
public function setDefaultOptions(OptionsResolverInterface $resolver) | |
{ | |
$resolver->setDefaults(array( | |
'allow_add' => false, | |
'by_reference' => true, | |
'options' => [ | |
'data_class' => $this->class, | |
] | |
)); | |
} | |
public function getParent() | |
{ | |
return 'collection'; | |
} | |
/** | |
* {@inheritDoc} | |
*/ | |
public function getName() | |
{ | |
return 'sonata_type_translation'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment