Bagbyte
Bagbyte

Reputation: 863

Symfony how to extend collection form field

I'm trying to extend collection form in order to render it with its own template...

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

And I use this type in this way:

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

I'm getting the following error:

The form's view data is expected to be of type scalar, array or an instance of \ArrayAccess, but is an instance of class MyApp\MainBundle\Entity\Contact. You can avoid this error by setting the "data_class" option to "MyApp\MainBundle\Entity\Contact" or by adding a view transformer that transforms an instance of class MyApp\MainBundle\Entity\Contact to scalar, array or an instance of \ArrayAccess.

if I use this:

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

It works fine.

I don't want to implement this data_class as suggested...I would like to extend the collection widget

Upvotes: 0

Views: 1143

Answers (1)

Zephyr
Zephyr

Reputation: 1598

Your form definition seems fine and does not need more tinkering. Your problem lies in the instanciation.

From what I see, I believe you instanciate your form more or less that way:

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

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

However, the collection form types do not use a Contact() instance to work but an array of such instances.

Having fed your instanciation with a Contact() instance instead of an array of such objects, your code fails. What you need to do is:

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

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

Although this is what I believe you did, you have not submitted the instanciation code so it remains difficult to tell if I'm right. If your problem persists, I suggest you provide it.

Upvotes: 1

Related Questions