Note:

If you want to create a new page for developers, you should create it on the Moodle Developer Resource site.

lib/formslib.php Usage

From MoodleDocs

Usage of Formslib

Basic Usage in A Normal Page

Generally the structure of a page with a form on it looks this :

require_once('pathtoformdesctiption');
//you'll process some page parameters at the top here and get the info about
//what instance of your module and what course you're in etc. Make sure you
//include hidden variable in your forms which have their defaults set in set_defaults
//which pass these variables from page to page


$mform = new yourmod_formfunction_form();//name of the form you defined in file above.
if ($fromform=$mform->data_submitted()){
//this branch is where you process validated data.

} 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.
    //setup strings for heading
    print_header_simple($streditinga, '',
     "<a href=\"$CFG->wwwroot/mod/$module->name/index.php?id=$course->id\">$strmodulenameplural</a> ->
     $strnav $streditinga", $mform->focus(), "", false);
    //notice use of $mform->focus() above which puts the cursor 
    //in the first form field or the first field with an error.

    //call to print_heading_with_help or print_heading? then :
    
    //put data you want to fill out in the form into array $toform here then :

    $mform->set_defaults($toform);
    $mform->display();
    print_footer($course);

}

Defining Your Form Class

The form class tells us about the structure of the form. It is encouraged for you to put this in file called {function}_form.php probably in the same folder in which the page that uses it is located. The name of your class should be {modname}_{funciton}_form eg. forum_post_form or course_edit_form. These forms will extend class moodleform.

Use Fieldsets to group Form Elements

You use code like this to open a fieldset with a legend.

//-------------------------------------------------------------------------------
        $mform->addElement('header', 'nameforyourheaderelement', get_string('titleforlegened', 'modulename'));

You can't yet nest these visible fieldsets unfortunately. But in fact groups of elements are wrapped in invisible fieldsets.

You close a fieldset with this code. You tell addStopFieldsetElements the element before you wish to end the fieldset. A fieldset is automatically closed if you open a new one. You need to use this code only if you want to close a fieldset and the subsequent form elements are not to be enclosed by a fieldset  :

        //possibly at the start of definition();
	$mform    =& $this->_form;
        $renderer =& $mform->defaultRenderer();


        $renderer->addStopFieldsetElements('buttonar');

Definition

In function defintion() you define what elements etc you want in your form.


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, eq or if it is anything else then 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.
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.
addElement

Use the addElement method to add a an element to a form. The first few arguments are always the same. The first param is the type of the element to add. The second is the elementname to use which is normally the html name of the element in the form. The third is often the text for the label for the element.

Some examples are below :

        $mform->addElement('text', 'name', get_string('forumname', 'forum'));

        $mform->addElement('select', 'type', get_string('forumtype', 'forum'), $FORUM_TYPES);

        $mform->addElement('selectyesno', 'maxbytes', get_string('maxattachmentsize', 'forum'));

        $mform->addElement('modgrade', 'scale', get_string('grade'), false);

        $mform->addElement('checkbox', 'ratingtime', get_string('ratingtime', 'forum'));

        $mform->addElement('date_time_selector', 'assesstimestart', get_string('from'));

        $mform->addElement('date_selector', 'assesstimefinish', get_string('to'));
addGroup

A 'group' in formslib is just a group of elements that will have a label and will be included on one line.

For example typical code to include a submit and cancel button on the same line :

        $buttonarray=array();
        $buttonarray[] = &MoodleQuickForm::createElement('submit', 'submitbutton', get_string('savechanges'));
        $buttonarray[] = &MoodleQuickForm::createElement('submit', 'cancel', get_string('cancel'));
        $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);

You use the same arguments for createElement as you do for addElement. Any label for the element in the third argument is normally ignored (but not in the case of the submit buttons above where the third argument is not for a label but is the text for the button).

Here's an example of putting a date_selector (which is itself a group of elements) and a checkbox on the same line, note that you can disable every element in the group using the group name 'availablefromgroup' but it doesn't disable the controlling element the 'availablefromenabled' checkbox:

        $availablefromgroup=array();
	$availablefromgroup[]=&MoodleQuickForm::createElement('date_selector', 'availablefrom', '');
	$availablefromgroup[]=&MoodleQuickForm::createElement('checkbox', 'availablefromenabled', '', get_string('enable'));
        $mform->addGroup($availablefromgroup, 'availablefromgroup', get_string('availablefromdate', 'data'), ' ', false);
        $mform->disabledIf('availablefromgroup', 'availablefromenabled');

Use in Activity Modules Add / Update Forms

Syntax is the same in activity modules to create your update / add page. We are still supporting mod.html but if you want to use the new formslib then you can in Moodle 1.8 just include in your module directory the file mod_form.php instead of mod.html and it will be automatically detected. Inside this file you define a class with class name '{modname}__mod_form' which extends the class 'moodleform_mod'. See many examples of the core modules which have been converted to use formslib already.

defaults_preprocessing

For activity modules you use the same syntax to define your form. You may also want to override method defaults_preprocessing this can be used to take the data from the data base and tell the form how to fill out defaults in the form with this data. For example in the forum module in forum/mod_form.php we needed to tick an enable check box if a date had been selected in the date select. Normally data is loaded from the database and directly loaded into form fields with the same name as the database record you only need to use defaults_preprocessing if there isn't this one to one relationship. Another example is the lesson/mod_form.php which takes the data from the database and unserializes it. choice/mod_form.php shows an exampe of loading data from another db table referred to by a foreign key, to include in the form.

Post Processing Still Done in lib.php Functions

Post processing of data is done in lib.php functions modname_add_instance and modname_update_instance after the data has been validated. When migrating a from little change needs to be made in the post processing often. An exception is that date and date_time_selector fields automatically have their submitted data turned into timestamps so you don't need to do this in your add and update functions anymore.

Automatically Including Standard Activity Module Form Elements

Standard activity module form elements are automatically included using the moodleform_mod method standard_coursemodule_elements(). The default is to include a visibility and groupsmode select box and to include all necessary hidden fields. You can pass a parameter false to tell the method that your module doesn't support groups and so you don't want the groupsmode select button.