Skip to content

Instantly share code, notes, and snippets.

@cornobils
Last active April 30, 2018 11:03
Show Gist options
  • Save cornobils/e4217d6d6d8820492ade5a210547cc30 to your computer and use it in GitHub Desktop.
Save cornobils/e4217d6d6d8820492ade5a210547cc30 to your computer and use it in GitHub Desktop.
How to inject custom DataTransformer in Sylius/Symfony form
<?php
namespace AppBundle\DataTransformer;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;
class CustomBooleanToStringTransformer implements DataTransformerInterface {
/**
* The value emitted upon transform if the input is true.
*
* @var string
*/
private $trueValue;
final class OnePageCheckoutType extends AbstractResourceType {
/** @var CustomBooleanToStringTransformer $transformer */
private $transformer;
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('differentBillingAddress', CheckboxType::class, [
'mapped' => false,
'required' => false,
'data' => true,
'label' => 'sylius.form.checkout.addressing.different_billing_address'
])
->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($options) {
...
});
$builder->get('differentBillingAddress')->resetViewTransformers()->addViewTransformer($this->transformer);
services:
app.transformer.bool_to_string:
class: 'AppBundle\DataTransformer\CustomBooleanToStringTransformer'
sylius.form.type.checkout_address:
class: AppBundle\Form\OnePageCheckoutType
autowire: true
arguments:
- '@app.transformer.bool_to_string'
- %sylius.model.order.class%
- %sylius.form.type.checkout_address.validation_groups%
tags:
- { name: form.type }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment