Reputation: 431
I am using Sonata Admin and I have a field of categories and I need to show them in order like a tree in select:
<select>
<option>Category father-1</option>
<option>--Category child-1-1</option>
<option>--Category child-1-2</option>
<option>--Category child-1-3</option>
<option>----Category child-1-3-1</option>
<option>----Category child-1-3-2</option>
<option>--Category child-1-4</option>
<option>--...</option>
<option>Category father-2</option>
</select>
It's possible? I have tried it including in 'choice_list' an array generate in getTreeCatsArray method:
protected function configureFormFields(FormMapper $formMapper)
{
$tree_cat_array = $this->em->getRepository('MyBundle:Category')->getTreeCatsArray();
$formMapper
->add('category', 'sonata_type_model', array(
'empty_value' => '',
'choice_list' => $tree_cat_array));
}
This shows the error:
The option "choice_list" with value "Array" is expected to be of type "null", "Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface"
I am not sure if I must use field type 'sonata_type_model' or 'choice'
Upvotes: 13
Views: 31194
Reputation: 431
OK, I've got the list of categories ordered in tree to include it in the related entity as follows:
protected function configureFormFields(FormMapper $formMapper)
{
$em = $this->modelManager->getEntityManager('MyBundle\Entity\Category');
$query = $em->createQueryBuilder('c')
->select('c')
->from('MyBundle:Category', 'c')
->where('c.parent IS NOT NULL')
->orderBy('c.root, c.lft', 'ASC');
$formMapper
...
->add('categoria', 'sonata_type_model', array(
'required' => true,
'query' => $query
))
...
;
}
I hope it can help someone
Upvotes: 29
Reputation: 2607
Afterreading the above answers I had to do the following to get the functionality the OP was after:
protected function configureFormFields(FormMapper $formMapper)
{
$em = $this->modelManager->getEntityManager('YourBundleFile\YourBundleFileBundle\Entity\YourEntity');
$qb = $em->createQueryBuilder();
$qb = $qb->add('select', 'u')
->add('from', 'YourBundleFile\YourBundleFileBundle\Entity\YourEntity u');
$query = $qb->getQuery();
$arrayType = $query->getArrayResult();
$formMapper
->add('yourProperty', 'choice', array('choices'=>$arrayType))
-end();
}
Upvotes: 0
Reputation: 2796
Try:
->add('category', 'entity', array(
'class' => 'Acme\Entity\Category',
)
This will work only if you have entity Category
.
See this article about creating a tree editor for Category
entity for SonataAdminBundle. Here is the same article in Russian, but contains missing code in the first variant.
Upvotes: 8