【问题标题】:Symfony 3 - Form - CollectionType in Entity without DoctrineSymfony 3 - 表单 - 没有教义的实体中的 CollectionType
【发布时间】:2018-04-28 23:46:38
【问题描述】:

我正在为 symfony3 表单和 CollectionType 类苦苦挣扎:

我有一个包含多个复杂表单的页面。我不使用任何数据库(经过验证的表单被发送到外部 REST 服务)

现在假设我的请求有一个名为“ProductService”的实体对象:

class ProductService
{
    /** @var string */
    private $msg;

    /** @var array*/
    private $products
}

还有一个 ProductServiceType 类来呈现表单:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('products', CollectionType::class, [
            'entry_type'   => ProductType::class,
        ])
        ->add('msg' [...]);
}

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults([
        'data_class' => ProductService::class,
    ]);
}

通过此设置,一切都像魅力一样工作,所有产品都将添加到我实体的产品数组中。 问题是,我希望 $products 成为一个 SplObjectStorage-object:

class ProductService
{
    /** @var string */
    private $msg;

    /** @var SplObjectStorage */
    private $products
}

如果我将它设置为此并附加一个空对象,symfony 就不能再渲染表单了。它抛出以下错误: 警告:SplObjectStorage::offsetExists() 期望参数 1 是对象,给定字符串

那么,谁能告诉我,当不使用教义和 orm 时,如何处理实体中的 collectionType? 是使用数组的唯一可能性,还是这种情况有任何文档,我没有找到? (我还在想 symfony 是怎么调用 offsetExists 的,一定有什么东西可以实现来处理 SplObjectStorage,还是我错了?)

【问题讨论】:

    标签: forms symfony splobjectstorage


    【解决方案1】:

    我相信你的错误是因为没有实现表单集合来处理你所期望的 SplObjectStorage。您可以在 symfony 存储库中为其创建问题。

    当 symfony 试图通过以这种方式从 ProductService 中读取您的产品来填充表单集合时,会导致该错误:

    $products = $productService->getProducts();
    $products->offsetExists(0); //here is the error.
    

    因为它期望任何实现 ArrayAccess 的存储都将以这种方式读取,但对于 SplObjectStorage,情况并非如此。

    表单元素有一个设置 property_path link,您可以利用它来解决您的问题。

    我的解决方案是使用此设置并返回 返回数组 来填充您的集合:

    $builder
            ->add('products', CollectionType::class, [
                'entry_type'   => ProductType::class,
                'property_path' => 'productsArray'
            ])
    
    class ProductService
    {
    
    ... 
    public function getProductsArray() {
        $prArray= [];
        foreach ($this->products as $value) {
            $prArray[] = $value;
        }
        return $prArray;
    }
    

    这样您就可以使用生成的数组来填充表单集合。

    我认为另一种解决方案是使用data transformer。希望这会有所帮助

    【讨论】:

    • 哇,Botis 先生,你让我很开心 :) 这似乎是一个不错的解决方案!我将在接下来的几天尝试并给出答案。非常感谢
    • 您好 Jannes,我刚刚实施了您的解决方案并且它有效。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-01
    • 1970-01-01
    相关资源
    最近更新 更多