【问题标题】:Symfony 3.0+ : form CollectionType field doesn't generate any html inputSymfony 3.0+:表单 CollectionType 字段不生成任何 html 输入
【发布时间】:2017-11-19 00:08:09
【问题描述】:

我必须在我的项目中使用 CollectionType 字段,并且我希望有一个带有 name="langues[]" 的 html 输入,它将返回一个数组,但是从 Symfony 官方文档中复制代码后,该字段没有显示结果。只显示标签。

我写的代码:

    $builder->add('langues', CollectionType::class, array(
        'entry_type' => TextType::class,
        'allow_add' => true,
        'prototype' => true,
        'prototype_data' => 'New Tag Placeholder',
    ))
    ;

我从浏览器元素检查器中生成的html:

<div>
    <label class="required">Langues</label>
    <div id="homebundle_personnel_langues" data-prototype="<div><label for=&quot;homebundle_personnel_langues___name__&quot; class=&quot;required&quot;>__name__label__</label><input type=&quot;text&quot; id=&quot;homebundle_personnel_langues___name__&quot; name=&quot;homebundle_personnel[langues][__name__]&quot; required=&quot;required&quot; value=&quot;New Tag Placeholder&quot; /></div>">
    </div>
</div>

那么,如何正确实现 CollectionType 呢?

【问题讨论】:

  • 一个陷阱是父实体必须在数组中包含一种或多种语言才能看到它们。
  • Frank B 是对的:默认情况下,您的收藏是空的,因此没有可显示的内容。顺便说一句,在问类似问题之前,请考虑先查看您的other question。其他我们最终会针对同一问题提出许多不同的问题:不了解集合。
  • 这个网站的目的是收集开发者可以对google研究提出的最多的问题,老实说我认为这个问题是独立的,所以有很多人会使用收集也许他们会问这样一个笼统的问题,尽管另一个问题非常具体。感谢您的支持。
  • 不,本网站的目标是收集尽可能多的问题。目标是生成编写良好、实用、详细的问题和答案。使这个网站很棒的不是问题的数量,而是问题的质量。关于一个问题,您有 四个 问题:不了解收集的工作原理。请先阅读文档并查找类似的问题(从您自己的问题开始!)。并请回复您的own question

标签: symfony symfony-forms


【解决方案1】:

所以对这个问题的回答是,我们必须初始化属性$langues,该属性在实体中定义为一个数组,至少有一个集合字段。

// entity class :
private $langues = array('');

【讨论】:

    【解决方案2】:

    你为什么不关注documentation's example

    class Task
    {
        protected $description;
    
        protected $tags;
    
        public function __construct()
        {
            $this->tags = new ArrayCollection();
        }
    }
    

    还有控制器:

    class TaskController extends Controller
    {
        public function newAction(Request $request)
        {
            $task = new Task();
    
            // dummy code - this is here just so that the Task has some tags
            // otherwise, this isn't an interesting example
            $tag1 = new Tag();
            $tag1->setName('tag1');
            $task->getTags()->add($tag1);
            $tag2 = new Tag();
            $tag2->setName('tag2');
            $task->getTags()->add($tag2);
            // end dummy code
    
            //etc.
        }
    }
    

    所以你的情况

    class Personnel
    {    
        protected $langues;
    
        public function __construct()
        {
            $this->langues = new ArrayCollection();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-01-15
      • 2016-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多