[Documentation] Customizing Forms: Extensions

Form Extensions explained with ProductVariant example
This commit is contained in:
Kjell 2017-06-20 15:10:05 +02:00
parent 8700b3eb6f
commit c89ef021b8

View file

@ -123,6 +123,89 @@ Need more information?
Some of the forms already have extensions in Sylius. Learn more about Extensions `here <http://symfony.com/doc/current/bundles/extension.html>`_.
F.i. the ``ProductVariant`` admin form is defined under ``Sylius/Bundle/ProductBundle/Form/Type/ProductVariantType.php`` and later extended in
``Sylius/Bundle/CoreBundle/Form/Extension/ProductVariantTypeExtension.php``. If you again extend the base type form like this:
.. code-block:: yaml
services:
app.form.extension.type.product_variant:
class: AppBundle\Form\Extension\ProductVariantTypeMyExtension
tags:
- { name: form.type_extension, extended_type: Sylius\Bundle\ProductBundle\Form\Type\ProductVariantType, priority: -5 }
your form extension will also be executed. Whether before or after the other extensions depends on priority tag set.
Having a look at the extensions and possible additionally defined event handlers can also be useful when form elements are embedded dynamically,
as it is done in the ``ProductVariantTypeExtension`` by the ``CoreBundle``:
.. code-block:: php
<?php
...
final class ProductVariantTypeExtension extends AbstractTypeExtension
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
...
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
$productVariant = $event->getData();
$event->getForm()->add('channelPricings', ChannelCollectionType::class, [
'entry_type' => ChannelPricingType::class,
'entry_options' => function (ChannelInterface $channel) use ($productVariant) {
return [
'channel' => $channel,
'product_variant' => $productVariant,
'required' => false,
];
},
'label' => 'sylius.form.variant.price',
]);
});
}
...
}
The ``channelPricings`` get added on ``FormEvents::PRE_SET_DATA``, so when you wish to remove or alter this form definition,
you will also have to set up an event listener and then remove the field:
.. code-block:: php
<?php
...
final class ProductVariantTypeMyExtension extneds AbstractTypeExtension
{
...
public function buildForm(FormBuilderInterface $builder, array $options)
{
...
$builder
->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
$event->getForm()->remove('channelPricings');
})
->addEventSubscriber(new AddCodeFormSubscriber(NULL, ['label' => 'app.form.my_other_code_label']))
;
...
}
}
Here we additionally redefine the labeling of the code field, which is first added in the basic ``ProductVariantType`` class.
Overriding forms completely
---------------------------