问题
SonataAdminBundle gives a method configureFormFields
when you extend the Admin
class.
That method takes a FormMapper
class.
For the entity that I have created this class for, I have already built a FormType
class in the typical Symfony fashion.
How can I use that class instead of having to define the form properties again using the FormMapper
?
回答1:
something like:
public function configureFormFields(FormMapper $formMapper)
{
$form = new ReviewFormType();
$form->buildForm($formMapper->getFormBuilder(),array());
}
回答2:
I had to the exact same thing today (defined a custom form type and tried to use in sonata) after hours of finding a clean way, i came up with this:
formMapper->add('your_field', new YourType($your_params), array(
), array('type' => 'form'))
Replace your_field
with your field name,
new YourType
with your custom field type and
$your_params
with your field's constructor's parameters,
the fourth parameter array('type' => 'form')
is very important, it tells sonata about what type your form is actually (sonata wont determine automatically from your type's object) my custom field extends the form
type (it is an embedded form with its own fields) so i specify that, if your type extends something else then specify that, and hopefully it would work fine.
回答3:
I came across this question looking for the exact same thing and eventually found the following in the docs:
You can add Symfony
FormBuilderInterface
instances to theFormMapper
. This allows you to re-use a model form type. When adding a field using aFormBuilderInterface
, the type is guessed.Given you have a
PostType
like this:use Symfony\Component\Form\FormBuilderInterface; use Symfony\Bridge\Doctrine\Form\Type\EntityType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\Extension\Core\Type\TextareaType; use Symfony\Component\Form\AbstractType; class PostType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('author', EntityType::class, [ 'class' => User::class ]) ->add('title', TextType::class) ->add('body', TextareaType::class) ; } }
you can reuse it like this:
use Sonata\AdminBundle\Form\FormMapper; use Sonata\AdminBundle\Admin\AbstractAdmin; use App\Form\PostType; class Post extend AbstractAdmin { protected function configureFormFields(FormMapper $formMapper) { $builder = $formMapper->getFormBuilder()->getFormFactory()->createBuilder(PostType::class); $formMapper ->with('Post') ->add($builder->get('title')) ->add($builder->get('body')) ->end() ->with('Author') ->add($builder->get('author')) ->end() ; } }
https://symfony.com/doc/master/bundles/SonataAdminBundle/reference/form_types.html#adding-a-formbuilderinterface
来源:https://stackoverflow.com/questions/13896885/how-to-use-existing-symfony-formtype-in-sonata-admin-bundle-configureformfields