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.

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

报告相同问题?