Note:

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

User:Frédéric Massart: Difference between revisions

From MoodleDocs
No edit summary
No edit summary
(17 intermediate revisions by the same user not shown)
Line 1: Line 1:
== Persistents ==
{{Moodle 3.3}}If you are creating [[Persistent|persistent]] entries from forms, we've got something for you. You can use the class ''core\form\persistent'' as a base for your form instead of ''moodleform''. Our persistent form class comes handy tools, such as automatic validation.


Moodle persistents are equivalent to models (or active records). They represent an object stored in the database and provide the methods to create, read, update, and delete those objects. Additionally, the persistents validate its own data against automatic and custom validation rules.
''Note: for more information about forms themselves, [[:Category:Formslib|head this way]].''


Persistents extend the abstract class ''core\persistent''.
== Linking to a persistent ==


=== Properties ===
In order for the form class to know what persistent we'll be dealing with, we must declare the ''protected static $persistentclass'' variable. The latter contains the fully qualified name of the persistent class.


Defining properties can be done by defining the method ''protected static define_properties()''. It returns an array where the keys are the names of the fields (and database columns), and their details. The ''type'' of each field must be specified using one of the ''PARAM_*'' constants. This type will be used to automatically validate the property's value.
<code php>
 
/** @var string Persistent class name. */
<code>
protected static $persistentclass = 'example\\status';
/**
* Return the definition of the properties of this model.
*
* @return array
*/
protected static function define_properties() {
    return array(
        'userid' => array(
            'type' => PARAM_INT,
        ),
        'message' => array(
            'type' => PARAM_RAW,
        )
    );
}
</code>
</code>


Here we define two mandatory fields, one being a non-null integer, and the other one a non-null free text field. For a complete list of properties
== Defining the form fields ==


==== Mandatory properties ====
Unfortunately this is not automatically done for us, so let's add our fields to the ''definition()'' method like you would do for any form.


Four fields are always added to your persistent and should be reflected in your database table. You must not define those properties inThose are:
<code php>
/**
* Define the form.
*/
public function definition() {
    $mform = $this->_form;


;id (non-null integer)
    // User ID.
: The primary key of the record.
    $mform->addElement('hidden', 'userid');
;usermodified (non-null integer)
    $mform->setType('userid', PARAM_INT);
: The user who created/modified the object. It is automatically set.
    $mform->setConstant('userid', $this->_customdata['userid']);
;timecreated (non-null integer)
: The timestamp at which the record was modified. It is automatically set.
;timemodified (non-null integer)
: The timestamp at which the record was modified. It is automatically set, and defaults to 0.


=== Attaching to the database ===
    // Message.
    $mform->addElement('editor', 'message', 'Message');
    $mform->setType('message', PARAM_RAW);


While the persistent class is helpful for database interactions, it does not automatically fetch the properties from the database, nor does it create the tables. You will need to create the table yourself, as well as pointing the persistent to the right class. This can be done by defining the constant ''TABLE''.
    // Location.
    $mform->addElement('text', 'location', 'Location');
    $mform->setType('location', PARAM_ALPHANUMEXT);


<code>
    $this->add_action_buttons();
/** Table name for the persistent. */
}
const TABLE = 'status';
</code>
</code>


The table name must not contain the Moodle prefix. Also it is common practice to always refer to your table use by accessing the constant rather than repeating it.
All of this is pretty standard, except for the ''userid''. When creating a new 'status', we do not want our users to be in control of this value. Therefore we define it as a hidden value which we lock (using ''setConstant'') to the value we created our form with. All the mandatory fields (without a default value) of the persistent need to be added to the form. If your users cannot change their values, then they must be hidden and locked with ''setConstant''.


=== Assigning values to properties ===
Also note that the ''id'' property is not included. It is not required, nor recommended, to add it to your fields as it will be handled automatically.


Before even saving our object, we must find out how to assign values to our object's properties. There are 3 methods to do so.
== Using the form ==


You can pass an object (''stdClass'') as the second argument of the constructor. The object's properties will be assigned to the new instance.
When instantiating the form, there are two little things that you need to pay attention to.  


<code>
Firstly you should always pass the URL of the current page, including its query parameters. We need this to be able to display the form with its validation errors without affecting anything else.
// Instantiates a new object with value for some properties.
$data = (object) array('userid' => 2, 'message' => 'Hello world!');
$persistent = new status(0, $data);
</code>


Or you can use the ''set()'' method on an instance.
Secondly, the persistent instance must be provided to the form through the custom data. That persistent instance will be used to populate the form with initial data, typically when you are editing an object. When you don't have a persistent instance yet, probably because your user will be creating a new one, then simply pass null.


<code>
<code php>
// Instantiates a blank object.
$customdata = [
$persistent = new status();
    'persistent' => $persistent,  // An instance, or null.
    'userid' => $USER->id        // For the hidden userid field.
];
$form = new status_form($PAGE->url->out(false), $customdata);
</code>


// Assign a new value to the 'message' property.
Just like any other form, we will be using ''get_data()'' to validate the form. The only difference is that to determine whether we are editing an object, or creating a new one, we will check if the ''id'' value was returned to us. The persistent form will return the ID value from the persistent we gave it. Then it's up to you to decide how to apply the data, most likely you will defer the logic to another part of your code, one that ensures that all capability checks are fulfilled.
$persistent->set('message', Hello new world!');
</code>


Finally you can use the magic setters 'set_' followed by the property name.
<code php>
// Get the data. This ensures that the form was validated.
if (($data = $form->get_data())) {


<code>
    if (empty($data->id)) {
// Instantiates a blank object.
        // If we don't have an ID, we know that we must create a new record.
$persistent = new status();
        // Call your API to create a new persistent from this data.
        // Or, do the following if you don't want capability checks (discouraged).
        $persistent = new status(null, $data);
        $persistent->create();
    } else {
        // We had an ID, this means that we are going to update a record.
        // Call your API to update the persistent from the data.
        // Or, do the following if you don't want capability checks (discouraged).
        $persistent->from_record($data);
        $persistent->update();
    }


// Assign a new value to the 'message' property.
    // We are done, so let's redirect somewhere.
$persistent->set_message('Hello new world!');
    redirect(new moodle_url('/'));
}
</code>
</code>


==== Defining your own setter ====
== Additional validation ==


Though you don't have to for the code to work, you can define your own ''setter'' methods which will override the magic setters. They are useful if you want to extract the data out of a more complex object prior to assigning it. Though note that those setters will then have to use the ''set()'' method to assign the values.
There are times when the built-in validation of the persistent is not enough. Usually you would use the method ''validation()'', but as the form persistent class does some extra stuff to make it easier for you, you must use the ''extra_validation()'' method. The latter works almost just like the ''validation()'' one.


<code>
<code php>
/**
/**
  * Convenience method to set the user ID.
  * Extra validation.
  *
  *
  * @param object|int $idorobject The user ID, or a user object.
  * @param stdClass $data Data to validate.
* @param  array $files Array of files.
* @param  array $errors Currently reported errors.
* @return array of additional errors, or overridden errors.
  */
  */
public function set_userid($idorobject) {
protected function extra_validation($data, $files, array &$errors) {
     $userid = $idorobject;
     $newerrors = array();
     if (is_object($idorobject)) {
 
         $userid = $idorobject->id;
     if ($data->location === 'SFO') {
         $newerrors['location'] = 'San-Francisco Airport is not accepted from the form.';
     }
     }
     $this->set('userid', $userid);
 
     return $newerrors;
}
}
</code>
</code>


In the above example we will accept an object or an ID, as a convenience for developers we will extract the ID value out of the object passed if any.
The typical additional validation will return an array of errors, those will override any previously defined errors. Sometimes, though rarely, you will need to remove previously reported errors, hence the reference to ''$errors'' given, which you can modify directly. Do not abuse it though, this should only be used when you have no other choice.


Note that you cannot guarantee that your setter will be used. Developers can directly call the ''set()'' method. Therefore you must not use a custom setter to reliably transform any data added to a property. For instance do not add a custom setter to remove HTML tags out of a text field, it may not always happen.
== Foreign fields ==


You can obviously create your own setters which aren't based on any properties just as a convenience. For instance we could have created ''set_userid_from_user(object $user)'' which is more verbose and more predictable
By default, the form class tries to be smart at detecting foreign fields such as the submit button. Failure to do so will cause troubles during validation, or when getting the data. So when your form becomes more complex, if it includes more submit buttons, or when it deals with other fields, for example file managers, we must indicate it.


=== Read, save and delete entries ===
=== Fields to ignore completely ===


The methods to ''create'', ''read'', ''update'' and ''delete'' are eponymous. Your object will be validated before you ''create'' or ''update'' it. The ''update'', ''delete'' and ''read'' methods require your object to contain its ID. And you also won't be allowed to ''create'' an entry which already had an ID defined.
The fields to remove are never validated and they are not returned when calling ''get_data()''. By default the submit button is added to this list so that when we call ''get_data()'' we only get the persistent-related fields. To remove more fields, re-declare the ''protected static $fieldstoremove'' class variable.


Here are some code examples:
<code php>
/** @var array Fields to remove when getting the final data. */
protected static $fieldstoremove = array('submitbutton', 'areyouhappy');
</code>
 
Do not forget to add the ''submitbutton'' back in there.


<code>
=== Fields to validate ===
// Fetches an object from database based on its ID.
$id = 123;
$persistent = new status($id);
</code>


<code>
What about when we have a ''legit'' field but it does not belong to the persistent? We still want to validate it ourselves, but we don't want it to be validated by the persistent as it will cause an error. In that case we define it in the ''protected static $foreignfields'' class variable.
// Create previously instantiated object in the database.
$persistent->create();
</code>


<code>
<code php>
// Load an object from the database, and update it.
/** @var array Fields to remove from the persistent validation. */
$id = 123;
protected static $foreignfields = array('updatedelay');
$persistent = new status($id);
$persistent->set_message('Hello new world!');
$persistent->update();
</code>
</code>


<code>
Now the persistent will not validate this field, and we will get the ''updatedelay'' value when we call ''get_data()''. Just don't forget to remove it before you feed the data to your persistent.
// Reset the instance to the values in the database.
$persistent->read();
</code>


<code>
<code php>
// Permanently delete the object from the database.
if (($data = $form->get_data())) {
$persistent->delete();
    $updatedelay = $data->updatedelay;
    unset($data->updatedelay);
    $newpersistent = new status(0, $data);
}
</code>
</code>


=== Validating ===
This method is particularily useful when dealing with file managers.


Basic validation of the properties values happens automatically based on their type (''PARAM_*'' constant), however this not always enough. In order to implement your own custom validation, simply define a ''protected'' method starting with ''validate_'' followed with the property name. This method will be called whenever the model needs to be validated and will receive the data to validate.
== Examples ==


A validation method must always return either ''true'' or an instance of ''lang_string'' which contains the error message to send to the user.
=== Minimalist ===


<code>
<code php>
/**
class status_form extends \core\form\persistent {
* Validate the user ID.
   
*
    /** @var string Persistent class name. */
* @param int $value The value.
    protected static $persistentclass = 'example\\status';
* @return true|lang_string
*/
protected function validate_userid($value) {
    global $DB;


     if (!core_user::is_real_user($value, true)) {
     /**
         return new lang_string('invaliduserid', 'error');
    * Define the form.
    }
    */
    public function definition() {
         $mform = $this->_form;


    return true;
        // User ID.
}
        $mform->addElement('hidden', 'userid');
</code>
        $mform->setType('userid', PARAM_INT);
        $mform->setConstant('userid', $this->_customdata['userid']);


The above example ensures that the ''userid'' property contains a valid user ID.
        // Message.
        $mform->addElement('editor', 'message', 'Message');
        $mform->setType('message', PARAM_RAW);


Note that the basic validation is always performed first, and thus your custom validation method will not be called when the value did not pass the basic validation.
        // Location.
        $mform->addElement('text', 'location', 'Location');
        $mform->setType('location', PARAM_ALPHANUMEXT);


==== Validation results ====
        $this->add_action_buttons();
 
    }
The validation of the object automatically happens upon ''create'' and ''update''. If the validation did not pass, an ''invalid_persisten_exception'' will be raised. You can validate the object prior to saving the object and get the validation results if you need to.


<code>
// We can catch the invalid_persistent_exception.
try {
    $persistent = new status();
    $persistent->create();
} catch (invalid_persistent_exception $e) {
    // Whoops, something wrong happened.
}
}
</code>
</code>


<code>
=== More advanced ===
$persistent = new status();


// Whether the object is valid.
<code php>
$persistent->is_valid();        // True or false.
class status_form extends \core\form\persistent {


// Get the validation errors.
    /** @var string Persistent class name. */
$persistent->get_errors();     // Array where keys are properties and values are errors.
    protected static $persistentclass = 'example\\status';


// Validate the object.
    /** @var array Fields to remove when getting the final data. */
$persistent->validate();       // Returns true, or an array of errors.
    protected static $fieldstoremove = array('submitbutton', 'areyouhappy');
</code>


=== Fetching records ===
    /** @var array Fields to remove from the persistent validation. */
    protected static $foreignfields = array('updatedelay');


Once you start using persistents you should never directly interact with the database outside of your class. The persistent class comes with a few handy methods allowing you to retrieve your objects.
    /**
    * Define the form.
    */
    public function definition() {
        $mform = $this->_form;


<code>
        // User ID.
// Use the constructor to fetch one object from its ID.
        $mform->addElement('hidden', 'userid');
$persistent = new status($id);
        $mform->setType('userid', PARAM_INT);
</code>
        $mform->setConstant('userid', $this->_customdata['userid']);


<code>
        // Message.
// Get one record from a set of conditions.
        $mform->addElement('editor', 'message', 'Message');
$persistent = status::get_record(['userid' => $userid, 'message' => 'Hello world!']);
        $mform->setType('message', PARAM_RAW);
</code>


<code>
        // Location.
// Get multiple records from a set of conditions.
        $mform->addElement('text', 'location', 'Location');
$persistents = status::get_records(['userid' => $userid]);
        $mform->setType('location', PARAM_ALPHANUMEXT);
</code>


<code>
        // Status update delay.
// Count the records.
        $mform->addElement('duration', 'updatedelay', 'Status update delay');
$count = status::count_records(['userid' => $userid]);
</code>


<code>
        // Are you happy?
// Check whether a record exists.
        $mform->addElement('selectyesno', 'areyouhappy', 'Are you happy?');
$exists = status::record_exists($id);
</code>


Make sure to also check their additional parameters and their variants (''record_exists_select()'', ''count_records_select'', ''get_records_select'', ...).
        $this->add_action_buttons();
    }


==== Custom fetching ====
    /**
 
    * Extra validation.
It's always a good idea to add more complex queries directly within your persistent. By convention you should always return an instance of your persistent and never an stdClass. Here we add a custom method which allows to directly fetch all records by username.
    *
    * @param  stdClass $data Data to validate.
    * @param  array $files Array of files.
    * @param  array $errors Currently reported errors.
    * @return array of additional errors, or overridden errors.
    */
    protected function extra_validation($data, $files, array &$errors) {
        $newerrors = array();


<code>
        if ($data->location === 'SFO') {
/**
            $newerrors['location'] = 'San-Francisco Airport is not accepted from the form.';
* Get all records by a user from its username
        }
*
* @param string $username The username.
* @return status[]
*/
public static function get_records_by_username($username) {
    global $DB;


    $sql = 'SELECT s.*
         return $newerrors;
              FROM {' . static::TABLE . '} s
              JOIN {user} u
                ON u.id = s.userid
            WHERE u.username = :username';
 
    $persistents = [];
 
    $recordset = $DB->get_recordset_sql($sql, ['username' => $username]);
    foreach ($recordset as $record) {
         $persistents[] = new static(0, $record);
     }
     }
    $recordset->close();
    return $persistents;
}
}
</code>
</code>


=== Hooks ===
=== Using the form ===
 
Consider the following code to be a page you users will access at '/example.php'.
 
<code php>
require 'config.php';


You can define the following methods to be notified prior to, or after, something happened:
// Check if we go an ID.
$id = optional_param('id', null, PARAM_INT);


;before_validate()
// Set the PAGE URL (and mandatory context). Note the ID being recorded, this is important.
: Do something before the object is validated.
$PAGE->set_context(context_system::instance());
;before_create()
$PAGE->set_url(new moodle_url('/example.php', ['id' => $id]));
: Do something before the object is inserted in the database. Note that values assigned to properties are not longer validated at this point.
;after_create()
: Do something right after the object was added to the database.
;before_update()
: Do something before the object is updated in the database. Note that values assigned to properties are not longer validated at this point.
;after_update(bool $result)
: Do something right after the object was updated in the database.
;before_delete()
: Do something right before the object is deleted from the database.
;after_delete(bool $result)
: Do something right after the object was deleted from the database.


=== Full example ===
// Instantiate a persistent object if we received an ID. Typically receiving an ID
// means that we are going to be updating an object rather than creating a new one.
$persistent = null;
if (!empty($id)) {
    $persistent = new status($id);
}


<code>
// Create the form instance. We need to use the current URL and the custom data.
class status extends persistent {
$customdata = [
    'persistent' => $persistent,
    'userid' => $USER->id        // For the hidden userid field.
];
$form = new status_form($PAGE->url->out(false), $customdata);


    /** Table name for the persistent. */
// Get the data. This ensures that the form was validated.
    const TABLE = 'status';
if (($data = $form->get_data())) {


     /**
     if (empty($data->id)) {
    * Return the definition of the properties of this model.
        // If we don't have an ID, we know that we must create a new record.
    *
        // Call your API to create a new persistent from this data.
    * @return array
        // Or, do the following if you don't want capability checks (discouraged).
    */
         $persistent = new status(null, $data);
    protected static function define_properties() {
        $persistent->create();
         return array(
    } else {
            'userid' => array(
        // We had an ID, this means that we are going to update a record.
                'type' => PARAM_INT,
        // Call your API to update the persistent from the data.
            ),
        // Or, do the following if you don't want capability checks (discouraged).
            'message' => array(
        $persistent->from_record($data);
                'type' => PARAM_RAW,
         $persistent->update();
            )
         );
     }
     }


    // We are done, so let's redirect somewhere.
    redirect(new moodle_url('/'));
}
}
// Display the mandatory header and footer.
// And display the form, and its validation errors if there are any.
echo $OUTPUT->header();
$form->display();
echo $OUTPUT->footer();
</code>
</code>

Revision as of 07:58, 16 December 2016

Moodle 3.3 If you are creating persistent entries from forms, we've got something for you. You can use the class core\form\persistent as a base for your form instead of moodleform. Our persistent form class comes handy tools, such as automatic validation.

Note: for more information about forms themselves, head this way.

Linking to a persistent

In order for the form class to know what persistent we'll be dealing with, we must declare the protected static $persistentclass variable. The latter contains the fully qualified name of the persistent class.

/** @var string Persistent class name. */ protected static $persistentclass = 'example\\status';

Defining the form fields

Unfortunately this is not automatically done for us, so let's add our fields to the definition() method like you would do for any form.

/**

* Define the form.
*/

public function definition() {

   $mform = $this->_form;
   // User ID.
   $mform->addElement('hidden', 'userid');
   $mform->setType('userid', PARAM_INT);
   $mform->setConstant('userid', $this->_customdata['userid']);
   // Message.
   $mform->addElement('editor', 'message', 'Message');
   $mform->setType('message', PARAM_RAW);
   // Location.
   $mform->addElement('text', 'location', 'Location');
   $mform->setType('location', PARAM_ALPHANUMEXT);
   $this->add_action_buttons();

}

All of this is pretty standard, except for the userid. When creating a new 'status', we do not want our users to be in control of this value. Therefore we define it as a hidden value which we lock (using setConstant) to the value we created our form with. All the mandatory fields (without a default value) of the persistent need to be added to the form. If your users cannot change their values, then they must be hidden and locked with setConstant.

Also note that the id property is not included. It is not required, nor recommended, to add it to your fields as it will be handled automatically.

Using the form

When instantiating the form, there are two little things that you need to pay attention to.

Firstly you should always pass the URL of the current page, including its query parameters. We need this to be able to display the form with its validation errors without affecting anything else.

Secondly, the persistent instance must be provided to the form through the custom data. That persistent instance will be used to populate the form with initial data, typically when you are editing an object. When you don't have a persistent instance yet, probably because your user will be creating a new one, then simply pass null.

$customdata = [

   'persistent' => $persistent,  // An instance, or null.
   'userid' => $USER->id         // For the hidden userid field.

]; $form = new status_form($PAGE->url->out(false), $customdata);

Just like any other form, we will be using get_data() to validate the form. The only difference is that to determine whether we are editing an object, or creating a new one, we will check if the id value was returned to us. The persistent form will return the ID value from the persistent we gave it. Then it's up to you to decide how to apply the data, most likely you will defer the logic to another part of your code, one that ensures that all capability checks are fulfilled.

// Get the data. This ensures that the form was validated. if (($data = $form->get_data())) {

   if (empty($data->id)) {
       // If we don't have an ID, we know that we must create a new record.
       // Call your API to create a new persistent from this data.
       // Or, do the following if you don't want capability checks (discouraged).
       $persistent = new status(null, $data);
       $persistent->create();
   } else {
       // We had an ID, this means that we are going to update a record.
       // Call your API to update the persistent from the data.
       // Or, do the following if you don't want capability checks (discouraged).
       $persistent->from_record($data);
       $persistent->update();
   }
   // We are done, so let's redirect somewhere.
   redirect(new moodle_url('/'));

}

Additional validation

There are times when the built-in validation of the persistent is not enough. Usually you would use the method validation(), but as the form persistent class does some extra stuff to make it easier for you, you must use the extra_validation() method. The latter works almost just like the validation() one.

/**

* Extra validation.
*
* @param  stdClass $data Data to validate.
* @param  array $files Array of files.
* @param  array $errors Currently reported errors.
* @return array of additional errors, or overridden errors.
*/

protected function extra_validation($data, $files, array &$errors) {

   $newerrors = array();
   if ($data->location === 'SFO') {
       $newerrors['location'] = 'San-Francisco Airport is not accepted from the form.';
   }
   return $newerrors;

}

The typical additional validation will return an array of errors, those will override any previously defined errors. Sometimes, though rarely, you will need to remove previously reported errors, hence the reference to $errors given, which you can modify directly. Do not abuse it though, this should only be used when you have no other choice.

Foreign fields

By default, the form class tries to be smart at detecting foreign fields such as the submit button. Failure to do so will cause troubles during validation, or when getting the data. So when your form becomes more complex, if it includes more submit buttons, or when it deals with other fields, for example file managers, we must indicate it.

Fields to ignore completely

The fields to remove are never validated and they are not returned when calling get_data(). By default the submit button is added to this list so that when we call get_data() we only get the persistent-related fields. To remove more fields, re-declare the protected static $fieldstoremove class variable.

/** @var array Fields to remove when getting the final data. */ protected static $fieldstoremove = array('submitbutton', 'areyouhappy');

Do not forget to add the submitbutton back in there.

Fields to validate

What about when we have a legit field but it does not belong to the persistent? We still want to validate it ourselves, but we don't want it to be validated by the persistent as it will cause an error. In that case we define it in the protected static $foreignfields class variable.

/** @var array Fields to remove from the persistent validation. */ protected static $foreignfields = array('updatedelay');

Now the persistent will not validate this field, and we will get the updatedelay value when we call get_data(). Just don't forget to remove it before you feed the data to your persistent.

if (($data = $form->get_data())) {

   $updatedelay = $data->updatedelay;
   unset($data->updatedelay);
   $newpersistent = new status(0, $data);

}

This method is particularily useful when dealing with file managers.

Examples

Minimalist

class status_form extends \core\form\persistent {

   /** @var string Persistent class name. */
   protected static $persistentclass = 'example\\status';
   /**
    * Define the form.
    */
   public function definition() {
       $mform = $this->_form;
       // User ID.
       $mform->addElement('hidden', 'userid');
       $mform->setType('userid', PARAM_INT);
       $mform->setConstant('userid', $this->_customdata['userid']);
       // Message.
       $mform->addElement('editor', 'message', 'Message');
       $mform->setType('message', PARAM_RAW);
       // Location.
       $mform->addElement('text', 'location', 'Location');
       $mform->setType('location', PARAM_ALPHANUMEXT);
       $this->add_action_buttons();
   }

}

More advanced

class status_form extends \core\form\persistent {

   /** @var string Persistent class name. */
   protected static $persistentclass = 'example\\status';
   /** @var array Fields to remove when getting the final data. */
   protected static $fieldstoremove = array('submitbutton', 'areyouhappy');
   /** @var array Fields to remove from the persistent validation. */
   protected static $foreignfields = array('updatedelay');
   /**
    * Define the form.
    */
   public function definition() {
       $mform = $this->_form;
       // User ID.
       $mform->addElement('hidden', 'userid');
       $mform->setType('userid', PARAM_INT);
       $mform->setConstant('userid', $this->_customdata['userid']);
       // Message.
       $mform->addElement('editor', 'message', 'Message');
       $mform->setType('message', PARAM_RAW);
       // Location.
       $mform->addElement('text', 'location', 'Location');
       $mform->setType('location', PARAM_ALPHANUMEXT);
       // Status update delay.
       $mform->addElement('duration', 'updatedelay', 'Status update delay');
       // Are you happy?
       $mform->addElement('selectyesno', 'areyouhappy', 'Are you happy?');
       $this->add_action_buttons();
   }
   /**
    * Extra validation.
    *
    * @param  stdClass $data Data to validate.
    * @param  array $files Array of files.
    * @param  array $errors Currently reported errors.
    * @return array of additional errors, or overridden errors.
    */
   protected function extra_validation($data, $files, array &$errors) {
       $newerrors = array();
       if ($data->location === 'SFO') {
           $newerrors['location'] = 'San-Francisco Airport is not accepted from the form.';
       }
       return $newerrors;
   }

}

Using the form

Consider the following code to be a page you users will access at '/example.php'.

require 'config.php';

// Check if we go an ID. $id = optional_param('id', null, PARAM_INT);

// Set the PAGE URL (and mandatory context). Note the ID being recorded, this is important. $PAGE->set_context(context_system::instance()); $PAGE->set_url(new moodle_url('/example.php', ['id' => $id]));

// Instantiate a persistent object if we received an ID. Typically receiving an ID // means that we are going to be updating an object rather than creating a new one. $persistent = null; if (!empty($id)) {

   $persistent = new status($id);

}

// Create the form instance. We need to use the current URL and the custom data. $customdata = [

   'persistent' => $persistent,
   'userid' => $USER->id         // For the hidden userid field.

]; $form = new status_form($PAGE->url->out(false), $customdata);

// Get the data. This ensures that the form was validated. if (($data = $form->get_data())) {

   if (empty($data->id)) {
       // If we don't have an ID, we know that we must create a new record.
       // Call your API to create a new persistent from this data.
       // Or, do the following if you don't want capability checks (discouraged).
       $persistent = new status(null, $data);
       $persistent->create();
   } else {
       // We had an ID, this means that we are going to update a record.
       // Call your API to update the persistent from the data.
       // Or, do the following if you don't want capability checks (discouraged).
       $persistent->from_record($data);
       $persistent->update();
   }
   // We are done, so let's redirect somewhere.
   redirect(new moodle_url('/'));

}

// Display the mandatory header and footer. // And display the form, and its validation errors if there are any. echo $OUTPUT->header(); $form->display(); echo $OUTPUT->footer();