I'm building an API using FOSRestBundle for adding products to a basket. For the sake of keeping this example simple we have a range of products which come in different sizes.
I'd like to be able to specify the size code in the JSON request. For example:
{
"product": 3,
"size": "S"
}
(I'd also like to use the product code instead of the database ID, but that's for another day!)
Other parts of the project I have done similar tasks using data transformers, but these were simpler forms where the values didn't change based on other fields selected values.
So my current basket form...
class BasketAddType extends AbstractType
{
protected $em;
public function __construct(EntityManager $em)
{
$this->em = $em;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('product', 'entity', [
'class' => 'CatalogueBundle:Product',
]);
$builder->get('product')->addEventListener(FormEvents::POST_SUBMIT, [$this, 'onPostSubmit']);
}
public function onPostSubmit(FormEvent $event)
{
// this will be Product entity
$form = $event->getForm();
$this->addElements($form->getParent(), $form->getData());
}
protected function addElements(FormInterface $form, Product $product = null)
{
if (is_null($product)) {
$sizes = [];
} else {
$sizes = $product->getSizes();
}
$form
->add('size', 'size', [
'choices' => $sizes
]);
}
public function getName()
{
return '';
}
}
The custom size form type I'm using above is so I can add the model transformer. As found in this answer https://stackoverflow.com/a/19590707/3861815
class SizeType extends AbstractType
{
protected $em;
public function __construct(EntityManager $em)
{
$this->em = $em;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->addModelTransformer(new SizeTransformer($this->em));
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults([
'class' => 'CatalogueBundle\Entity\Size'
]);
}
public function getParent()
{
return 'entity';
}
public function getName()
{
return 'size';
}
}
And finally the transformer.
class SizeTransformer implements DataTransformerInterface
{
protected $em;
public function __construct(EntityManager $em)
{
$this->em = $em;
}
public function transform($size)
{
if (null === $size) {
return '';
}
return $size->getCode();
}
public function reverseTransform($code)
{
// WE NEVER GET HERE?
$size = $this->em->getRepository('CatalogueBundle:Size')
->findOneByCode($code);
if (null === $size) {
throw new TransformationFailedException('No such size exists');
}
return $size;
}
}
So I did a quick exit;
in reverseTransform
and it's never fired so I will always get an error on the size element about it being invalid.
What would be the best way to getting a data transformer onto the size field here?