From c89ef021b8375c66d2504e6c876d53a5ba0587b4 Mon Sep 17 00:00:00 2001 From: Kjell Date: Tue, 20 Jun 2017 15:10:05 +0200 Subject: [PATCH] [Documentation] Customizing Forms: Extensions Form Extensions explained with ProductVariant example --- docs/customization/form.rst | 83 +++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) diff --git a/docs/customization/form.rst b/docs/customization/form.rst index e86f81454c..bbe670e099 100644 --- a/docs/customization/form.rst +++ b/docs/customization/form.rst @@ -123,6 +123,89 @@ Need more information? Some of the forms already have extensions in Sylius. Learn more about Extensions `here `_. +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 + + 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 + + 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 ---------------------------