首页 > 解决方案 > 如何使用学说(Symfony 4)从 mysql 数据库中获取数据到数据表中?

问题描述

像这样我的表是从一个数组填充数据:

  public function showAction(Request $request)
  {

    $table = $this->createDataTable()
    ->add('firstName', TextColumn::class)
    ->add('lastName', TextColumn::class)
    ->createAdapter(ArrayAdapter::class, [
      ['firstName' => 'Cat', 'lastName' => 'Duck'],
      ['firstName' => 'Monkey', 'lastName' => 'Dog'],
    ])
    ->handleRequest($request);

    if ($table->isCallback()) {
      return $table->getResponse();
    }

    return $this->render('list.html.twig', ['datatable' => $table]);
  }

但我需要的是直接从 mySQL 数据库中获取数据。我用教义试过这个:

 public function showAction(Request $request)
  {
    $articles = $this->getDoctrine()->getRepository(Article::class)->findAll()->handleRequest($request);

    if ($articles ->isCallback()) {
      return $articles ->getResponse();
    }

    return $this->render('list.html.twig', ['datatable' => $articles]);
  }

但我得到一个错误:

未捕获的 PHP 异常 Symfony\Component\Debug\Exception\FatalThrowableError:“调用数组上的成员函数 handleRequest()”,位于 /Users/work/project/src/Controller/DataTableController.php 第 27 行

我也试着这样写:

  public function showAction(Request $request)
  {
    $articles = $this->getDoctrine()->getRepository(Article::class)->findAll();

    return $this->render('list.html.twig', ['datatable' => $articles]);
  }

但在这里我得到了错误:

传递给 Omines\DataTablesBundle\Twig\DataTablesExtension::Omines\DataTablesBundle\Twig{closure}() 的参数 1 必须是 Omines\DataTablesBundle\DataTable 的实例,给定数组,在 /Users/work/project/var/cache/ 中调用dev/twig/0b/0bf4881c934fbecf72f2dfcacd298733196c8daa0e22d77f67fcdf0fee9f33e4.php 在第 185 行

标签: phpmysqlsymfonydatatabledoctrine

解决方案


根据文档(https://omines.github.io/datatables-bundle/#doctrine-orm

在您的第一个示例中,您需要这样做:

public function showAction(Request $request)
{
    $table = $this->createDataTable()
    ->add('firstName', TextColumn::class)
    ->add('lastName', TextColumn::class)
    ->createAdapter(ORMAdapter::class, [
        'entity' => Article::class,
    ])
    ->handleRequest($request);

    if ($table->isCallback()) {
        return $table->getResponse();
    }

    return $this->render('list.html.twig', ['datatable' => $table]);
}

不要忘记在课堂上添加这个:

use Omines\DataTablesBundle\Adapter\Doctrine\ORMAdapter;

推荐阅读