Drupal 8 MySQL数据库查询

时间:2018-04-12 09:47:45

标签: php mysql drupal-modules drupal-8

我有一个带定义路径的自定义模块。我想查询一个单独的数据库(在localhost中)并通过响应提取这些数据,以便它显示在模块的.twig页面上。

我正在笔记本电脑上使用本地开发环境。只是无法让它工作。我究竟做错了什么?

Controller.php文件:

namespace Drupal\career_pathways\Controller;
use Symfony\Component\HttpFoundation\Response;

class PathwaysController{
 public function getPaths(){
  $response = new Response();

   $con = \Drupal\Core\Database\Database::getConnection('career_pathways','default');
   $sql = query("SELECT * FROM {pathways}");
   $result = $query->execute();

   if ($result) {
     while ($row = $result->fetchAll()) {
       // Do something with:
       $response = array(
         '#theme' => 'career_pathways',
         '#title' => 'Career Pathways',
         '#markup' => 'A Career Without Boundaries',
         '#firstname' => $row['firstname'],
         '#lastname' => $row['lastname'],
         '#role' => $row['role'],
         '#company' => $row['company']
       );
     }
   }
return $response;
}
}

1 个答案:

答案 0 :(得分:1)

要在自定义模板文件中显示路线,您需要执行以下操作

<强> career_pathways.routing.yml

career_pathways.getpaths:
  path: '/getpaths'
  defaults:
    _controller: '\Drupal\career_pathways\Controller\PathwaysController::getPaths'
    _title: 'getPaths'
  requirements:
    _permission: 'access content'

<强> PathwaysController.php

namespace Drupal\career_pathways\Controller;
use Symfony\Component\HttpFoundation\Response;

use Drupal\Core\Controller\ControllerBase;

class PathwaysController extends ControllerBase {
 public function getPaths(){
   $query = \Drupal::database()->query( "SELECT * FROM pathways" );
   $results = $query->fetchAll();
   $processedResults=[];
    :
   Process your result here
    :

   $build = [
     '#theme' => 'career_pathways',
      '#results' => $processedResults,
    ];
    return $build;
  }
}

<强> career_pathways.module

/**
 * Implements hook_theme().
 */
function career_pathways_theme() {
  return [
    'career_pathways' => [
      'variables' => [
        'results' => NULL,
      ],
      'render element' => 'children',
    ],
  ];
}

<强>模板/职业pathways.html.twig

Hi im working
{{results}}

现在,正确加载模板后。添加逻辑并将其传递给$results变量