Reputation: 478
i'm facing a problem with a Symfony Form.
I'm specifying the data_class in the formType class as show below :
<?php
namespace myCompany\myBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use myCompany\myBundle\Entity\someEntity;
class someType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
//here my form builder. No problem there...
}
public function getName()
{
return 'aNameForTheServiceToBeCalled';
}
public function setDefautOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'myCompany\myBundle\Entity\someEntity',
'empty_data' => new someEntity()
));
}
}
As this form is declared as a service, i call it this way from the controller :
$form=$this->createForm('aNameForTheServiceToBeCalled');
Then at some point i want to get the posted form data, so i do :
$data = $form->getData();
According to Symfony API documentation:
public mixed getData() : returns the data in the format needed for the underlying object
So i'm expecting $data to be an instance of someEntity.
But apparently i'm wrong because as i'm trying to $em->persist($data); i recieve an error saying :
EntityManager#persist() expects parameter 1 to be an entity object, array given.
So apparently $data is an array, and an instance of someEntity. Thx in advance for your help!
----------------------- NB. i know that instead of calling
$form=$this->createForm('aNameForTheServiceToBeCalled');
from my controller, i could do the following instead :
$someEntity = //... new instance of someEntity, or from a repository, or whatever someEntity managerslike service
$form=$this->createForm('aNameForTheServiceToBeCalled', $someEntity);
but that's exactly what i dont want to do....
Upvotes: 0
Views: 2219
Reputation: 1031
Great, that's it. setDefaultOptions is required, but is deprecated since Symfony 2.6 and to be removed from 3.0 in favor of configureOptions.
Here you are a tip that will allow you a smooth transition from Symfony 2.X to Symfony 3.0 and above:
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$this->configureOptions($resolver);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => YOUR_ENTITY_OR_MODEL_CLASS::class,
'attr' => array(
'id' => $this->getName()
),
'custom_parameters' => [] // Set a Variable that will allow to pass custom parameters from a controller to the type
));
}
Upvotes: 2
Reputation: 478
I had a typo :
public function setDefautOptions(OptionsResolverInterface $resolver)
should have been
public function setDefau**l**tOptions(OptionsResolverInterface $resolver)
L was missing... On how wasting 2 hours for nothing... Thx everyone!
Upvotes: 2