Custom choices list of sonata_type_model field with Sonata Admin

Raúl picture Raúl · Aug 28, 2013 · Viewed 29.5k times · Source

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'

Answer

Ra&#250;l picture Raúl · Aug 28, 2013

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