Symfony如何扩展集合表单字段

时间:2013-04-08 21:52:12

标签: forms symfony collections custom-post-type

我正在尝试扩展集合表单,以便使用自己的模板呈现它......

class ContactFieldType extends AbstractType
{
  public function setDefaultOptions(OptionsResolverInterface $resolver)
  {
    $resolver->setDefaults(array(
      'collection' => array('type' => new ContactType())
    ));
  }

  public function getParent()
  {
    return 'collection';
  }

  public function getName()
  {
    return 'contactField';
  }
}

我以这种方式使用这种类型:

$builder->add('contacts',new ContactFieldType(), array(
  'label_attr' => array('class' => 'contacts')
));

我收到以下错误:

  

表单的视图数据应该是标量,数组或类型   \ ArrayAccess的实例,但是是类的实例   MyApp的\ MainBundle \实体\联系。你可以避免这个错误   将“data_class”选项设置为   “MyApp \ MainBundle \ Entity \ Contact”或添加视图转换器   转换类的实例   MyApp \ MainBundle \ Entity \与标量,数组或实例联系   \ ArrayAccess。

如果我使用它:

$builder->add('contacts','collection', array(
  'type' => new ContactType(),
  'label_attr' => array('class' => 'contacts')
));

工作正常。

我不想按照建议实现这个data_class ...我想扩展集合小部件

1 个答案:

答案 0 :(得分:1)

您的表单定义似乎很好,不需要更多的修补。你的问题在于实现。

从我看到的情况来看,我相信你或多或少会以这种方式实现你的形式:

$model = new ParentClass();
$model->setContacts(new Contact());

$form = $this->createForm(new ParentFormType(), $model));

但是,集合表单类型不使用 Contact()实例,而是使用此类实例的数组。

使用Contact()实例而不是此类对象的数组提供了instanciation,您的代码将失败。你需要做的是:

$model = new ParentClass();
$model->setContacts(array(new Contact()));

$form = $this->createForm(new ParentFormType(), $model));

虽然这是我相信你所做的,但你还没有提交实例代码,因此很难判断我是否正确。如果您的问题仍然存在,我建议您提供。