duanhai7274 2015-09-08 16:14
浏览 15
已采纳

动态表格上的Symfony数据变换器

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?

  • 写回答

2条回答 默认 最新

  • dongzhijing8202 2015-09-09 12:13
    关注

    So the problem was that I was using an entity type instead of a text type when using the model data transformer.

    Here is my working code albeit probably not perfect, the primary form

    class BasketAddType extends AbstractType
    {
        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)
        {
            $form = $event->getForm()->getParent();
            $product = $event->getForm()->getData();
    
            $form
                ->add('size', 'size', [
                    'sizes' => $product->getSizes()->toArray() // getSizes() is an ArrayCollection
                );
        }
    
        public function getName()
        {
            return '';
        }
    }
    

    My custom form size type which applies the model transformer with the provided size options.

    class SizeType extends AbstractType
    {
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder->addModelTransformer(new SizeTransformer($options['sizes']));
        }
    
        public function setDefaultOptions(OptionsResolverInterface $resolver)
        {
            $resolver->setRequired([
                'sizes'
            ]);
        }
    
        public function getParent()
        {
            return 'text';
        }
    
        public function getName()
        {
            return 'size';
        }
    }
    

    And finally the size transformer.

    class SizeTransformer implements DataTransformerInterface
    {
        protected $sizes;
    
        public function __construct(array $sizes)
        {
            $this->sizes = $sizes;
        }
    
        public function transform($size)
        {
            if (null === $size) {
                return '';
            }
    
            return $size->getCode();
        }
    
        public function reverseTransform($code)
        {
            foreach ($this->sizes as $size) {
                if ($size->getCode() == $code) {
                    return $size;
                }
            }
    
            throw new TransformationFailedException('No such size exists');
        }
    }
    

    This solution wouldn't work too well if there were a high number of sizes available for each product. Guess if that was the case I'd need to pass both the EntityManager and the product into the transformer and query the DB accordingly.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?