如何使用条令(symfony4)从mysql数据库获取数据到datatable中?

2sbarzqh  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(331)

像这样,我的表是从数组中填充的数据:

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/0bf4881c934fbecf72f2dfcacd2983196c8daa02d77f67fcdf0fee9f33e4.php的第185行调用

9cbw7uwe

9cbw7uwe1#

根据文件(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;

相关问题