Development:lib/formslib.php Form Definition

出自MoodleDocs
於 2009年8月9日 (日) 03:28 由 Hua Wu對話 | 貢獻 所做的修訂
跳到:導覽、​搜尋

Template:Formslib

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));

類似前面所說的複選框,但有兩個重要的擴展:

  1. 第五個參數是屬性數組($attributes), 用於設置<input>對象的HTML屬性. 這裏, 可以指定一個特定的 'group' 值, 以便賦予該對象一個類

名, 以便對其進行控制,請參閱

checkbox controller

  1. 第六個參數是與複選框的選擇/反選狀態相關的數組值. 一般複選框沒有該值, 實際上

未選擇的複選按鈕不會被發送.

選擇課程文件

$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

);

可以對一個或多個數組名重新複製,以覆蓋其默認值. 也可以使用第五個參數定義對象屬性.

時間間隔

Template:Moodle 2.0

       $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

by Keith Edmunds of Midnighthax.com (via

archive.org as original now dead)]