duandie5707 2015-10-06 08:41
浏览 43
已采纳

Symfony2表单 - 结构化数据到扁平实体

Is it possible to map this data by SF2 form

[
   'name' => 'XL',
   'dimensions' => [
       'width' => 50,
       'height' => 20,
       'length' => 20,
    ]
] 

to the entity

Box[name, width, height, length]

Something like:

$builder->add('dimensions.width', 'text', [
    'property_path' => 'width'
])

Thanks!

  • 写回答

1条回答 默认 最新

  • doulu4976 2015-10-06 12:02
    关注

    Short version no. The dimensions array key above would have to be an embedded form, however you could set the data class to be the same object which would (probably) work. E.g.

    class DimensionType extends AbstractType
    {
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder->add('width')->add('height')->add('length');
        }
    
        public function configureOptions(OptionsResolver $resolver)
        {
            $resolver->setDefaults([ 'data_class' => 'MyClass' ]);
        }
    }
    
    class MyFormType extends AbstractType
    {
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder->add('name')->add('dimension', new DimensionType(), [ 'mapped' => false, 'data' => $options['data'] ]);
        }
    
        public function configureOptions(OptionsResolver $resolver)
        {
            $resolver->setDefaults([ 'data_class' => 'MyClass' ]);
        }
    }
    

    So you have two form types, one of which is embedded in the other. For MyFormType, the dimension field isn't mapped to MyClass, however it has the same data_class option which means when the form resolves it should set the width, height and length properties on the object.

    I haven't tested this but in theory this should work. Ideally you'd change the submitted data to match your object (as Symfony forms are only views of your objects) but this might be a decent patch.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000
  • ¥30 ppOCRLabel导出识别结果失败