General developer forum

Minimum source for simple form

Richard Jones
Re: Minimum source for simple form
Particularly helpful MoodlersPlugin developersTesters

Here's a form (mod_form.php):

 * Example form
class mod_form extends moodleform{
     * Defines forms elements
    public function definition() {
        $mform = $this->_form;
        // Adding header (use get_string appropriately to your module)
        $mform->addElement('header', 'general', 'lang string header');
        // Adding standard text field
        $mform->addElement('text', 'name', 'language string here', array('size'=>'64'));
       // IMPORTANT: add validation and type rules as per documentation

Here's a use case (from the dev docs - Form_API) in view.php:

$mform = new mod_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.
  //displays the form

I coded both these in Moodle's root and it displays a form.  Of course you need to do quite a bit more standard Moodle coding (page, context, etc) to make it usable in your plugin but hopefully this shows there's nothing particularly complicated about creating and using a simple form.

Average of ratings: -