【问题标题】:Symfony Sonata Admin: how get choices array from DBSymfony Sonata Admin:如何从 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
        ));

}

【问题讨论】:

    标签: symfony admin sonata


    【解决方案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;
      }
      
      }
      

      【讨论】:

        猜你喜欢
        • 2015-11-06
        • 1970-01-01
        • 2023-04-01
        • 2018-01-27
        • 1970-01-01
        • 2018-02-11
        • 1970-01-01
        • 2015-05-30
        • 2018-10-25
        相关资源
        最近更新 更多