简体   繁体   中英

Form view error in Symfony2

In Symfony2, I have a SelectableEmailsType which holds a collection of SelectableEmailType . This simply allows me to have a form with multiple 'id/checkbox' rows.

When I instantiate my form:

$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);

I get a 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 .

Where am I going wrong? Here are my types and the associated models:

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;
    }
}

You didn't specify the data_class property in order to tell the form mapping to the right object. By default, it will expect an array, an instance of \\ArrayAccess or a scalar value.

Therefore, you should add the following code:

use Symfony\Component\OptionsResolver\OptionsResolverInterface;

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'MyProject\Email\SelectableEmail',
    ));
}

See more detail on the Symfony's official website , search for data_class .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM