在Symfony2中,我有一个SelectableEmailsType
,其中包含SelectableEmailType
的集合。这只是让我有一个包含多个“ID /复选框”的表单。行。
当我实例化我的表单时:
$selectableEmailsModel = new SelectableEmails();
$selectableEmailModels = [];
foreach ($emailEntities as $emailEntity) {
$selectableEmail = new SelectableEmail();
$selectableEmail->setId($emailEntity->getId());
$selectableEmailModels[] = $selectableEmail;
}
$selectableEmailsModel->setSelectableEmails($selectableEmailModels);
$form = $this->createForm(new SelectableEmailsType(), $selectableEmailsModel);
我得到The form's view data is expected to be of type scalar, array or an instance of \ArrayAccess, but is an instance of class MyProject\Bundle\EmailsBundle\Form\Model\SelectableEmail
。
我哪里错了?以下是我的类型和相关模型:
class SelectableEmailsType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('selectableEmails', 'collection', [ 'type' => new SelectableEmailType() ]);
}
public function getName()
{
return 'selectableEmails';
}
}
class SelectableEmailType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('id', 'text');
$builder->add('selected', 'checkbox');
}
public function getName()
{
return 'selectableEmail';
}
}
class SelectableEmails
{
protected $emails;
public function setSelectableEmails($selectableEmails)
{
$this->emails = $selectableEmails;
}
public function getSelectableEmails()
{
return $this->emails;
}
}
class SelectableEmail
{
protected $id;
protected $selected;
public function getId()
{
return $this->id;
}
public function setId($id)
{
$this->id = $id;
}
public function getSelected()
{
return $this->selected;
}
public function setSelected($selected)
{
$this->selected = (Boolean)$selected;
}
}
答案 0 :(得分:0)
您没有指定data_class
属性,以便将表单映射到正确的对象。
默认情况下,它会期望一个数组,一个\ ArrayAccess实例或一个标量值。
因此,您应该添加以下代码:
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'MyProject\Email\SelectableEmail',
));
}
查看the Symfony's official website的详细信息,搜索data_class
。