Eh ma non so perchè non ci riesco.
Accedendo al metodo findAll del repository di Category, ottengo il mio array di entità.
Lo passo al metodo add entity, ma mi risponde con questo errore a mio avviso poco comprensibile .
"A "__toString()" method was not found on the objects of type "Acme\DemoBundle\Entity\Category" passed to the choice field. To read a custom getter instead, set the argument $labelPath to the desired property path. "
Codice PHP:
public function createAction(Request $request)
{
$book = new Book();
//$category = $this->getDoctrine()
// ->getRepository('AcmeDemoBundle:Category')
// ->findAllReturnArray();
$category = $this->getDoctrine()
->getRepository('AcmeDemoBundle:Category')
->findAll();
//dump($category);exit();
$form = $this->createFormBuilder($book)
->add('title', 'text')
->add('isbn', 'text')
->add('author', 'text')
->add('description', 'textarea')
->add('price', 'text')
/* //Metodo 1 Select con array
/*->add('categoryId', 'choice', array('choices' => $category,
'required' => false)
)*/
//Metodo 2 Select con entity
->add('caterogyId', 'entity', array(
'class' => 'AcmeDemoBundle:Category',
'choices' => $category))
/* // Metodo 3 select tramite query builder
->add('categoryId', 'entity', array('class' => 'AcmeDemoBundle:Category',
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('cat')
->orderBy('cat.id', 'ASC');
},
))*/
->add('save', 'submit', array('label' => 'Crea libro'))
->getForm();
$form->handleRequest($request);
if ($form->isValid()) {
//inserisco manualmente l'autore per semplificare l'esempio
$em = $this->getDoctrine()->getManager();
//$category = $em->getRepository('AcmeDemoBundle:Category')->find(1);
//$book->setCategoryId($category);
$em->persist($book);
$em->flush();
return $this->redirect($this->generateUrl('_book'));
}