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
m (Text replacement - "<code php>" to "<syntaxhighlight lang="php">")
 
(8 intermediate revisions by 2 users not shown)
Line 1: Line 1:
{{Moodle 3.3}}Moodle exporters are classes which receive data and serialise it to a simple pre-defined structure. They ensure that the format of the data exported is uniform and easily maintainable. They are also used to generate the signature (parameters and return values) of [[External functions API|external functions]].
{{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.


== Introduction ==
''Note: for more information about forms themselves, [[:Category:Formslib|head this way]].''


When dealing with external functions (Ajax, web services, ...) and rendering methods we often hit a situation where the same object is used, and exported, from multiple places. When that situation arises, the code that serialises our objects gets duplicated, or becomes inconsistent.
== Linking to a persistent ==


We made the exporters to remedy to this situation. An exporter clearly defines what data it exports, and contains the logic which transform the incoming data into the exported data. As it knows everything, it can generate the structure required by external functions automatically.
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.


This means that not only developers have less code to maintain, but they also have a more robust structure which can easily evolve with their needs. If a new property needs to be exported, it is simply added to the exporter class, and automatically all usage of the exporter inherit this added property.
<syntaxhighlight lang="php">
/** @var string Persistent class name. */
protected static $persistentclass = 'example\\status';
</syntaxhighlight>


== Defining properties ==
== Defining the form fields ==


The method ''define_properties()'' returns a list of the properties expected for the incoming data, and for the exported data. This also means that to create (or update) you will require those 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.


<code php>
<syntaxhighlight lang="php">
/**
/**
  * Return the list of properties.
  * Define the form.
*
* @return array
  */
  */
protected static function define_properties() {
public function definition() {
     return array(
     $mform = $this->_form;
        'id' => array(
 
            'type' => PARAM_INT
    // User ID.
        ),
    $mform->addElement('hidden', 'userid');
        'username' => array(
    $mform->setType('userid', PARAM_INT);
            'type' => PARAM_ALPHANUMEXT
    $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();
}
}
</code>
</syntaxhighlight>


Although this is not a ''rule'', it is recommended that the ''standard properties'' (by opposition to [[#Additional_properties|additional properties]]) only use the ''type'' [[#Property_attributes|attribute]], and with ''PARAM_*'' constants only.
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''.


== Using an exporter ==
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.


Once we've got a [[#Minimalist|minimalist exporter]] set-up, here is how to use it.
== Using the form ==


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


<code php>
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.
$data = (object) ['id' => 123, 'username' => 'batman'];


// The only time we can give data to our exporter is when instantiating it.
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.
$ue = new user_exporter($data);


// To export, we must pass the reference to a renderer.
<syntaxhighlight lang="php">
$data = $ue->export($OUTPUT);
$customdata = [
</code>
    'persistent' => $persistent,  // An instance, or null.
    'userid' => $USER->id        // For the hidden userid field.
];
$form = new status_form($PAGE->url->out(false), $customdata);
</syntaxhighlight>


If we print the content of ''$data'', we will obtain this:
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.


<code>
<syntaxhighlight lang="php">
stdClass Object
// Get the data. This ensures that the form was validated.
(
if (($data = $form->get_data())) {
    [id] => 123
    [username] => batman
)
</code>


=== In external functions ===
    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();
    }


Let's imagine that we have an external function ''get_users'' which returns a list of users. For now we only want to export the user ID and their user name, so we'll use our exporter. Let's ask our exporter to create the external structure for us:
    // We are done, so let's redirect somewhere.
    redirect(new moodle_url('/'));
}
</syntaxhighlight>


<code php>
== Additional validation ==
public static function get_users_returns() {
 
    return external_multiple_structure(
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.
        user_exporter::get_read_structure()
    );
}
</code>


Now that this is done, we must use our exporter as shown above to export our users' data.
<syntaxhighlight lang="php">
/**
* 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();


<code php>
    if ($data->location === 'SFO') {
public static function get_users() {
         $newerrors['location'] = 'San-Francisco Airport is not accepted from the form.';
    global $DB, $PAGE;
    $output = $output = $PAGE->get_renderer('core');
    $users = $DB->get_records('user', null, '', 'id, username', 0, 10); // Get 10 users.
    $result = [];
    foreach ($users as $userdata) {
         $exporter = new user_exporter($userdata);
        $result[] = $exporter->export($output);
     }
     }
     return $result;
 
     return $newerrors;
}
}
</code>
</syntaxhighlight>
 
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.


Lastly, if you had another external function to create users, you could use the exporter to get the structure of the incoming data. That helps if you want your external functions to require more information to create your ''users'' as your needs grow.
=== Fields to ignore completely ===


<code php>
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.
public static function create_user_parameters() {
 
    return new external_function_parameters([
<syntaxhighlight lang="php">
        'user' => user_exporter::get_create_structure()
/** @var array Fields to remove when getting the final data. */
    ]);
protected static $fieldstoremove = array('submitbutton', 'areyouhappy');
}
</syntaxhighlight>


public static function create_user($user) {
Do not forget to add the ''submitbutton'' back in there.
    // Mandatory parameter validation.
    $params = self::validate_parameters(self::create_user_parameters(), ['user' => $user]);
    $user = $params['user'];
    ...
}
</code>


Important note: when used in the ''parameters'', the exporter's structure must always be included in an argument, above we used ''user''. Else this would not flexible, and may not generate a valid structure for some protocols.
=== Fields to validate ===


== Abiding to text formatting rules ==
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.


If we had to pass the ''$OUTPUT'' during export as seen above, that is because we are handling the text formatting automatically for you. Remember the functions ''format_text()'' and ''format_string()''? They are used to apply [[Filters|filters]] on the content typically submitted by users, but also to convert it from a few given formats to HTML.
<syntaxhighlight lang="php">
/** @var array Fields to remove from the persistent validation. */
protected static $foreignfields = array('updatedelay');
</syntaxhighlight>


Upon export, the exporter looks at the ''type'' of all your properties. When it finds a property of type ''PARAM_TEXT'', it will use ''format_string()''. However, if it finds a property using ''PARAM_RAW'' and there is another property of the same name but ending with ''format'' it will use ''format_text()''.
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.


<code php>
<syntaxhighlight lang="php">
'description' => array(
if (($data = $form->get_data())) {
     'type' => PARAM_RAW,
     $updatedelay = $data->updatedelay;
),
    unset($data->updatedelay);
'descriptionformat' => array(
    $newpersistent = new status(0, $data);
    'type' => PARAM_INT,
}
),
</syntaxhighlight>
</code>


With the two above properties (not ''other properties'') added, let's see what happens when the user wrote their description on Markdown and we export it.
This method is particularily useful when dealing with file managers.


<code php>
== Examples ==
$data = (object) [
    'id' => 123,
    'username' => 'batman',
    'description' => 'Hello __world__!',
    'descriptionformat' => FORMAT_MARKDOWN
];
$ue = new user_exporter($data);
$data = $ue->export($OUTPUT);
</code>


Unsurprisingly, this is what comes out of it:
=== Minimalist ===


<code>
<syntaxhighlight lang="php">
stdClass Object
class status_form extends \core\form\persistent {
(
      
    [id] => 123
     /** @var string Persistent class name. */
     [username] => batman
     protected static $persistentclass = 'example\\status';
     [description] => <p>Hello <strong>world</strong>!</p>
     [descriptionformat] => 1
)
</code>


Psst... If you're wondering where we get the ''context'' from, look at [[#Related_objects|related objects]].
    /**
    * Define the form.
    */
    public function definition() {
        $mform = $this->_form;


== Additional properties ==
        // User ID.
        $mform->addElement('hidden', 'userid');
        $mform->setType('userid', PARAM_INT);
        $mform->setConstant('userid', $this->_customdata['userid']);


The list of _other_ properties are to be seen as _additional_ properties which do not need to be given to the exporter for it to export them. They are dynamically generated from the data provided (and the [[#Related objects|related objects]], more on that later). For example, if we wanted our exporter to provide the URL to a user's profile, we wouldn't need the developer to pass it beforehand, we could generate it based on the ID which was already provided.
        // Message.
        $mform->addElement('editor', 'message', 'Message');
        $mform->setType('message', PARAM_RAW);


_Other_ properties are only included in the _read_ structure of an object as they are dynamically generated. They are not required, nor needed, to _create_ or _update_ an object.
        // Location.
        $mform->addElement('text', 'location', 'Location');
        $mform->setType('location', PARAM_ALPHANUMEXT);


<code php>
        $this->add_action_buttons();
/**
    }
* Return the list of additional properties.


* @return array
*/
protected static function define_other_properties() {
    return array(
        'profileurl' => array(
            'type' => PARAM_URL
        ),
        'statuses' => array(
            'type' => status_exporter::read_properties_definition(),
            'multiple' => true,
            'optional' => true
        ),
    );
}
}
</code>
</syntaxhighlight>


The snippet above defines that we will always export a URL under the property ''profileurl'', and that we will either export a list of ''status_exporters'', or not. As you can see, the ''type'' can use the ''read'' properties of another exporter which allows exporters to be nested.
=== More advanced ===


=== Property attributes ===
<syntaxhighlight lang="php">
class status_form extends \core\form\persistent {


Each property is configured using the following attributes:
    /** @var string Persistent class name. */
    protected static $persistentclass = 'example\\status';


;type
    /** @var array Fields to remove when getting the final data. */
: The only mandatory attribute. It must either be one of the many PARAM_* constants, or an array of properties.
    protected static $fieldstoremove = array('submitbutton', 'areyouhappy');
;default
: The default value when the value was not provided. When not specified, a value is required.
;null
: Either of the constants NULL_ALLOWED or NULL_NOT_ALLOWED telling if the null value is accepted. This defaults to NULL_NOT_ALLOWED.
;optional
: Whether the property can be omitted completely. Defaults to false.
;multiple
; Whether there will be more one or more entries under this property. Defaults to false.


== Related objects ==
    /** @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']);


== Common misconception ==
        // Message.
        $mform->addElement('editor', 'message', 'Message');
        $mform->setType('message', PARAM_RAW);


# Exporters do not validate your data. They use the properties' attributes to generate the structure required by the [[External functions API]], the latter is responsive for using the structure to validate the data being exported.
        // Location.
        $mform->addElement('text', 'location', 'Location');
        $mform->setType('location', PARAM_ALPHANUMEXT);


== Examples ==
        // Status update delay.
        $mform->addElement('duration', 'updatedelay', 'Status update delay');


=== Minimalist ===
        // Are you happy?
        $mform->addElement('selectyesno', 'areyouhappy', 'Are you happy?');


<code php>
        $this->add_action_buttons();
class user_exporter extends core\external\exporter {
    }


     /**
     /**
     * Return the list of properties.
     * Extra validation.
     *
     *
     * @return array
    * @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 static function define_properties() {
     protected function extra_validation($data, $files, array &$errors) {
         return array(
         $newerrors = array();
            'id' => array(
 
                'type' => PARAM_INT
        if ($data->location === 'SFO') {
            ),
             $newerrors['location'] = 'San-Francisco Airport is not accepted from the form.';
             'username' => array(
        }
                'type' => PARAM_ALPHANUMEXT
 
            ),
         return $newerrors;
         );
     }
     }
}
</syntaxhighlight>


=== Using the form ===
Consider the following code to be a page you users will access at '/example.php'.
<syntaxhighlight lang="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('/'));
}
}
</code>
 
// 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();
</syntaxhighlight>

Latest revision as of 20:33, 14 July 2021

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();