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.

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

报告相同问题?

悬赏问题

  • ¥15 有偿求苍穹外卖环境配置
  • ¥15 代码在keil5里变成了这样怎么办啊,文件图像也变了,
  • ¥20 Ue4.26打包win64bit报错,如何解决?(语言-c++)
  • ¥15 clousx6整点报时指令怎么写
  • ¥30 远程帮我安装软件及库文件
  • ¥15 关于#自动化#的问题:如何通过电脑控制多相机同步拍照或摄影(相机或者摄影模组数量大于60),并将所有采集的照片或视频以一定编码规则存放至规定电脑文件夹内
  • ¥20 深信服vpn-2050这台设备如何配置才能成功联网?
  • ¥15 Arduino的wifi连接,如何关闭低功耗模式?
  • ¥15 Android studio 无法定位adb是什么问题?
  • ¥15 C#连接不上服务器,