Development:lib/formslib.php Form Definition
definition()
定义表单中的对象,类型(PARAM_*)、帮助按钮(helpbuttons)等,必须全部包含在表单类中的definition()函数中。
definition() 用于定义表单中的对象 该定义用于输出表单及验证提交的数据. select 和 checkbox 类型的对象仅允许选择特定值.
仅定义在表单中的对象其数据才能被接收为提交数据.
definition() 应包含表单使用到的所有对象, 某些对象可以用 definition_after_data() 删除或调整. 请勿在 definition() 中对
象间的关联条件, 因为 definition() 不依赖于所提交的数据.
require_once("$CFG->libdir/formslib.php");
class simplehtml_form extends moodleform {
function definition() {
global $CFG;
$mform =& $this->_form; // 不要漏掉下划线!
$mform->addElement()... // 添加表单对象
...
} // 函数终结
} // 类终结
使用 Fieldsets 分组表单对象
使用如下代码建立一个类似legend的对象集.
(提示: Moodle的某些风格主题使用如下的CSS在管理员设置页面中关闭了legend: #adminsettings legend {display:none;}
.)
$mform->addElement('header', 'header对象名', get_string('titleforlegened', 'modulename'));
这样,你就不能再使用对象集,虽然实际上这些对象组还是被封装到隐藏的对象集中.
在对象集的最后一个对象使用 moodle_form 的 closeHeaderBefore 方法关闭一个对象集. 创建一个新的对象集将会自动关闭前一个对象集. 仅在
后继对象不再使用对象集时,才需要显式地关闭该对象
(当然,后继对象仍会隐含地关闭) :
$mform->closeHeaderBefore('buttonar');
addElement
使用 addElement 方法添加表单对象. 无论是什么对象类型(text、select、checkbox等)前三个参数总是相同的. 第一个参数是对象类型. 第二
个参数是对象名,即html中表单的对象名. 第三个是表
单标签文字.
实例 :
按钮
$mform->addElement('button', 'intro', get_string("buttonlabel"));
这是一个按钮对象. 提交和取消按钮请参阅 'submit' 对象.
复选框
$mform->addElement('checkbox', 'ratingtime', get_string('ratingtime', 'forum'));
这是一个简单的复选框. 第三个参数是显示于该对象左侧的标签. 第四个参数则是显示在该对象右侧的标签. 可对复选框和单选按钮分组然后在对象右侧创建独立的标签.
第五个参数是对象属性.
高级复选框
$mform->addElement('advcheckbox', 'ratingtime', get_string('ratingtime', 'forum'), 'Label displayed after checkbox', array
('group' => 1), array(0, 1));
类似前面所说的复选框,但有两个重要的扩展:
- 第五个参数是属性数组($attributes), 用于设置<input>对象的HTML属性. 这里, 可以指定一个特定的 'group' 值, 以便赋予该对象一个类
名, 以便对其进行控制,请参阅
- 第六个参数是与复选框的选择/反选状态相关的数组值. 一般复选框没有该值, 实际上
未选择的复选按钮不会被发送.
选择课程文件
$mform->addElement('choosecoursefile', 'mediafile', get_string('mediafile', 'lesson'), array('courseid'=>$COURSE->id));
从课程文件区选择文件. 第四个可选参数是个列表选项.
array('courseid' =>null, //if it is null (default then use global $COURSE
'height' =>500, // height of the popup window
'width' =>750, // width of the popup window
'options' =>'none'); //options string for the pop up window
//eg. 'menubar=0,location=0,scrollbars,resizable'
第五个参数是属性,类似其它对象. 嘴有用的属性如
array('maxlength' => 255, 'size' => 48)
控制文本域的长度或大小 (默认值为 48 )
因为该对象包含按钮和值, 可以按以下方法 addGroupRule() 添加验证规则:
$mform->addGroupRule('elementname', array('value' => array(array(list, of, rule, params, but, fieldname))));
"elementname" 是文件对象名, "value" 是文本域名,"list, of, addrule, params,
but, fieldname" 对应 addRule() 中的功能,忽略第一个域名.
例子 file/url resource type, 使用了
"choosecoursefile" 对象,
使用 addGroupRule() 控制该域的长度最大值 (255):
$mform->addGroupRule('reference', array('value' => array(array(get_string('maximumchars', , 255), 'maxlength', 255,
'client'))));
日期选择器
$mform->addElement('date_selector', 'assesstimefinish', get_string('to'));
这是一个日期选择器. 以下拉列表的方式选择日、月、年. 其四个参数为选项数组, 默认值是 :
array(
'startyear' => 1970,
'stopyear' => 2020,
'timezone' => 99,
'applydst' => true,
'optional' => false
);
可以对一个或多个数组名重新复制,以覆盖其默认值. 也可以使用第五个参数定义对象属性.
日期时间选择器
$mform->addElement('date_time_selector', 'assesstimestart', get_string('from'));
是一组包含日、月、年、时、分下拉列表的选择. 提交时,数据被处理成时间戳,然后传输到 $form->get_data();
第五个参数为数组选项,默认值:
array(
'startyear' => 1970,
'stopyear' => 2020,
'timezone' => 99,
'applydst' => true,
'step' => 5
);
可以对一个或多个数组名重新复制,以覆盖其默认值. 也可以使用第五个参数定义对象属性.
时间间隔
$mform->addElement('duration', 'timelimit', get_string('timelimit', 'quiz'));
用于输入时间间隔. 这是一个组合文本域,可以输入数字,也可以通过下拉列表选择日、小时、分钟或秒.
提交时该值被转换为秒.
第四个参数为选项. 当前仅支持数组选项. 其默认值:
array('optional' => true)
第五个参数与其它对象一样. 最有用的使用方法是
array('size' => 5)
限制文本框的宽度.
文件
文件上传输入框及浏览按钮. 定义如下
$mform->addElement('file', 'attachment', get_string('attachment', 'forum'));
提交及验证后的使用方法:
if ($data = $mform->get_data()) {
...
$mform->save_files($destination_directory);
...
}
如果需要高级功能, 如必选文件、最大上传值或上传文件名,则
$this->set_upload_manager(new upload_manager('attachment', true, false, $COURSE, false, 0, true, true, false));
$mform->addElement('file', 'attachment', get_string('attachment', 'forum'));
$mform->addRule('attachment', null, 'required');
if ($data = $mform->get_data()) {
...
$mform->save_files($destination_directory);
$newfilename = $mform->get_new_filename();
...
}
移植老代码时直接使用上传管理器(upload manager)处理上传文件也是可以的.
需要注意的是 set_upload_manager() 必须在 ddElement('file',..) 之前使用.
Template:Moodle 2.0 2.0版已重写了文件上传的代码,请参阅内部文档. 新的API稳定之后本页面江更新.
文件选择
Template:Moodle 2.0 已用 file 对象替换.
隐藏
$mform->addElement('hidden', 'reply', 'yes');
隐藏对象. 设置对象名 (本例为 reply) 为指定值 (本例为 yes).
html
你可以在Moodle表单中添加任意HTML标记:
$mform->addElement('html', '
');
参 "Question: Can I put a moodleform inside a table td?" 的具体例子.
html编辑器及格式化
$mform->addElement('htmleditor', 'text', get_string('choicetext', 'choice'));
$mform->setType('text', PARAM_RAW);
$mform->addRule('text', null, 'required', null, 'client');
$mform->addElement('format', 'format', get_string('format'));
第四个参数为数组 :
array(
'canUseHtmlEditor'=>'detect',
'rows' => 10,
'cols' => 65,
'width' => 0,
'height'=> 0,
'course'=> 0,
);
//数组中的选项与 print_textarea 中的参数同
//使用 rows 和 cols 选项控制 html 编辑器的大小.
活动成绩
$mform->addElement('modgrade', 'scale', get_string('grade'), false);
这是一个自定义的活动成绩选择. 第四个参数指定是否将无成绩标为0. 该选择框不包含比例.
默认值为 True, 即无成绩选项.
帮助按钮自动添加.
密码
$mform->addElement('password', 'password', get_string('label'), $attributes);
密码对象. 第四个参数为数组或属性值.
非屏蔽密码
Moodle1.9
$mform->addElement('passwordunmask', 'password', get_string('label'), $attributes);
含显示明文密码选项. 第四个参数为数组或属性值.
单选按钮
$radioarray=array();
$radioarray[] = &MoodleQuickForm::createElement('radio', 'yesno', , get_string('yes'), 1, $attributes);
$radioarray[] = &MoodleQuickForm::createElement('radio', 'yesno', , get_string('no'), 0, $attributes);
$mform->addGroup($radioarray, 'radioar', , array(' '), false);
第二个参数命名单选按钮, 组内的按钮名应一样, 以便选择能正确地在按钮间切换. 第四个参数应是表单对象标签
不过一般会被忽略, 因为组对象有自己的标签. 第四个参数是字符串, 显示在对象右侧. 第五个参数是单选按钮的
值. $attributes 可以是字符串或属性数组.
为单个对象添加帮助链接也是可能的, 不过需要自定义的模板. 请参阅. See MDL-15571.
默认设置
使用下面的代码为单选按钮设置默认值 :
$mform->setDefault('yesno', 0);
默认为 'no'.
选择框
$mform->addElement('select', 'type', get_string('forumtype', 'forum'), $FORUM_TYPES, $attributes);
第四个参数为选择框的选项数组. 数组名为选项值, 数组值为选项文本. 第五个参数为属性, 参阅文本对象的属性参数.
多项选择
$select = &$mform->addElement('select', 'colors', get_string('colors'), array('red', 'blue', 'green'), $attributes);
$select->setMultiple(true);
yes / no选择
$mform->addElement('selectyesno', 'maxbytes', get_string('maxattachmentsize', 'forum'));
值 1 为 yes, 0 为 no.
静态
$mform->addElement('static', 'description', get_string('description', 'exercise'),
get_string('descriptionofexercise', 'exercise', $COURSE->students));
这是一个静态对象. 需小心使用, 用于显示静态文本标签块. 第三个参数为标签, 第四个参数为静态文本本身.
submit, reset 及 cancel
//正常使用 use add_action_buttons 来替换以下代码
$buttonarray=array();
$buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
$buttonarray[] = &$mform->createElement('reset', 'resetbutton', get_string('revert'));
$buttonarray[] = &$mform->createElement('cancel');
$mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
$mform->closeHeaderBefore('buttonar');
'Submit' 类对象是表单提交对象, 用于提交表单. 'Reset' 恢复表单数据,不提交. 'Cancel' 取消表单.
get_data()之前用is_cancelled()检查表单是否已被取消; 参看使用例子.
可以将提交和重置按钮命名为 'submitbutton' 和 'resetbutton', 或者其它类似的名字 (不能使用 'submit' 和 'reset').
这样可以避免在 Javascript 中产生冲突.
add_action_buttons($cancel = true, $submitlabel=null);
可以使用帮助功能, Moodle表单在表单后添加所有必须的动作按钮. 布尔值指定包含取消按钮; 指定提交按钮标签 (传递 get_string 的返回值). 默认的提交按钮标签为 get_string('savechanges').
文本
$mform->addElement('text', 'name', get_string('forumname', 'forum'), $attributes);
这是一个简单文本对象. 第四个参数可以是字符串或文本对象属性数组. 以下两行是等效的 :
$attributes='size="20"';
$attributes=array('size'=>'20');
鼓励使用CSS而不是属性样式.
格式化对象用于格式化选择框, 在 html 编辑器中不可选.
第三个参数是 $useHtmlEditor, 默认为空, 意味着若浏览器和用户设置为支持的话, 使用html编辑器.
文本域
$mform->addElement('textarea', 'introduction', get_string("introtext", "survey"), 'wrap="virtual" rows="20"
cols="50"');
这是一个文本域对象. 若需要html编辑器, 请使用 htmleditor 对象. 第四个参数为字符串或属性数组.
recaptcha
Moodle1.9
$mform->addElement('recaptcha', 'recaptcha_field_name', $attributes);
使用 recaptcha 对象可以减少受自动表单程序攻击的风险. 第三个参数为字符串或属性数组. 使用该对象前, 请先从
http://recaptcha.net/api/getkey 获取密钥.
下面的代码检查网站是否支持 recaptcha:
if (!empty($CFG->recaptchapublickey) && !empty($CFG->recaptchaprivatekey)) {
//recaptcha 已启用
}
标记
Moodle 2.0+ only.
$mform->addElement('tags', 'field_name', $lable, $options, $attributes);
用于标记列表, 如博客.
仅 'display' 选项可用, 该选项必须设为以下 MoodleQuickForm_tags 常量之一: ONLYOFFICIAL,
NOOFFICIAL 或 DEFAULTUI. 用于控制是否以简易方式列表正式标记, 或以文本域输入任意标记, 或两者都使用. 默认为两者都使用.
其设置或返回值为标记数组.
添加组
表单库中的 '组(group)' 是对象组, 该组有一个标签, 并显示在同一行.
典型的代码是同一行中包含提交与取消按钮 :
$buttonarray=array();
$buttonarray[] =& $mform->createElement('submit', 'submitbutton', get_string('savechanges'));
$buttonarray[] =& $mform->createElement('submit', 'cancel', get_string('cancel'));
$mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
在添加对象(addELEMENT)中请使用相同的参数($buttonarray). 第三个标签参数总是被忽略(除上述的提交按钮外, 提交按钮中的该参数用做按钮显示文本而不是标签).
下面是一个不好的示例 (请勿在正式代码中使用, 在日期对象中应使用 'optional' => true 选项):
在同一行中放置日期选择器(本身就是一个对象组) 及一个复选框, 需注意的是, 在组中可以使用 'availablefromgroup' 关闭所有对象,
但不能关闭 'availablefromenabled' 控制对象复选框:
$availablefromgroup=array();
$availablefromgroup[] =& $mform->createElement('date_selector', 'availablefrom', '');
$availablefromgroup[] =& $mform->createElement('checkbox', 'availablefromenabled', '', get_string('enable'));
$mform->addGroup($availablefromgroup, 'availablefromgroup', get_string('availablefromdate', 'data'), ' ', false);
$mform->disabledIf('availablefromgroup', 'availablefromenabled');
添加规则
$mform->addRule('elementname', get_string('error'), 'rule type', 'extraruledata', 'server'(default), false, false);
第一个参数是对象名, 第二个参数为显示给用户的错误信息.
第三个参数为规则类型:必填(required), 最大长度(maxlength), 最小长度(minlength), 长度范围(rangelength), email, 正则表达式(regex),
仅字母(lettersonly), 字母数字(alphanumeric), 数字(numeric), 无标点符号(nopunctuation), 非0(nonzero), 复查(callback), 比较(compare).
第四个参数(格式化)是类似最小长度和正则表达式所要求的额外数据.
第五个参数(验证)是输入数据的验证端为服务器或客户, 客户端验证同时也会在服务器端检查.
* @param string $element 对象名 * @param string $message 无效数据的显示信息 * @param string $type 规则类型, 使用 getRegisteredRules() 取得支持的类型 * @param string $format (可选)规则的额外数据 * @param string $validation (可选)验证执行端: "server", "client" * @param boolean $reset 客户端验证: 出现错误时重置表单对象的值 * @param boolean $force 即使表单对象不存在也要强制规则检查
帮助按钮
$mform->setHelpButton('lessondefault', array('lessondefault', get_string('lessondefault', 'lesson'), 'lesson'));
第一个参数是对象名, 第二个参数是传递给weblib.php的帮助按钮的参数数组. 该数组定义如下:
* @param string $page 帮助页面关键词 * @param string $title 链接、鼠标翻转提示、替换文本标记等的标题 * 以'Help with' (或其它同意思的语言)为前缀,后跟 '...' . * @param string $module 定义帮助页面的模块 * @param mixed $image 是否使用帮助图标做链接? (true/false/"both") * @param boolean $linktext true 则在帮助图标后显示标题. * @param string $text 若定义, 则帮助页面显示该文本, 忽略 $page 变量. * @param boolean $return true 则其输出返回字符串, false 则直接显示在当前页面中. * @param string $imagetext 帮助图标的完整文本. 为空时默认使用 help.gif
Make sure you don't set boolean $return to false.
You need to do use this method after addElement();
setDefault
$mform->addElement('select', 'grade', get_string('gradeforsubmission', 'exercise'), $grades);
$mform->setHelpButton('grade', array('grade', get_string('gradeforsubmission', 'exercise'), 'exercise'));
$mform->setDefault('grade', 100);
Set the default of the form value with setDefault($elementname, $value); where elementname is the elementname whose default you
want to set and $value is the default to set. We
set the defaults for the form in definition(). This default is what is used if no data is loaded into the form with set_data();
eg. on display of the form for an 'add' rather
than 'update' function.
disabledIf
For any element or groups of element in a form you can conditionally disable the group or individual element depending on
conditions.
You can use $mform->disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value=null)
- elementname can be a group. If you specify a group all elements in the group will be disabled (if dependentOn is in
elementname group that is ignored and not disabled). These
are the element names you've used as the first argument in addElement or addGroup.
- dependentOn is the actual name of the element as it will appear in html. This can be different to the name used in addGroup
particularly but also addElement where you're
adding a complex element like a date_selector. Check the html of your page. You typically make the depedentOn a checkbox or
select box.
- $condition will be 'notchecked', 'checked', 'noitemselected', 'eq' or, if it is anything else, we test for 'neq'.
- If $condition is 'eq' or 'neq' then we check the value of the dependentOn field and check for equality (==) or nonequality
(!=) in js
- If $condition is 'checked' or 'notchecked' then we check to see if a checkbox is checked or not.
- If $condition is 'noitemselected' then we check to see whether nothing is selected in a dropdown list.
Examples:
// Disable my control unless a checkbox is checked.
$mform->disabledIf('mycontrol', 'somecheckbox');
// Disable my control if a checkbox is checked.
$mform->disabledIf('mycontrol', 'somecheckbox', 'checked');
// Disable my control unless a dropdown has value 42.
$mform->disabledIf('mycontrol', 'someselect', 'eq', 42);
The possible choices here are in the function lockoptionsall in lib/javascript-static.js.
setType
PARAM_* types are used to specify how a submitted variable should be cleaned. These should be used for get parameters such as
id, course etc. which are used to load a page and
also with setType(); method. Every form element should have a type specified except select, radio box and checkbox elements,
these elements do a good job of cleaning themselves
(only specified options are allowed as user input).
Most Commonly Used PARAM_* Types
These are the most commonly used PARAM_* types and their proper uses. More types can be seen in moodlelib.php starting around
line 100.
- PARAM_CLEAN is deprecated and you should try to use a more specific type.
- PARAM_TEXT should be used for cleaning data that is expected to be plain text. It will strip all html tags. But will still let
tags for multilang support through.
- PARAM_NOTAGS should be used for cleaning data that is expected to be plain text. It will strip *all* html type tags. It will
still *not* let tags for multilang support
through. This should be used for instance for email addresses where no multilang support is appropriate.
- PARAM_RAW means no cleaning whatsoever, it is used mostly for data from the html editor. Data from the editor is later cleaned
before display using format_text() function.
PARAM_RAW can also be used for data that is validated by some other way or printed by p() or s().
- PARAM_INT should be used for integers.
- PARAM_ACTION is an alias of PARAM_ALPHA and is used for hidden fields specifying form actions.
References
- [http://web.archive.org/web/20080214041550/http://www.midnighthax.com/quickform.php PEAR HTML QuickForm Getting Started Guide
by Keith Edmunds of Midnighthax.com (via
archive.org as original now dead)]