You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Moodle中创建Datatable时无法从数据库取数填充表格问题求助

Moodle Datatable数据填充问题修复方案

现有代码核心问题

  • 执行SQL查询获取数据后,立即用$result = new stdClass();覆盖了查询结果,导致后续完全无法拿到数据库返回的词条数据
  • 没有将查询到的数据传递给模板,前端无法渲染Datatable
  • 没有加载Datatable所需的样式和JS依赖

1. 修复后端index.php逻辑

<?php
require_once '../../config.php';
global $USER, $DB,$CFG;

$PAGE->set_url('/local/glossary/index.php');
$PAGE->set_context(context_system::instance());
$PAGE->requires->jquery();
// 加载Datatable依赖,提前将对应静态资源放到local/glossary/assets目录下
$PAGE->requires->css('/local/glossary/assets/datatables.min.css');
$PAGE->requires->js('/local/glossary/assets/datatables.min.js');
$PAGE->requires->js('/local/glossary/assets/glossary.js');
require_login();

$strpagetitle=get_string('glossary','local_glossary');
$strpageheading=get_string('glossary','local_glossary');
$PAGE->set_title($strpagetitle);
$PAGE->set_heading($strpageheading);

// Moodle规范用{}包裹表名,不要硬写mdl_前缀,适配不同站点的表前缀配置
$sql = "SELECT id, term, definition FROM {local_glossary}";
$glossary_data = $DB->get_records_sql($sql);
// 格式化数据适配模板遍历要求
$template_data = [
    'glossary_list' => array_values($glossary_data)
];

echo $OUTPUT->header();
echo $OUTPUT->render_from_template('local_glossary/searchbar', $template_data);
echo $OUTPUT->footer();

2. 调整Mustache模板(local/glossary/templates/searchbar.mustache)

添加Datatable所需的表格结构:

<!-- 原有搜索栏代码保留 -->
<table id="glossaryTable" class="table table-striped">
    <thead>
        <tr>
            <th>ID</th>
            <th>术语</th>
            <th>定义</th>
        </tr>
    </thead>
    <tbody>
        {{#glossary_list}}
        <tr>
            <td>{{id}}</td>
            <td>{{term}}</td>
            <td>{{definition}}</td>
        </tr>
        {{/glossary_list}}
    </tbody>
</table>

3. 编写glossary.js初始化Datatable

$(document).ready(function() {
    $('#glossaryTable').DataTable({
        pageLength: 10,
        // 可自定义排序、搜索、导出等相关配置
    });
});

内容的提问来源于stack exchange,提问作者johan_schmidt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 12:54:00