Note:

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

Blocks Advanced: Difference between revisions

From MoodleDocs
No edit summary
Line 209: Line 209:
$mform->addGroup($radioarray, 'radioar', get_string('pictureselect', 'block_simplehtml'), array(' '), FALSE);
$mform->addGroup($radioarray, 'radioar', get_string('pictureselect', 'block_simplehtml'), array(' '), FALSE);
</code>
</code>
A group is also added to capture multiple form elements on one line. Another approach would be to just display each radio element on its own line.
====Alt Text Input====
Finally, to wrap-up the image display selection, allow the user to choose the alternate text that will be displayed with the selected image.
<code php>
// add description field
$attributes = array('size' => '50', 'maxlength' => '100');
$mform->addElement('text', 'description', get_string('picturedesc', 'block_simplehtml'), $attributes);
$mform->setType('description', PARAM_TEXT);
</code>
Note that there is an attributes variable added to the text field to limit its size and length. The setAdvanced() function adds advanced options to a form. To use this function pass in the name of the form element, group of elements, or header. The "Advanced Options" button appears in the upper right corner of the fieldset. In this example, there is a single element, but later you'll see an element within a header. Learn more about setAdvanced. The"Show/Hide Advanced" button won't be displayed until adding action buttons to the form during the next step of this tutorial.
====Date Time Selector====
Now add the date field as an optional element:
<code php>
// add optional grouping
$mform->addElement('header', 'optional', get_string('optional', 'form'), null, false);
</code>
<code php>
// add date_time selector in optional area
$mform->addElement('date_time_selector', 'displaydate', get_string('displaydate', 'block_simplehtml'), array('optional' => true));
$mform->setAdvanced('optional');
</code>
The above code adds a form header and sets it to hide the date/time selector within the optional (advanced) form controls.
===Add State Variables and Finalize the Form===
====Adding Form Buttons====
Most moodle forms have a basic set of buttons. "Submit" and "Cancel" are added by calling the moodleform member function add_action_buttons(). Add the following at the end of simplehtml_form.php

Revision as of 06:19, 5 April 2012

Introduction

This is a continuation of the simpleHTML block example.

Adding forms

The next thing that we want to do is add a form to create a simpleHTML page.

We are going to create two pages - view.php and simplehtml_form.php All of our logic will be contained in view.php and simplehtml_form.php will just display the form elements.

Create a new file in the blocks/simplehtml directory called simplehtml_form.php. Add the following code: require_once("$CFG->libdir/formslib.php");

class simplehtml_form extends moodleform {

   function definition() {
       
       $mform =& $this->_form;
       $mform->addElement('header','displayinfo', get_string('textfields', 'block_simplehtml'));
   }

} Now let's create view.php.

Create a new file in the blocks/simplehtml directory called view.php. In this file add the following code:

<?php

require_once('../../config.php'); require_once('simplehtml_form.php');

global $DB;

// Check for all required variables. $courseid = required_param('courseid', PARAM_INT);


if (!$course = $DB->get_record('course', array('id' => $courseid))) {

   print_error('invalidcourse', 'block_simplehtml', $courseid);

}

require_login($course);

$simplehtml = new simplehtml_form();

$simplehtml->display(); ?> Next we will add a link from our block to this page so that we can see what we have created.

In the get_content() method of our block_simplehtml class replace $this->content->footer = 'Footer here...'; with global $COURSE

// The other code.

$url = new moodle_url('blocks/simplehtml/view.php', array('blockid' => $this->instance->id, 'courseid' => $COURSE->id)); $this->content->footer = html_writer::link($url, get_string('addpage', 'block_simplehtml'));

Add a Header

If you visit the page now you will see a very basic non-themed form without any of the necessary navigational structure. Note that this happens because the form processing page, in this case view.php, is being accessed directly via the URL and not by being included in another page. This means that the necessary infrastructure must be added directly to the script. Add this by using the print_header function, but a few pieces of data are needed to build appropriate navigation. Make the following adjustments to view.php:


In the global declaration: global $DB, $OUTPUT, $PAGE; After require_login($course); $PAGE->set_url('/blocks/simplehtml/view.php', array('id' => $courseid)); $PAGE->set_pagelayout('standard'); $PAGE->set_heading(get_string('edithtml', 'block_simplehtml')); One last lot of code to add. The following lines should be added after $simplehtml = new simplehtml_form(); echo $OUTPUT->header(); $simplehtml->display(); echo $OUTPUT->footer();

Navigation breadcrumbs

To really make this look like it's a part of moodle we will add the navigation breadcrumbs to the header of our page.

Add the following after $courseid = required_param('courseid', PARAM_INT); $blockid = required_param('blockid', PARAM_INT);

// Next look for optional variables. $id = optional_param('id', 0, PARAM_INT); Then add the following after the header code $settingsnode = $PAGE->settingsnav->add(get_string('simplehtmlsettings', 'block_simplehtml')); $editurl = new moodle_url('/blocks/simplehtml/view.php', array('id' => $id, 'courseid' => $courseid, 'blockid' => $blockid)); $editnode = $settingsnode->add(get_string('editpage', 'block_simplehtml'), $editurl); $editnode->make_active(); Don't forget to include definitions for the new strings that you are creating, into block_simplehtml.php

Form State Control

Now to add some basic form state control: The first step is to setup the appropriate actions based on the form state, accounting for three scenarios:

  1. to display a form for the first time
  2. to process submitted form data
  3. the user has canceled the form submission

To implement these three scenarios adjust the code a bit. The existing form display and header code will be used as the first time display code, and an if statement added after instantiating the simplehtml_form object will handle the logic behind the application flow: if($simplehtml->is_cancelled()) {

   // Cancelled forms redirect to the course main page.
   $courseurl = new moodle_url('course/view.php', array('id' => $id));
   redirect($courseurl);

} else if ($simplehtml->get_data()) {

   // We need to add code to appropriately act on and store the submitted data
   // but for now we will just redirect back to the course main page.
   $courseurl = new moodle_url('course/view.php', array('id' => $courseid));
   redirect($courseurl);

} else {

   // form didn't validate or this is the first display
   $site = get_site();
   echo $OUTPUT->header();
   $simplehtml->display();
   echo $OUTPUT->footer();

} Notice that the existing header and form display code have been moved into the third branch of the conditional. Also, there isn't any code to handle form processing. That code will be added shortly.

Final Steps

Reviewing the progress so far:

  1. simplehtml_form.php is created which defines the class used later to display our form.
  2. view.php is created which:
    • loads base moodle API and any necessary third party modules or non-base API files.
    • loads the necessary course object and globals.
    • performs necessary access control.
    • loads our form and branches execution appropriately based on our form state.

So the form class is defined and the form is displayed in a separate file. Adding elements to the form and finishing the processing of our form will wrap it up!

Add Form Elements

Currently there are no form elements which can submit data. Editing the form class definition in simplehtml_form.php will change that by adding a wide set of form elements to the form for demonstrative purposes only. This will give an example of how to add and process various form elements.

To add the link title text field and the displaytext HTML area to the form, paste the following text after the creation of the form object in the simplehtml_form.php file: // add group for text areas $mform->addElement('header','displayinfo', get_string('textfields', 'block_simplehtml'));

// add page titel element. $mform->addElement('text', 'pagetitle', get_string('pagetitle', 'block_simplehtml')); $mform->addRule('pagetitle', null, 'required', null, 'client');

// add display text field $mform->addElement('htmleditor', 'displaytext', get_string('displayedhtml', 'block_simplehtml')); $mform->setType('displaytexttext', PARAM_RAW); $mform->addRule('displaytext', null, 'required', null, 'client'); For full details on addElement() review the moodle documentation on addElement. Also review addRule() in moodle's documentation and the PEAR web site. PEAR is an included form processing library that moodle uses for form processing.

Now add additional form elements to simplehtml_form.php:

File Upload

Add the file field to the form after the existing elements: // add filename selection. $mform->addElement('filepicker', 'filename', get_string('file'), null, array('accpeted_types' => '*')); his field allows the user to choose a file in the course file directory. Notice that the name of the element in the form is the same name as the field in the database. This will make it easy to insert and update the database records later.

Fieldset Header

// add picture fields grouping $mform->addElement('header', 'picfield', get_string('picturefields', 'block_simplehtml'), null, false);

Yes/No Select

// add display picture yes / no option $mform->addElement('selectyesno', 'displaypicture', get_string('displaypicture', 'block_simplehtml')); $mform->setDefault('displaypicture', 1);

Radio Select

To control the available options, create a function that will return the list of available options as an array keyed by an integer. This is preferred for several reasons:

  • It keeps the database free from enum field types by providing data key by integers. This is database engine independent.
  • It makes it easy to add additional options at a later date by changing our function
  • It avoids the use of global variables.

Create a file lib.php and place the following code into it which will define the image options via radio select. function block_simplehtml_images() {

   return array(html_writer::tag('img', , array('alt' => get_string('red', 'block_simplehtml'), 'src' => "pix/picture0.gif")),
               html_writer::tag('img', , array('alt' => get_string('blue', 'block_simplehtml'), 'src' => "pix/picture1.gif")),
               html_writer::tag('img', , array('alt' => get_string('green', 'block_simplehtml'), 'src' => "pix/picture2.gif")));

} Now include the above file in any files that need to use the function, for now this is just simplehtml_form.php. Add the following after require_once("$CFG->libdir/formslib.php"); in simplehtml_form.php require_once($CFG->dirroot.'/blocks/simplehtml/lib.php'); You now need to add some pictures to the pix directory. In this example I have three gif images each a different colour, but you could use any image (small is better). Create a directory called pix in your simplehtml block directory. Now add the radio select to the form definition (simplethml_form.php) // add image selector radio buttons $images = block_simplehtml_images(); $radioarray = array(); for ($i = 0; $i < count($images); $i++) {

   $radioarray[] =& $mform->createElement('radio', 'picture', , $images[$i], $i);

} $mform->addGroup($radioarray, 'radioar', get_string('pictureselect', 'block_simplehtml'), array(' '), FALSE); A group is also added to capture multiple form elements on one line. Another approach would be to just display each radio element on its own line.

Alt Text Input

Finally, to wrap-up the image display selection, allow the user to choose the alternate text that will be displayed with the selected image. // add description field $attributes = array('size' => '50', 'maxlength' => '100'); $mform->addElement('text', 'description', get_string('picturedesc', 'block_simplehtml'), $attributes); $mform->setType('description', PARAM_TEXT); Note that there is an attributes variable added to the text field to limit its size and length. The setAdvanced() function adds advanced options to a form. To use this function pass in the name of the form element, group of elements, or header. The "Advanced Options" button appears in the upper right corner of the fieldset. In this example, there is a single element, but later you'll see an element within a header. Learn more about setAdvanced. The"Show/Hide Advanced" button won't be displayed until adding action buttons to the form during the next step of this tutorial.

Date Time Selector

Now add the date field as an optional element:

// add optional grouping

$mform->addElement('header', 'optional', get_string('optional', 'form'), null, false);

// add date_time selector in optional area

$mform->addElement('date_time_selector', 'displaydate', get_string('displaydate', 'block_simplehtml'), array('optional' => true)); $mform->setAdvanced('optional'); The above code adds a form header and sets it to hide the date/time selector within the optional (advanced) form controls.

Add State Variables and Finalize the Form

Adding Form Buttons

Most moodle forms have a basic set of buttons. "Submit" and "Cancel" are added by calling the moodleform member function add_action_buttons(). Add the following at the end of simplehtml_form.php