Symfony Sonata Admin:如何从 DB 中获取选择数组

Posted

技术标签:

【中文标题】Symfony Sonata Admin:如何从 DB 中获取选择数组【英文标题】:Symfony Sonata Admin: how get choices array from DB 【发布时间】:2019-05-03 07:29:12 【问题描述】:

如何从 DB 中获取所有值 parent_id

$category = $this->getSubject();

protected function configureFormFields(FormMapper $formMapper)


    $fieldOptions = array(); //how get all value `parent_id` from DB

    $formMapper->add('parent_id', ChoiceType::class, array(
            'expanded' => true,
            'multiple' => false,

            'choices' => $fieldOptions,
            'data' => $category->parent_id
        ));


【问题讨论】:

【参考方案1】:

如果“父”是一个实体(可能是Category),您可能需要查看EntityType。否则,您的代码需要更多上下文。该 sn-p 位于哪个类或文件中?

【讨论】:

【参考方案2】:

答案:

class CategoryAdmin extends AbstractAdmin


    $category = $this->getSubject();

    protected function configureFormFields(FormMapper $formMapper)
    

    $em = $this->modelManager->getEntityManager(Category::class);
    $fieldOptions = $em->getRepository(Category::class)->getChoiceParentId();

    $formMapper->add('parent_id', ChoiceType::class, array(
        'multiple' => false,
        'choices' => array_flip($fieldOptions),
        'data' => $category->parent_id
    ));

    




class CategoryRepository extends ServiceEntityRepository


public function getChoiceParentId()


    $categories = $this->createQueryBuilder('c')
        ->select('c.id, c.name')
        ->getQuery()
        ->getResult();

    $choice_parent_id = [0 => 'Empty'];

    foreach ($categories as $category) 
        $choice_parent_id[$category['id']] = $category['name'];
    

    return $choice_parent_id;



【讨论】:

以上是关于Symfony Sonata Admin:如何从 DB 中获取选择数组的主要内容,如果未能解决你的问题,请参考以下文章

Symfony & Sonata:如何将 javascript 添加到实体管理表单?

如何在 Sonata Admin(Symfony 3.3、PHP 7)中使用自定义 javascript 为模态窗口扩展模板?

Symfony - Sonata-Admin 菜单组翻译

Sonata admin bundle:从全局搜索中排除自定义管理员

Symfony 3 Sonata Admin 使用注释创建管理员

Symfony 4 + Sonata + Sonata Doctrine ORM Admin Bundle:错误:没有要处理的元数据类