【问题标题】:Symfony form CollectionType remove empty valueSymfony 表单 CollectionType 删除空值
【发布时间】:2017-07-19 14:50:46
【问题描述】:

我正在使用 Symfony 3.3,并且我有一个带有 CollectionType 的表单:

$builder->add('links', CollectionType::class, array(
    'label' => false,
    'entry_type' => LinkType::class,
    'entry_options' => ['data_class' => CompanyLink::class],
    'allow_add' => true,
    'allow_delete' => true,
    'prototype' => true,
    'by_reference' => false,
));

我遵循了文档:https://symfony.com/doc/current/reference/forms/types/collection.html

这是我的看法:

因此,表单显示了我的数据库中已经存在的数据(每次一行),但它总是另外添加一个空字段。

如何删除此空白字段?因为我只想拥有这条线,所以我点击了“Ajouter”按钮。

谢谢!

【问题讨论】:

  • 你确定你没有在某处添加一个空条目(例如在你的控制器中)?
  • 你好,是的,我是
  • 你试过delete_empty选项吗? symfony.com/doc/current/reference/forms/types/…
  • 是的,对我来说删除空白是在您提交表单时
  • 哦,对了,现在我明白你的问题了。你能告诉我们这个表单的底层对象的{{ dump() }}吗?

标签: php forms symfony


【解决方案1】:

我认为在你的表单渲染函数中你有 setData(),

要在没有数据的情况下呈现表单,您只需要执行以下示例:

//Your main entity
$mainEntity = new Entity();
//adding the other entity into collection variable of other entity of main entity
$mainEntity->addOtherEntity(new otherEntity());

$form = $this->createForm(
        MainEntityForm::class,
        $mainEntity
);

希望对你有帮助。

【讨论】:

    【解决方案2】:

    这篇文章有点老了,希望还不算晚。我找到了一个解决方案,即使你用树枝旅行 collectionType 字段。 为避免在 for 循环后出现此空字段,请添加

    {% do form.your_field.setRendered %}
    

    它对我有用,希望它对你也有用:)

    【讨论】:

      猜你喜欢
      • 2017-01-15
      • 1970-01-01
      • 2016-10-12
      • 2022-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多