我想在moodle中创建一个自定义表单并将表单数据存储在数据库表中.我一直在研究moodle表库,但对我来说太复杂了.
有关如何在moodle中创建自定义表单以及将表单数据存储在数据库中的任何帮助或指导或教程或参考指南或电子书将非常感激.
小智 5
你有几种方法可以做到这一点。更清洁的是使用 Form API ( http://docs.moodle.org/dev/Form_API )。
顺便说一下,您可以使用页面 API ( http://docs.moodle.org/dev/Page_API )在本地插件中使用 PHP 轻松创建自己的表单。
这是一个简单的例子:
<?php
require_once('../../config.php');
global $CFG, $PAGE;
$PAGE->set_context(context_system::instance());
$PAGE->set_pagelayout('standard');
$PAGE->set_title('Form name');
$PAGE->set_heading('Form name');
$PAGE->set_url($CFG->wwwroot.'/local/yourform/index.php');
echo $OUTPUT->header();
?>
<form method="post" action="post.php">
... Your form code goes here
</form>
<?php
... Your PHP data handling code
echo $OUTPUT->footer();
?>
Run Code Online (Sandbox Code Playgroud)
将此代码放入 Moodle 根目录下的“本地”目录中的新目录中。例子 :
/moodle/local/yourform/index.php
Run Code Online (Sandbox Code Playgroud)
然后,通过local/yourform/index.php在 Moodle 根 URL 的末尾添加来访问您的表单。
最好使用Form API.这会处理输入验证,预填表格等.
有关详细信息,请参阅:https: //docs.moodle.org/dev/Form_API
亮点经过测试和优化,适用于主要的屏幕阅读器Dragon和JAWS.无表格布局.使用required_param,optional_param和会话密钥安全地处理表单数据.支持客户端验证工具将Moodle帮助按钮添加到表单.使用File_API支持文件存储库支持许多自定义moodle特定和非特定表单元素.添加重复元素.预先添加表单元素组用法要在moodle中创建表单,必须创建扩展moodleform类的类并覆盖表单元素的覆盖定义.
//moodleform is defined in formslib.php
require_once("$CFG->libdir/formslib.php");
class simplehtml_form extends moodleform {
//Add elements to form
public function definition() {
global $CFG;
$mform = $this->_form; // Don't forget the underscore!
$mform->addElement('text', 'email', get_string('email')); // Add elements to your form
$mform->setType('email', PARAM_NOTAGS); //Set type of element
$mform->setDefault('email', 'Please enter email'); //Default value
...
}
//Custom validation should be added here
function validation($data, $files) {
return array();
}
}
Run Code Online (Sandbox Code Playgroud)
然后在您的页面上实例化表单(在本例中为simplehtml_form).
//include simplehtml_form.php
require_once('PATH_TO/simplehtml_form.php');
//Instantiate simplehtml_form
$mform = new simplehtml_form();
//Form processing and displaying is done here
if ($mform->is_cancelled()) {
//Handle form cancel operation, if cancel button is present on form
} else if ($fromform = $mform->get_data()) {
//In this case you process validated data. $mform->get_data() returns data posted in form.
} else {
// this branch is executed if the form is submitted but the data doesn't validate and the form should be redisplayed
// or on the first display of the form.
//Set default data (if any)
$mform->set_data($toform);
//displays the form
$mform->display();
}
Run Code Online (Sandbox Code Playgroud)