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
請確定 $return 不要使用 false 返回值.
請在addElement()之後使用.
設置默認
$mform->addElement('select', 'grade', get_string('gradeforsubmission', 'exercise'), $grades);
$mform->setHelpButton('grade', array('grade', get_string('gradeforsubmission', 'exercise'), 'exercise'));
$mform->setDefault('grade', 100);
使用 setDefault($elementname, $value) 設置表單對象的默認值; elementname 是設置默認值的表單對象名.
用於設置在 definition() 中定義的表單對象的默認值. 若表單未在 set_data() 中設置值, 則顯示其默認值為新增而非修改值.
條件關閉
對於組中的對象, 可以按條件關閉組或組中的某對象.
可以使用 $mform->disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value=null)
- 對象名可以是組. 若指定組名則組中的所有對象都將關閉 (若組中含 dependentOn 則忽略, 組不關閉).
这是在addElement或addGroup中的第一个参数名.
- dependentOn 是html中出現的實際對象名. 特別地, 可不同於定義類似日期選擇器的複合對象 addGroup 或 addElement中的名稱.
请参阅生成的 html 页面. depedentOn 的典型应用是在复选框或选择框中.
- $condition 取 'notchecked', 'checked', 'noitemselected', 'eq', 其它值都被當作 'neq'.
- 若 $condition 為 'eq' 或 'neq', 則則 js 中檢查 dependentOn 欄位的值為等於(==)或不等於(!=)
- 若 $condition 為 'checked' 或 'notchecked' 則檢查複選框已被勾選或未被勾選.
- 若 $condition 為 'noitemselected' 則檢查下拉列表中是否未做選擇.
例子:
// 除非勾选复选框,否则不做控制.
$mform->disabledIf('mycontrol', 'somecheckbox');
// 关闭控制, 除非复选框 is 已勾选.
$mform->disabledIf('mycontrol', 'somecheckbox', 'checked');
// 关闭控制, 除非下拉列表的选中值为 42.
$mform->disabledIf('mycontrol', 'someselect', 'eq', 42);
可能的選項在 lib/javascript-static.js 中的 lockoptionsall 函數中定義.
設置類型
PARAM_* 類型定義提交變量如何過濾. 在獲取類似id、課程等中應使用對應的類型, 在裝載頁面及指定類型時都會用到該方法.
所有表單對象都應指定類型, 除select、radio、checkbox 外. 例外的對象自身可以很好地過濾數據(因為使用者只能輸入特定選項).
最常用的 PARAM_* 類型
有些 PARAM_* 類型是最為常用的, 其使用方式也是固定的. 更多類型可以參看 moodlelib.php, 前大約100行起.
- PARAM_CLEAN 不使用, 應使用其它特定類型.
- PARAM_TEXT 僅接受普通文本, 刪除所有 html 標誌, 但允許多語言支持標誌.
- PARAM_NOTAGS 用於純普通文本, 刪除所有 html 標誌, 不支持多. 適用於無多語言支持的email地址.
- PARAM_RAW 意味著不做任何過濾, 最常用於 html 編輯器. 從編輯器接收的數據在其後顯示時, 應使用 format_text() 函數顧慮.
PARAM_RAW 也可以用于其它验证方式或由 p() 或 s() 输出.
- PARAM_INT 用於數字.
- PARAM_ACTION PARAM_ALPHA 的別名, 用於特定表單動作的隱藏欄位.
參考
- [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)]