我有一个带有定义路径的自定义模块。我想查询一个单独的数据库(在本地主机内)并通过响应提取此数据,以便它显示在模块的 .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;
}
}
最佳答案
要在自定义模板文件中显示您的路线,您需要执行以下操作
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',
],
];
}
templates/career-pathways.html.twig
Hi im working
{{results}}
现在,正确加载模板后。添加您的逻辑并将其传递给 $results
变量
关于php - Drupal 8 MySQL数据库查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49793348/