I have this Entity defined:
You can also use the property accessor into your form:
->add('categoryDescription', 'collection',
array(
'type' => new CategoriesDescriptionType(),
'allow_add' => true,
'options' => array('data_class' => 'Apw\BlackbullBundle\Entity\CategoriesDescription'),
'by_reference' => false,
))
And add 'property' => 'name'
in your CategoriesDescriptionType.
By the way the @CoachNono answer is ok too.
For Symfony 3.x
According with Symfony docs v3.x you should use choice_label property to specify the entity field name to be used here.
->add('categoryDescription', 'collection',
array(
'type' => new CategoriesDescriptionType(),
'allow_add' => true,
'options' => array('data_class' => 'Apw\BlackbullBundle\Entity\CategoriesDescription'),
'choice_label' => 'name',
'by_reference' => false,
))
You need to implement the __toString()
method in your Apw\BlackbullBundle\Entity\CategoriesDescription
.
You could do:
public function __toString() {
return $this->name;
}
so I solved the problem by get the value of relative parent in the method $form->isValid()
public function createCategoryAction(Request $request){
$category = new Categories();
$categoryDesc = new CategoriesDescription();
$category->addCategoryDescription($categoryDesc);
$categoryDesc->setCategory($category);
$form = $this->createForm(new CategoriesType(), $category);
$form->handleRequest($request);
if($form->isValid()){
//exit(\Doctrine\Common\Util\Debug::dump($parentCategory->getId()));
$em = $this->getDoctrine()->getManager();
if(!$category->getParentId()){
$category->setParentId(0);
}else{
// get parent id value from input choice
$parent = $category->getParentId();
$parentCategory = $parent->getCategory();
// end
$category->setParentId($parentCategory->getId());
}
$em->persist($category);
$em->persist($categoryDesc);
$em->flush();
return $this->redirect($this->generateUrl('apw_blackbull_categories_showcategories'));
}
return array(
'form' => $form->createView()
);
}
thanks!
I got the same error but i tweaked it a little bit by adding:
public function __toString()
{
return (string) $this->name;
}
I'm sure i was getting null instead of a string value. (I was working with sonata-project).