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 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据