I am currently learning Symfony 3.2 and have been following along with the documentation on the Symfony site. But I have a bit of an issue with something I am trying to accomplish in relation to to forms, so any pointers would be great!
I have two Entities:
Job:
class Job
{
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(type="string", length=100)
*/
private $job_name;
/**
* @ORM\Column(type="integer")
*/
private $category_id;
And Category:
class Category
{
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(type="string", length=100)
*/
private $category_name;
I also have a form for each of the entities above (CategoryType
and JobType
). In my Job type I would like category_id
to be a drop down with the id's of the category listed inside it.
I followed the documentation here: http://symfony.com/doc/current/reference/forms/types/choice.html And a comment that was asked here: Passing data to buildForm() in Symfony 2.8/3.0
In my JobController
I used Doctrine to fetch all of the results from the category table:
$em = $this->getDoctrine()->getManager();
$categories = $em->getRepository('AppBundle:Category')->findAll();
And I passed $categories into my form in the options array:
$form = $this->createForm('AppBundle\Form\JobType', $job, array('categories' => $categories));
And in my JobType:
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Job',
'categories' => null,
));
}
On my builder I added the ChoiceType::class
to my category_id
and added the options categories to the choices array:
->add('category_id', ChoiceType::class, array(
'choices' => $options['categories'],
'choice_label' => 'category_name',
'choice_value' => 'id',
'placeholder' => 'Assign job to category...',
))
This works OK in terms of how it us loaded into the view, but when I click create (to submit the form) I get the following error:
An exception occurred while executing 'INSERT INTO jobs (job_name, category_id) VALUES (?, ?)' with params ["test", null, {}, null, null]:
Catchable Fatal Error: Object of class AppBundle\Entity\Category could not be converted to string
I'm guessing this has something to do with the value trying to be saved as an object? But I am unsure of how to resolve this or if I am going about it the right way?