Minimum source for simple form

Re: Minimum source for simple form

by Richard Jones -
Number of replies: 2
Picture of Plugin developers Picture of Testers

I'm pretty new to programming Moodle myself but there is a function (eg):

$this->add_action_buttons($cancel=true, $submitlabel="Save");

The optional parameters determine whether there is a cancel button and what text goes in the submit button.

You add that to the end of the form definition class and it does the work for you.

https://docs.moodle.org/dev/Form_API

In reply to Richard Jones

Re: Minimum source for simple form

by Robin Stark -

Hey, 

Thanks for replying, I noticed that as well and I'm still getting the error, how are you creating the instance of the form?  ie: $mform = new SomeForm();

Thanks, 

Rob

In reply to Robin Stark

Re: Minimum source for simple form

by Richard Jones -
Picture of Plugin developers Picture of Testers

Here's a form (mod_form.php):

require_once("$CFG->libdir/formslib.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
        $this->add_action_buttons();     
    }
}

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
  $mform->display();
}

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.