PHP code example of elao / form-simple-object-mapper

1. Go to this page and download the library: Download elao/form-simple-object-mapper library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

elao / form-simple-object-mapper example snippets



// app/AppKernel.php

// ...
class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = [
            // ...
            new Elao\FormSimpleObjectMapper\Bridge\Symfony\Bundle\ElaoFormSimpleObjectMapperBundle(),
        ];
    }

    // ...
}



use Elao\FormSimpleObjectMapper\Type\Extension\SimpleObjectMapperTypeExtension;
use Symfony\Component\Form\Forms;
 
$builder = Forms::createFormFactoryBuilder();
$builder->addTypeExtension(new SimpleObjectMapperTypeExtension());
$factory = $builder->getFormFactory();



namespace Acme\Application\Cart\Command;

class AddItemToCartCommand
{
    /** @var string */
    private $reference;

    /** @var int */
    private $quantity;

    public function __construct($reference, $quantity)
    {
        $this->reference = $reference;
        $this->quantity = $quantity;
    }

    public function getReference()
    {
        return $this->reference;
    }
    
    public function getQuantity()
    {
        return $this->quantity;
    }
}



class CartController extends Controller
{
    //...

    public function addItemAction(Request $request)
    {
        $builder = $this
            ->createFormBuilder()
            ->add('reference', HiddenType::class)
            ->add('quantity', IntegerType::class)
        ;
        
        $form = $builder->getForm();

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $data = $form->getData();
            
            $command = new AddItemToCartCommand($data['reference'], $data['quantity']);
            
            $this->getCommandBus()->handle($command);

            return $this->redirect(/*...*/);
        }

        return $this->render(':cart:add_item.html.twig', [
            'form' => $form->createView(),
        ]);
    }
    
    //...
}



class AddItemToCartType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('reference', HiddenType::class)
            ->add('quantity', IntegerType::class)
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => AddItemToCartCommand::class,
            'empty_data' => new AddItemToCart('', 1),
        ]);
    }
}



class CartController extends Controller
{
    //...

    public function addItemAction(Request $request)
    {
        $form = $this->createForm(AddItemToCartType::class);

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $command = $form->getData();
            
            $this->getCommandBus()->handle($command);

            return $this->redirect(/*...*/);
        }

        return $this->render(':cart:add_item.html.twig', [
            'form' => $form->createView(),
        ]);
    }
    
    //...
}



class AddItemToCartType extends AbstractType implements FormDataToObjectConverterInterface // <-- Implement this interface
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('reference', HiddenType::class)
            ->add('quantity', IntegerType::class)
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => AddItemToCartCommand::class,
            'simple_object_mapper' => $this, // <-- Set this option
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function convertFormDataToObject(array $data, $originalData)
    {
        // Tells the form how to build your object from its data:
        return new AddItemToCartCommand(
            $data['reference'],
            $data['quantity']
        );
    }
}



class AddItemToCartType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('reference', HiddenType::class)
            ->add('quantity', IntegerType::class)
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => AddItemToCartCommand::class,
            'simple_object_mapper' => function (array $data, $originalData) {
                  // Tells the form how to build your object from its data:
                  return new AddItemToCartCommand(
                      $data['reference'],
                      $data['quantity']
                  );
            }
        ]);
    }
}



class MoneyType extends AbstractType implements FormDataToObjectConverterInterface 
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('amount', NumberType::class)
            ->add('currency')
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Money::class,
            'simple_object_mapper' => $this,
        ]);
    }

    /**
     * {@inheritdoc}
     *
     * @param Money|null $originalData
     */
    public function convertFormDataToObject(array $data, $originalData)
    {
        // Logic to determine if the result should be considered null according to form fields data.
        if (null === $data['amount'] && null === $data['currency']) {
            return null;
        }

        return new Money($data['amount'], $data['currency']);
    }
}

# Money.php
class Money
{
    private $amount;
    private $currency;

    public function __construct($amount, $currency)
    {
        $this->amount = $amount;
        $this->currency = $currency;
    }

    public function getAmount() // ...
    public function getCurrency() // ...
}



class MediaConverter implements FormDataToObjectConverterInterface, ObjectToFormDataConverterInterface 
{
    // ...

    /**
     * {@inheritdoc}
     *
     * @param Media|null $object
     */
    public function convertObjectToFormData($object)
    {
        if (null === $object) {
            return [];
        }

        $mediaTypeByClass = [
            Movie::class => 'movie',
            Book::class => 'book',
        ];

        if (!isset($mediaTypeByClass[get_class($object)])) {
            throw new TransformationFailedException('Unexpected object class');
        }

        // The returned array will be used to set data in each form fields identified by keys.
        return [
            'mediaType' => $mediaTypeByClass[get_class($object)],
            'author' => $object->getAuthor(),
        ];
    }
}