Skip to content

Instantly share code, notes, and snippets.

@doup
Created July 21, 2013 14:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save doup/6048770 to your computer and use it in GitHub Desktop.
Save doup/6048770 to your computer and use it in GitHub Desktop.
FormType to use with Sonata + KNP DoctrineBehaviours translatable trait
<?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(),
))
;
}
// ...
}
<?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