13

我正在使用 Sonata Admin,我有一个类别字段,我需要像选择树一样按顺序显示它们:

<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>

这是可能的?我已经尝试过它,包括在'choice_list'中一个在getTreeCatsArray方法中生成的数组:

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)); 
}

这显示了错误:

The option "choice_list" with value "Array" is expected to be of type "null", "Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface"

我不确定是否必须使用字段类型“sonata_type_model”或“c​​hoice”

4

3 回答 3

29

好的,我已经在树中排序了类别列表,以将其包含在相关实体中,如下所示:

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
        ))
        ...
    ; 
}

我希望它可以帮助某人

于 2013-08-28T17:35:51.707 回答
8

尝试:

->add('category', 'entity', array(
        'class'    => 'Acme\Entity\Category',
)

仅当您拥有 entity 时,这才有效Category

请参阅这篇关于为SonataAdminBundleCategory实体创建树编辑器的文章。是俄语的同一篇文章,但在第一个变体中包含缺失的代码。

于 2013-08-28T10:38:58.610 回答
0

阅读上述答案后,我必须执行以下操作才能获得 OP 所追求的功能:

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();
}
于 2014-04-25T20:03:03.763 回答