Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom choices list of sonata_type_model field with Sonata Admin

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'

like image 318
Raúl Avatar asked Aug 28 '13 08:08

Raúl


2 Answers

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

like image 194
Raúl Avatar answered Oct 22 '22 18:10

Raúl


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.

like image 8
TautrimasPajarskas Avatar answered Oct 22 '22 18:10

TautrimasPajarskas