first commit

This commit is contained in:
CHIEFSOFT\ameye
2024-09-30 18:11:26 -04:00
commit e592ca6823
27270 changed files with 5002257 additions and 0 deletions
@@ -0,0 +1,87 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Customfield Checkbox plugin
*
* @package customfield_checkbox
* @copyright 2018 Daniel Neis Araujo <daniel@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace customfield_checkbox;
use core_customfield\api;
use core_customfield\output\field_data;
defined('MOODLE_INTERNAL') || die;
/**
* Class data
*
* @package customfield_checkbox
* @copyright 2018 Daniel Neis Araujo <daniel@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class data_controller extends \core_customfield\data_controller {
/**
* Return the name of the field where the information is stored
* @return string
*/
public function datafield(): string {
return 'intvalue';
}
/**
* Add fields for editing a checkbox field.
*
* @param \MoodleQuickForm $mform
*/
public function instance_form_definition(\MoodleQuickForm $mform) {
$field = $this->get_field();
$config = $field->get('configdata');
$elementname = $this->get_form_element_name();
// If checkbox is required (i.e. "agree to terms") then use 'checkbox' form element.
// The advcheckbox element cannot be used for required fields because advcheckbox elements always provide a value.
$isrequired = $field->get_configdata_property('required');
$mform->addElement($isrequired ? 'checkbox' : 'advcheckbox', $elementname, $this->get_field()->get_formatted_name());
$mform->setDefault($elementname, $config['checkbydefault']);
$mform->setType($elementname, PARAM_BOOL);
if ($isrequired) {
$mform->addRule($elementname, null, 'required', null, 'client');
}
}
/**
* Returns the default value as it would be stored in the database (not in human-readable format).
*
* @return mixed
*/
public function get_default_value() {
return $this->get_field()->get_configdata_property('checkbydefault') ? 1 : 0;
}
/**
* Returns value in a human-readable format
*
* @return mixed|null value or null if empty
*/
public function export_value() {
$value = $this->get_value();
return $value ? get_string('yes') : get_string('no');
}
}
@@ -0,0 +1,94 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Customfields checkbox plugin
*
* @package customfield_checkbox
* @copyright 2018 David Matamoros <davidmc@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace customfield_checkbox;
defined('MOODLE_INTERNAL') || die;
/**
* Class field
*
* @package customfield_checkbox
* @copyright 2018 David Matamoros <davidmc@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class field_controller extends \core_customfield\field_controller {
/**
* Plugin type
*/
const TYPE = 'checkbox';
/**
* Add fields for editing a checkbox field.
*
* @param \MoodleQuickForm $mform
*/
public function config_form_definition(\MoodleQuickForm $mform) {
$mform->addElement('header', 'header_specificsettings', get_string('specificsettings', 'customfield_checkbox'));
$mform->setExpanded('header_specificsettings', true);
$mform->addElement('selectyesno', 'configdata[checkbydefault]', get_string('checkedbydefault', 'customfield_checkbox'));
$mform->setType('configdata[checkbydefault]', PARAM_BOOL);
}
/**
* Validate the data on the field configuration form
*
* @param array $data from the add/edit profile field form
* @param array $files
* @return array associative array of error messages
*/
public function config_form_validation(array $data, $files = array()): array {
$errors = parent::config_form_validation($data, $files);
if ($data['configdata']['uniquevalues']) {
$errors['configdata[uniquevalues]'] = get_string('errorconfigunique', 'customfield_checkbox');
}
return $errors;
}
/**
* Does this custom field type support being used as part of the block_myoverview
* custom field grouping?
* @return bool
*/
public function supports_course_grouping(): bool {
return true;
}
/**
* If this field supports course grouping, then this function needs overriding to
* return the formatted values for this.
* @param array $values the used values that need formatting
* @return array
*/
public function course_grouping_format_values($values): array {
$name = $this->get_formatted_name();
return [
1 => $name.': '.get_string('yes'),
BLOCK_MYOVERVIEW_CUSTOMFIELD_EMPTY => $name.': '.get_string('no'),
];
}
}
@@ -0,0 +1,81 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Privacy Subsystem implementation for customfield_checkbox.
*
* @package customfield_checkbox
* @copyright 2018 Daniel Neis Araujo <danielneis@gmail.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace customfield_checkbox\privacy;
use core_customfield\data_controller;
use core_customfield\privacy\customfield_provider;
use core_privacy\local\request\writer;
defined('MOODLE_INTERNAL') || die();
/**
* Privacy Subsystem for customfield_checkbox implementing null_provider.
*
* @copyright 2018 Daniel Neis Araujo <danielneis@gmail.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class provider implements \core_privacy\local\metadata\null_provider, customfield_provider {
/**
* Get the language string identifier with the component's language
* file to explain why this plugin stores no data.
*
* @return string
*/
public static function get_reason(): string {
return 'privacy:metadata';
}
/**
* Preprocesses data object that is going to be exported
*
* @param data_controller $data
* @param \stdClass $exportdata
* @param array $subcontext
*/
public static function export_customfield_data(data_controller $data, \stdClass $exportdata, array $subcontext) {
writer::with_context($data->get_context())->export_data($subcontext, $exportdata);
}
/**
* Allows plugins to delete everything they store related to the data (usually files)
*
* @param string $dataidstest
* @param array $params
* @param array $contextids
* @return mixed|void
*/
public static function before_delete_data(string $dataidstest, array $params, array $contextids) {
}
/**
* Allows plugins to delete everything they store related to the field configuration (usually files)
*
* @param string $fieldidstest
* @param array $params
* @param array $contextids
*/
public static function before_delete_fields(string $fieldidstest, array $params, array $contextids) {
}
}
@@ -0,0 +1,30 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Customfield checkbox plugin
* @package customfield_checkbox
* @copyright 2018 Toni Barbera <toni@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$string['checkedbydefault'] = 'Checked by default';
$string['errorconfigunique'] = 'The checkbox field cannot be defined as unique.';
$string['pluginname'] = 'Checkbox';
$string['privacy:metadata'] = 'The Checkbox field type plugin doesn\'t store any personal data; it uses tables defined in core.';
$string['specificsettings'] = 'Checkbox field settings';
@@ -0,0 +1,78 @@
@customfield @customfield_checkbox @javascript
Feature: Managers can manage course custom fields checkbox
In order to have additional data on the course
As a manager
I need to create, edit, remove and sort custom fields
Background:
Given the following "custom field categories" exist:
| name | component | area | itemid |
| Category for test | core_course | course | 0 |
And I log in as "admin"
And I navigate to "Courses > Default settings > Course custom fields" in site administration
Scenario: Create a custom course checkbox field
When I click on "Add a new custom field" "link"
And I click on "Checkbox" "link"
And I set the following fields to these values:
| Name | Test field |
| Short name | testfield |
And I click on "Save changes" "button" in the "Adding a new Checkbox" "dialogue"
Then I should see "Test field"
And I log out
Scenario: Edit a custom course checkbox field
When I click on "Add a new custom field" "link"
And I click on "Checkbox" "link"
And I set the following fields to these values:
| Name | Test field |
| Short name | testfield |
And I click on "Save changes" "button" in the "Adding a new Checkbox" "dialogue"
And I click on "Edit" "link" in the "Test field" "table_row"
And I set the following fields to these values:
| Name | Edited field |
And I click on "Save changes" "button" in the "Updating Test field" "dialogue"
Then I should see "Edited field"
And I should not see "Test field"
Scenario: Delete a custom course checkbox field
When I click on "Add a new custom field" "link"
And I click on "Checkbox" "link"
And I set the following fields to these values:
| Name | Test field |
| Short name | testfield |
And I click on "Save changes" "button" in the "Adding a new Checkbox" "dialogue"
And I click on "Delete" "link" in the "Test field" "table_row"
And I click on "Yes" "button" in the "Confirm" "dialogue"
Then I should not see "Test field"
And I log out
Scenario: A checkbox checked by default must be shown on listing but allow uncheck that will keep showing
Given the following "users" exist:
| username | firstname | lastname | email |
| teacher1 | Teacher | Example 1 | teacher1@example.com |
And the following "courses" exist:
| fullname | shortname | format |
| Course 1 | C1 | topics |
And the following "course enrolments" exist:
| user | course | role |
| teacher1 | C1 | editingteacher |
When I click on "Add a new custom field" "link"
And I click on "Checkbox" "link"
And I set the following fields to these values:
| Name | Test field |
| Short name | testfield |
| Checked by default | Yes |
And I click on "Save changes" "button" in the "Adding a new Checkbox" "dialogue"
And I log out
And I log in as "teacher1"
And I am on site homepage
Then I should see "Test field: Yes"
When I am on "Course 1" course homepage
And I navigate to "Settings" in current page administration
And I expand all fieldsets
And I set the field "Test field" to ""
And I press "Save and display"
And I am on site homepage
Then I should see "Test field: No"
And I log out
@@ -0,0 +1,172 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace customfield_checkbox;
use core_customfield_generator;
use core_customfield_test_instance_form;
/**
* Functional test for customfield_checkbox
*
* @package customfield_checkbox
* @copyright 2019 Marina Glancy
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class plugin_test extends \advanced_testcase {
/** @var \stdClass[] */
private $courses = [];
/** @var \core_customfield\category_controller */
private $cfcat;
/** @var \core_customfield\field_controller[] */
private $cfields;
/** @var \core_customfield\data_controller[] */
private $cfdata;
/**
* Tests set up.
*/
public function setUp(): void {
$this->resetAfterTest();
$this->cfcat = $this->get_generator()->create_category();
$this->cfields[1] = $this->get_generator()->create_field(
['categoryid' => $this->cfcat->get('id'), 'shortname' => 'myfield1', 'type' => 'checkbox']);
$this->cfields[2] = $this->get_generator()->create_field(
['categoryid' => $this->cfcat->get('id'), 'shortname' => 'myfield2', 'type' => 'checkbox',
'configdata' => ['required' => 1]]);
$this->cfields[3] = $this->get_generator()->create_field(
['categoryid' => $this->cfcat->get('id'), 'shortname' => 'myfield3', 'type' => 'checkbox',
'configdata' => ['checkbydefault' => 1]]);
$this->courses[1] = $this->getDataGenerator()->create_course();
$this->courses[2] = $this->getDataGenerator()->create_course();
$this->courses[3] = $this->getDataGenerator()->create_course();
$this->cfdata[1] = $this->get_generator()->add_instance_data($this->cfields[1], $this->courses[1]->id, 1);
$this->cfdata[2] = $this->get_generator()->add_instance_data($this->cfields[1], $this->courses[2]->id, 1);
$this->setUser($this->getDataGenerator()->create_user());
}
/**
* Get generator
* @return core_customfield_generator
*/
protected function get_generator(): core_customfield_generator {
return $this->getDataGenerator()->get_plugin_generator('core_customfield');
}
/**
* Test for initialising field and data controllers
*/
public function test_initialise(): void {
$f = \core_customfield\field_controller::create($this->cfields[1]->get('id'));
$this->assertTrue($f instanceof field_controller);
$f = \core_customfield\field_controller::create(0, (object)['type' => 'checkbox'], $this->cfcat);
$this->assertTrue($f instanceof field_controller);
$d = \core_customfield\data_controller::create($this->cfdata[1]->get('id'));
$this->assertTrue($d instanceof data_controller);
$d = \core_customfield\data_controller::create(0, null, $this->cfields[1]);
$this->assertTrue($d instanceof data_controller);
}
/**
* Test for configuration form functions
*
* Create a configuration form and submit it with the same values as in the field
*/
public function test_config_form(): void {
$this->setAdminUser();
$submitdata = (array)$this->cfields[1]->to_record();
$submitdata['configdata'] = $this->cfields[1]->get('configdata');
$submitdata = \core_customfield\field_config_form::mock_ajax_submit($submitdata);
$form = new \core_customfield\field_config_form(null, null, 'post', '', null, true,
$submitdata, true);
$form->set_data_for_dynamic_submission();
$this->assertTrue($form->is_validated());
$form->process_dynamic_submission();
// Try submitting with 'unique values' checked.
$submitdata['configdata']['uniquevalues'] = 1;
$submitdata = \core_customfield\field_config_form::mock_ajax_submit($submitdata);
$form = new \core_customfield\field_config_form(null, null, 'post', '', null, true,
$submitdata, true);
$form->set_data_for_dynamic_submission();
$this->assertFalse($form->is_validated());
}
/**
* Test for instance form functions
*/
public function test_instance_form(): void {
global $CFG;
require_once($CFG->dirroot . '/customfield/tests/fixtures/test_instance_form.php');
$this->setAdminUser();
$handler = $this->cfcat->get_handler();
// First try to submit without required field.
$submitdata = (array)$this->courses[1];
core_customfield_test_instance_form::mock_submit($submitdata, []);
$form = new core_customfield_test_instance_form('POST',
['handler' => $handler, 'instance' => $this->courses[1]]);
$this->assertFalse($form->is_validated());
// Now with required field.
$submitdata['customfield_myfield2'] = 1;
core_customfield_test_instance_form::mock_submit($submitdata, []);
$form = new core_customfield_test_instance_form('POST',
['handler' => $handler, 'instance' => $this->courses[1]]);
$this->assertTrue($form->is_validated());
$data = $form->get_data();
$this->assertNotEmpty($data->customfield_myfield1);
$this->assertNotEmpty($data->customfield_myfield2);
$handler->instance_form_save($data);
}
/**
* Test for data_controller::get_value and export_value
*/
public function test_get_export_value(): void {
$this->assertEquals(1, $this->cfdata[1]->get_value());
$this->assertEquals('Yes', $this->cfdata[1]->export_value());
// Field without data.
$d = \core_customfield\data_controller::create(0, null, $this->cfields[2]);
$this->assertEquals(0, $d->get_value());
$this->assertEquals('No', $d->export_value());
// Field without data that is checked by default.
$d = \core_customfield\data_controller::create(0, null, $this->cfields[3]);
$this->assertEquals(1, $d->get_value());
$this->assertEquals('Yes', $d->export_value());
}
/**
* Deleting fields and data
*/
public function test_delete(): void {
$this->cfcat->get_handler()->delete_all();
}
}
+28
View File
@@ -0,0 +1,28 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Customfield checkbox plugin
* @package customfield_checkbox
* @copyright 2018 Toni Barbera <toni@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$plugin->component = 'customfield_checkbox';
$plugin->version = 2024042200;
$plugin->requires = 2024041600;
@@ -0,0 +1,147 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Customfield date plugin
*
* @package customfield_date
* @copyright 2018 Daniel Neis Araujo <daniel@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace customfield_date;
use core_customfield\api;
defined('MOODLE_INTERNAL') || die;
/**
* Class data
*
* @package customfield_date
* @copyright 2018 Daniel Neis Araujo <daniel@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class data_controller extends \core_customfield\data_controller {
/**
* Return the name of the field where the information is stored
* @return string
*/
public function datafield(): string {
return 'intvalue';
}
/**
* Add fields for editing data of a date field on a context.
*
* @param \MoodleQuickForm $mform
*/
public function instance_form_definition(\MoodleQuickForm $mform) {
$field = $this->get_field();
// Get the current calendar in use - see MDL-18375.
$calendartype = \core_calendar\type_factory::get_calendar_instance();
$config = $field->get('configdata');
// Always set the form element to "optional", even when it's required. Otherwise it defaults to the
// current date and is easy to miss.
$attributes = ['optional' => true];
if (!empty($config['mindate'])) {
$attributes['startyear'] = $calendartype->timestamp_to_date_array($config['mindate'])['year'];
}
if (!empty($config['maxdate'])) {
$attributes['stopyear'] = $calendartype->timestamp_to_date_array($config['maxdate'])['year'];
}
if (empty($config['includetime'])) {
$element = 'date_selector';
} else {
$element = 'date_time_selector';
}
$elementname = $this->get_form_element_name();
$mform->addElement($element, $elementname, $this->get_field()->get_formatted_name(), $attributes);
$mform->setType($elementname, PARAM_INT);
$mform->setDefault($elementname, time());
if ($field->get_configdata_property('required')) {
$mform->addRule($elementname, null, 'required', null, 'client');
}
}
/**
* Validates data for this field.
*
* @param array $data
* @param array $files
* @return array
*/
public function instance_form_validation(array $data, array $files): array {
$errors = parent::instance_form_validation($data, $files);
$elementname = $this->get_form_element_name();
if (!empty($data[$elementname])) {
// Compare the date with min/max values, trim the date to the minute or to the day (depending on inludetime setting).
$includetime = $this->get_field()->get_configdata_property('includetime');
$machineformat = $includetime ? '%Y-%m-%d %H:%M' : '%Y-%m-%d';
$humanformat = $includetime ? get_string('strftimedatetimeshort') : get_string('strftimedatefullshort');
$value = userdate($data[$elementname], $machineformat, 99, false, false);
$mindate = $this->get_field()->get_configdata_property('mindate');
$maxdate = $this->get_field()->get_configdata_property('maxdate');
if ($mindate && userdate($mindate, $machineformat, 99, false, false) > $value) {
$errors[$elementname] = get_string('errormindate', 'customfield_date', userdate($mindate, $humanformat));
}
if ($maxdate && userdate($maxdate, $machineformat, 99, false, false) < $value) {
$errors[$elementname] = get_string('errormaxdate', 'customfield_date', userdate($maxdate, $humanformat));
}
}
return $errors;
}
/**
* Returns the default value as it would be stored in the database (not in human-readable format).
*
* @return mixed
*/
public function get_default_value() {
return 0;
}
/**
* Returns value in a human-readable format
*
* @return mixed|null value or null if empty
*/
public function export_value() {
$value = $this->get_value();
if ($this->is_empty($value)) {
return null;
}
// Check if time needs to be included.
if ($this->get_field()->get_configdata_property('includetime')) {
$format = get_string('strftimedaydatetime', 'langconfig');
} else {
$format = get_string('strftimedate', 'langconfig');
}
return userdate($value, $format);
}
}
@@ -0,0 +1,130 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Customfield date plugin
*
* @package customfield_date
* @copyright 2018 David Matamoros <davidmc@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace customfield_date;
defined('MOODLE_INTERNAL') || die;
/**
* Class field
*
* @package customfield_date
* @copyright 2018 David Matamoros <davidmc@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class field_controller extends \core_customfield\field_controller {
/**
* Type of plugin data
*/
const TYPE = 'date';
/**
* Validate the data from the config form.
*
* @param array $data
* @param array $files
* @return array associative array of error messages
*/
public function config_form_validation(array $data, $files = array()): array {
$errors = array();
// Make sure the start year is not greater than the end year.
if (!empty($data['configdata']['mindate']) && !empty($data['configdata']['maxdate']) &&
$data['configdata']['mindate'] > $data['configdata']['maxdate']) {
$errors['configdata[mindate]'] = get_string('mindateaftermax', 'customfield_date');
}
return $errors;
}
/**
* Add fields for editing a date field.
*
* @param \MoodleQuickForm $mform
*/
public function config_form_definition(\MoodleQuickForm $mform) {
$config = $this->get('configdata');
// Add elements.
$mform->addElement('header', 'header_specificsettings', get_string('specificsettings', 'customfield_date'));
$mform->setExpanded('header_specificsettings', true);
$mform->addElement('advcheckbox', 'configdata[includetime]', get_string('includetime', 'customfield_date'));
$mform->addElement('date_time_selector', 'configdata[mindate]', get_string('mindate', 'customfield_date'),
['optional' => true]);
$mform->addElement('date_time_selector', 'configdata[maxdate]', get_string('maxdate', 'customfield_date'),
['optional' => true]);
$mform->hideIf('configdata[maxdate][hour]', 'configdata[includetime]');
$mform->hideIf('configdata[maxdate][minute]', 'configdata[includetime]');
$mform->hideIf('configdata[mindate][hour]', 'configdata[includetime]');
$mform->hideIf('configdata[mindate][minute]', 'configdata[includetime]');
}
/**
* Does this custom field type support being used as part of the block_myoverview
* custom field grouping?
* @return bool
*/
public function supports_course_grouping(): bool {
return true;
}
/**
* If this field supports course grouping, then this function needs overriding to
* return the formatted values for this.
* @param array $values the used values that need formatting
* @return array
*/
public function course_grouping_format_values($values): array {
$format = get_string('strftimedate', 'langconfig');
$ret = [];
foreach ($values as $value) {
if ($value) {
$ret[$value] = userdate($value, $format);
}
}
if (!$ret) {
return []; // If the only dates found are 0, then do not show any options.
}
$ret[BLOCK_MYOVERVIEW_CUSTOMFIELD_EMPTY] = get_string('nocustomvalue', 'block_myoverview',
$this->get_formatted_name());
return $ret;
}
/**
* Convert given value into appropriate timestamp
*
* @param string $value
* @return int
*/
public function parse_value(string $value) {
$timestamp = strtotime($value);
// If we have a valid, positive timestamp then return it.
return $timestamp > 0 ? $timestamp : 0;
}
}
@@ -0,0 +1,85 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Privacy Subsystem implementation for customfield_date.
*
* @package customfield_date
* @copyright 2018 Daniel Neis Araujo <danielneis@gmail.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace customfield_date\privacy;
use core_customfield\data_controller;
use core_customfield\privacy\customfield_provider;
use core_privacy\local\request\writer;
defined('MOODLE_INTERNAL') || die();
/**
* Privacy Subsystem for customfield_date implementing null_provider.
*
* @copyright 2018 Daniel Neis Araujo <danielneis@gmail.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class provider implements \core_privacy\local\metadata\null_provider, customfield_provider {
/**
* Get the language string identifier with the component's language
* file to explain why this plugin stores no data.
*
* @return string
*/
public static function get_reason(): string {
return 'privacy:metadata';
}
/**
* Preprocesses data object that is going to be exported
*
* @param data_controller $data
* @param \stdClass $exportdata
* @param array $subcontext
*/
public static function export_customfield_data(data_controller $data, \stdClass $exportdata, array $subcontext) {
$context = $data->get_context();
// For date field we want to use PrivacyAPI date format instead of export_value().
$exportdata->value = \core_privacy\local\request\transform::datetime($data->get_value());
writer::with_context($context)
->export_data($subcontext, $exportdata);
}
/**
* Allows plugins to delete everything they store related to the data (usually files)
*
* @param string $dataidstest
* @param array $params
* @param array $contextids
* @return mixed|void
*/
public static function before_delete_data(string $dataidstest, array $params, array $contextids) {
}
/**
* Allows plugins to delete everything they store related to the field configuration (usually files)
*
* @param string $fieldidstest
* @param array $params
* @param array $contextids
*/
public static function before_delete_fields(string $fieldidstest, array $params, array $contextids) {
}
}
@@ -0,0 +1,35 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Customfields date plugin
*
* @package customfield_date
* @copyright 2018 David Matamoros
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$string['errormaxdate'] = 'Please enter a date no later than {$a}.';
$string['errormindate'] = 'Please enter a date on or after {$a}.';
$string['includetime'] = 'Include time';
$string['maxdate'] = 'Maximum value';
$string['mindate'] = 'Minimum value';
$string['mindateaftermax'] = 'The minimum value cannot be bigger than the maximum value.';
$string['pluginname'] = 'Date and time';
$string['privacy:metadata'] = 'The Date and time field type plugin doesn\'t store any personal data; it uses tables defined in core.';
$string['specificsettings'] = 'Date and time field settings';
+35
View File
@@ -0,0 +1,35 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Customfield date plugin
*
* @package customfield_date
* @copyright 2018 Daniel Neis Araujo <daniel@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
/**
* Get icon mapping for font-awesome.
*/
function customfield_date_get_fontawesome_icon_map() {
return [
'customfield_date:checked' => 'fa-check-square-o',
'customfield_date:notchecked' => 'fa-square-o',
];
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 372 B

+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="16px" height="16px" viewBox="0 0 16 16" version="1.1" preserveAspectRatio="xMinYMid meet">
<g id="surface1">
<path style=" stroke:none;fill-rule:nonzero;fill:rgb(60%,60%,60%);fill-opacity:1;" d="M 13.144531 8.304688 L 13.144531 11.144531 C 13.144531 11.851562 12.890625 12.457031 12.386719 12.960938 C 11.886719 13.460938 11.28125 13.714844 10.570312 13.714844 L 3.144531 13.714844 C 2.433594 13.714844 1.828125 13.460938 1.324219 12.960938 C 0.824219 12.457031 0.570312 11.851562 0.570312 11.144531 L 0.570312 3.714844 C 0.570312 3.007812 0.824219 2.398438 1.324219 1.898438 C 1.828125 1.394531 2.433594 1.144531 3.144531 1.144531 L 10.570312 1.144531 C 10.945312 1.144531 11.292969 1.21875 11.617188 1.367188 C 11.707031 1.40625 11.757812 1.476562 11.777344 1.570312 C 11.792969 1.671875 11.769531 1.757812 11.695312 1.832031 L 11.257812 2.269531 C 11.199219 2.328125 11.132812 2.355469 11.054688 2.355469 C 11.035156 2.355469 11.007812 2.351562 10.972656 2.339844 C 10.835938 2.304688 10.703125 2.285156 10.570312 2.285156 L 3.144531 2.285156 C 2.75 2.285156 2.414062 2.425781 2.132812 2.707031 C 1.855469 2.984375 1.714844 3.320312 1.714844 3.714844 L 1.714844 11.144531 C 1.714844 11.535156 1.855469 11.871094 2.132812 12.152344 C 2.414062 12.429688 2.75 12.570312 3.144531 12.570312 L 10.570312 12.570312 C 10.964844 12.570312 11.300781 12.429688 11.582031 12.152344 C 11.859375 11.871094 12 11.535156 12 11.144531 L 12 8.875 C 12 8.796875 12.027344 8.730469 12.082031 8.679688 L 12.652344 8.105469 C 12.710938 8.046875 12.78125 8.019531 12.855469 8.019531 C 12.894531 8.019531 12.929688 8.027344 12.964844 8.042969 C 13.082031 8.09375 13.144531 8.179688 13.144531 8.304688 Z M 15.207031 3.9375 L 7.9375 11.207031 C 7.792969 11.347656 7.625 11.417969 7.429688 11.417969 C 7.230469 11.417969 7.0625 11.347656 6.917969 11.207031 L 3.082031 7.367188 C 2.9375 7.222656 2.867188 7.054688 2.867188 6.855469 C 2.867188 6.660156 2.9375 6.492188 3.082031 6.347656 L 4.0625 5.367188 C 4.207031 5.222656 4.375 5.152344 4.570312 5.152344 C 4.769531 5.152344 4.9375 5.222656 5.082031 5.367188 L 7.429688 7.714844 L 13.207031 1.9375 C 13.347656 1.792969 13.519531 1.722656 13.714844 1.722656 C 13.910156 1.722656 14.082031 1.792969 14.222656 1.9375 L 15.207031 2.917969 C 15.347656 3.0625 15.417969 3.230469 15.417969 3.429688 C 15.417969 3.625 15.347656 3.792969 15.207031 3.9375 Z M 15.207031 3.9375 "/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 266 B

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="16px" height="16px" viewBox="0 0 16 16" version="1.1" preserveAspectRatio="xMinYMid meet">
<g id="surface1">
<path style=" stroke:none;fill-rule:nonzero;fill:rgb(60%,60%,60%);fill-opacity:1;" d="M 11.714844 2.285156 L 4.285156 2.285156 C 3.894531 2.285156 3.554688 2.425781 3.277344 2.707031 C 2.996094 2.984375 2.855469 3.320312 2.855469 3.714844 L 2.855469 11.144531 C 2.855469 11.535156 2.996094 11.871094 3.277344 12.152344 C 3.554688 12.429688 3.894531 12.570312 4.285156 12.570312 L 11.714844 12.570312 C 12.105469 12.570312 12.445312 12.429688 12.722656 12.152344 C 13.003906 11.871094 13.144531 11.535156 13.144531 11.144531 L 13.144531 3.714844 C 13.144531 3.320312 13.003906 2.984375 12.722656 2.707031 C 12.445312 2.425781 12.105469 2.285156 11.714844 2.285156 Z M 14.285156 3.714844 L 14.285156 11.144531 C 14.285156 11.851562 14.035156 12.457031 13.53125 12.960938 C 13.027344 13.460938 12.421875 13.714844 11.714844 13.714844 L 4.285156 13.714844 C 3.578125 13.714844 2.972656 13.460938 2.46875 12.960938 C 1.964844 12.457031 1.714844 11.851562 1.714844 11.144531 L 1.714844 3.714844 C 1.714844 3.007812 1.964844 2.398438 2.46875 1.898438 C 2.972656 1.394531 3.578125 1.144531 4.285156 1.144531 L 11.714844 1.144531 C 12.421875 1.144531 13.027344 1.394531 13.53125 1.898438 C 14.035156 2.398438 14.285156 3.007812 14.285156 3.714844 Z M 14.285156 3.714844 "/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

@@ -0,0 +1,102 @@
@customfield @customfield_date @javascript
Feature: Managers can manage course custom fields date
In order to have additional data on the course
As a manager
I need to create, edit, remove and sort custom fields
Background:
Given the following "custom field categories" exist:
| name | component | area | itemid |
| Category for test | core_course | course | 0 |
And I log in as "admin"
And I navigate to "Courses > Default settings > Course custom fields" in site administration
Scenario: Create a custom course date field
When I click on "Add a new custom field" "link"
And I click on "Date and time" "link"
And I set the following fields to these values:
| Name | Test field |
| Short name | testfield |
And I click on "Save changes" "button" in the "Adding a new Date and time" "dialogue"
Then I should see "Test field"
And I log out
Scenario: Edit a custom course date field
When I click on "Add a new custom field" "link"
And I click on "Date and time" "link"
And I set the following fields to these values:
| Name | Test field |
| Short name | testfield |
And I click on "Save changes" "button" in the "Adding a new Date and time" "dialogue"
And I click on "[data-role='editfield']" "css_element"
And I set the following fields to these values:
| Name | Edited field |
And I click on "Save changes" "button" in the "Updating Test field" "dialogue"
Then I should see "Edited field"
And I log out
Scenario: Delete a custom course date field
When I click on "Add a new custom field" "link"
And I click on "Date and time" "link"
And I set the following fields to these values:
| Name | Test field |
| Short name | testfield |
And I click on "Save changes" "button" in the "Adding a new Date and time" "dialogue"
And I click on "[data-role='deletefield']" "css_element"
And I click on "Yes" "button" in the "Confirm" "dialogue"
Then I should not see "Test field"
And I log out
Scenario: A date field makerd to include time must show those fields on course form
Given the following "users" exist:
| username | firstname | lastname | email |
| teacher1 | Teacher | Example 1 | teacher1@example.com |
And the following "courses" exist:
| fullname | shortname | format |
| Course 1 | C1 | topics |
And the following "course enrolments" exist:
| user | course | role |
| teacher1 | C1 | editingteacher |
When I click on "Add a new custom field" "link"
And I click on "Date and time" "link"
And I set the following fields to these values:
| Name | Test field |
| Short name | testfield |
| Include time | 1 |
And I click on "Save changes" "button" in the "Adding a new Date and time" "dialogue"
And I log out
Then I log in as "teacher1"
When I am on site homepage
When I am on "Course 1" course homepage
And I navigate to "Settings" in current page administration
And I expand all fieldsets
Then "#id_customfield_testfield_hour" "css_element" should be visible
Then "#id_customfield_testfield_minute" "css_element" should be visible
And I log out
Scenario: A date field makerd to not include time must not show those fields on course form
Given the following "users" exist:
| username | firstname | lastname | email |
| teacher1 | Teacher | Example 1 | teacher1@example.com |
And the following "courses" exist:
| fullname | shortname | format |
| Course 1 | C1 | topics |
And the following "course enrolments" exist:
| user | course | role |
| teacher1 | C1 | editingteacher |
When I click on "Add a new custom field" "link"
And I click on "Date and time" "link"
And I set the following fields to these values:
| Name | Test field |
| Short name | testfield |
| Include time | |
And I click on "Save changes" "button" in the "Adding a new Date and time" "dialogue"
And I log out
Then I log in as "teacher1"
When I am on site homepage
When I am on "Course 1" course homepage
And I navigate to "Settings" in current page administration
And I expand all fieldsets
Then "#id_customfield_testfield_hour" "css_element" should not be visible
Then "#id_customfield_testfield_minute" "css_element" should not be visible
And I log out
@@ -0,0 +1,202 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace customfield_date;
use core_customfield_generator;
use core_customfield_test_instance_form;
/**
* Functional test for customfield_date
*
* @package customfield_date
* @copyright 2019 Marina Glancy
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class plugin_test extends \advanced_testcase {
/** @var stdClass[] */
private $courses = [];
/** @var \core_customfield\category_controller */
private $cfcat;
/** @var \core_customfield\field_controller[] */
private $cfields;
/** @var \core_customfield\data_controller[] */
private $cfdata;
/**
* Tests set up.
*/
public function setUp(): void {
$this->resetAfterTest();
$this->cfcat = $this->get_generator()->create_category();
$this->cfields[1] = $this->get_generator()->create_field(
['categoryid' => $this->cfcat->get('id'), 'shortname' => 'myfield1', 'type' => 'date']);
$this->cfields[2] = $this->get_generator()->create_field(
['categoryid' => $this->cfcat->get('id'), 'shortname' => 'myfield2', 'type' => 'date',
'configdata' => ['required' => 1, 'includetime' => 0, 'mindate' => 946684800, 'maxdate' => 1893456000]]);
$this->courses[1] = $this->getDataGenerator()->create_course();
$this->courses[2] = $this->getDataGenerator()->create_course();
$this->courses[3] = $this->getDataGenerator()->create_course();
$this->cfdata[1] = $this->get_generator()->add_instance_data($this->cfields[1], $this->courses[1]->id, 1546300800);
$this->cfdata[2] = $this->get_generator()->add_instance_data($this->cfields[1], $this->courses[2]->id, 1546300800);
$this->setUser($this->getDataGenerator()->create_user());
}
/**
* Get generator
* @return core_customfield_generator
*/
protected function get_generator(): core_customfield_generator {
return $this->getDataGenerator()->get_plugin_generator('core_customfield');
}
/**
* Test for initialising field and data controllers
*/
public function test_initialise(): void {
$f = \core_customfield\field_controller::create($this->cfields[1]->get('id'));
$this->assertTrue($f instanceof field_controller);
$f = \core_customfield\field_controller::create(0, (object)['type' => 'date'], $this->cfcat);
$this->assertTrue($f instanceof field_controller);
$d = \core_customfield\data_controller::create($this->cfdata[1]->get('id'));
$this->assertTrue($d instanceof data_controller);
$d = \core_customfield\data_controller::create(0, null, $this->cfields[1]);
$this->assertTrue($d instanceof data_controller);
}
/**
* Test for configuration form functions
*
* Create a configuration form and submit it with the same values as in the field
*/
public function test_config_form(): void {
$this->setAdminUser();
$submitdata = (array)$this->cfields[1]->to_record();
$submitdata['configdata'] = $this->cfields[1]->get('configdata');
$submitdata = \core_customfield\field_config_form::mock_ajax_submit($submitdata);
$form = new \core_customfield\field_config_form(null, null, 'post', '', null, true,
$submitdata, true);
$form->set_data_for_dynamic_submission();
$this->assertTrue($form->is_validated());
$form->process_dynamic_submission();
}
/**
* Test for instance form functions
*/
public function test_instance_form(): void {
global $CFG;
require_once($CFG->dirroot . '/customfield/tests/fixtures/test_instance_form.php');
$this->setAdminUser();
$handler = $this->cfcat->get_handler();
// First try to submit without required field.
$submitdata = (array)$this->courses[1];
core_customfield_test_instance_form::mock_submit($submitdata, []);
$form = new core_customfield_test_instance_form('POST',
['handler' => $handler, 'instance' => $this->courses[1]]);
$this->assertFalse($form->is_validated());
// Now with required field.
$submitdata['customfield_myfield2'] = time();
core_customfield_test_instance_form::mock_submit($submitdata, []);
$form = new core_customfield_test_instance_form('POST',
['handler' => $handler, 'instance' => $this->courses[1]]);
$this->assertTrue($form->is_validated());
$data = $form->get_data();
$this->assertEmpty($data->customfield_myfield1);
$this->assertNotEmpty($data->customfield_myfield2);
$handler->instance_form_save($data);
}
/**
* Test for min/max date validation
*/
public function test_instance_form_validation(): void {
$this->setAdminUser();
$handler = $this->cfcat->get_handler();
$submitdata = (array)$this->courses[1];
$data = data_controller::create(0, null, $this->cfields[2]);
// Submit with date less than mindate.
$submitdata['customfield_myfield2'] = 915148800;
$this->assertNotEmpty($data->instance_form_validation($submitdata, []));
// Submit with date more than maxdate.
$submitdata['customfield_myfield2'] = 1893557000;
$this->assertNotEmpty($data->instance_form_validation($submitdata, []));
}
/**
* Test for data_controller::get_value and export_value
*/
public function test_get_export_value(): void {
$this->assertEquals(1546300800, $this->cfdata[1]->get_value());
$this->assertStringMatchesFormat('%a 1 January 2019%a', $this->cfdata[1]->export_value());
// Field without data.
$d = \core_customfield\data_controller::create(0, null, $this->cfields[2]);
$this->assertEquals(0, $d->get_value());
$this->assertEquals(null, $d->export_value());
}
/**
* Data provider for {@see test_parse_value}
*
* @return array
*/
public function parse_value_provider(): array {
return [
// Valid times.
['2019-10-01', strtotime('2019-10-01')],
['2019-10-01 14:00', strtotime('2019-10-01 14:00')],
// Invalid times.
['ZZZZZ', 0],
['202-04-01', 0],
['2019-15-15', 0],
];
}
/**
* Test field parse_value method
*
* @param string $value
* @param int $expected
* @return void
*
* @dataProvider parse_value_provider
*/
public function test_parse_value(string $value, int $expected): void {
$this->assertSame($expected, $this->cfields[1]->parse_value($value));
}
/**
* Deleting fields and data
*/
public function test_delete(): void {
$this->cfcat->get_handler()->delete_all();
}
}
+30
View File
@@ -0,0 +1,30 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Customfield date plugin
*
* @package customfield_date
* @copyright 2018 Toni Barbera <toni@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$plugin->component = 'customfield_date';
$plugin->version = 2024042200;
$plugin->requires = 2024041600;
@@ -0,0 +1,121 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Select plugin data controller
*
* @package customfield_select
* @copyright 2018 Daniel Neis Araujo <daniel@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace customfield_select;
defined('MOODLE_INTERNAL') || die;
/**
* Class data
*
* @package customfield_select
* @copyright 2018 Daniel Neis Araujo <daniel@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class data_controller extends \core_customfield\data_controller {
/**
* Return the name of the field where the information is stored
* @return string
*/
public function datafield(): string {
return 'intvalue';
}
/**
* Returns the default value as it would be stored in the database (not in human-readable format).
*
* @return mixed
*/
public function get_default_value() {
$defaultvalue = $this->get_field()->get_configdata_property('defaultvalue');
if ('' . $defaultvalue !== '') {
$key = array_search($defaultvalue, $this->get_field()->get_options());
if ($key !== false) {
return $key;
}
}
return 0;
}
/**
* Add fields for editing a textarea field.
*
* @param \MoodleQuickForm $mform
*/
public function instance_form_definition(\MoodleQuickForm $mform) {
$field = $this->get_field();
$config = $field->get('configdata');
$options = $field->get_options();
$elementname = $this->get_form_element_name();
$mform->addElement('select', $elementname, $this->get_field()->get_formatted_name(), $options);
if (($defaultkey = array_search($config['defaultvalue'], $options)) !== false) {
$mform->setDefault($elementname, $defaultkey);
}
if ($field->get_configdata_property('required')) {
$mform->addRule($elementname, null, 'required', null, 'client');
}
}
/**
* Validates data for this field.
*
* @param array $data
* @param array $files
* @return array
*/
public function instance_form_validation(array $data, array $files): array {
$errors = parent::instance_form_validation($data, $files);
if ($this->get_field()->get_configdata_property('required')) {
// Standard required rule does not work on select element.
$elementname = $this->get_form_element_name();
if (empty($data[$elementname])) {
$errors[$elementname] = get_string('err_required', 'form');
}
}
return $errors;
}
/**
* Returns value in a human-readable format
*
* @return mixed|null value or null if empty
*/
public function export_value() {
$value = $this->get_value();
if ($this->is_empty($value)) {
return null;
}
$options = $this->get_field()->get_options();
if (array_key_exists($value, $options)) {
return $options[$value];
}
return null;
}
}
@@ -0,0 +1,135 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace customfield_select;
use coding_exception;
/**
* Class field
*
* @package customfield_select
* @copyright 2018 David Matamoros <davidmc@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class field_controller extends \core_customfield\field_controller {
/**
* Customfield type
*/
const TYPE = 'select';
/**
* Add fields for editing a select field.
*
* @param \MoodleQuickForm $mform
*/
public function config_form_definition(\MoodleQuickForm $mform) {
$mform->addElement('header', 'header_specificsettings', get_string('specificsettings', 'customfield_select'));
$mform->setExpanded('header_specificsettings', true);
$mform->addElement('textarea', 'configdata[options]', get_string('menuoptions', 'customfield_select'));
$mform->setType('configdata[options]', PARAM_TEXT);
$mform->addElement('text', 'configdata[defaultvalue]', get_string('defaultvalue', 'core_customfield'), 'size="50"');
$mform->setType('configdata[defaultvalue]', PARAM_TEXT);
}
/**
* @deprecated since Moodle 3.10 - MDL-68569 please use $field->get_options
*/
public static function get_options_array(): void {
throw new coding_exception('get_options_array() is deprecated, please use $field->get_options() instead');
}
/**
* Return configured field options
*
* @return array
*/
public function get_options(): array {
$optionconfig = $this->get_configdata_property('options');
if ($optionconfig) {
$context = $this->get_handler()->get_configuration_context();
$options = array_map(
fn(string $option) => format_string($option, true, ['context' => $context]),
preg_split("/\s*\n\s*/", trim($optionconfig), -1, PREG_SPLIT_NO_EMPTY),
);
} else {
$options = array();
}
return array_merge([''], $options);
}
/**
* Validate the data from the config form.
* Sub classes must reimplement it.
*
* @param array $data from the add/edit profile field form
* @param array $files
* @return array associative array of error messages
*/
public function config_form_validation(array $data, $files = array()): array {
$options = preg_split("/\s*\n\s*/", trim($data['configdata']['options']));
$errors = [];
if (!$options || count($options) < 2) {
$errors['configdata[options]'] = get_string('errornotenoughoptions', 'customfield_select');
} else if (!empty($data['configdata']['defaultvalue'])) {
$defaultkey = array_search($data['configdata']['defaultvalue'], $options);
if ($defaultkey === false) {
$errors['configdata[defaultvalue]'] = get_string('errordefaultvaluenotinlist', 'customfield_select');
}
}
return $errors;
}
/**
* Does this custom field type support being used as part of the block_myoverview
* custom field grouping?
* @return bool
*/
public function supports_course_grouping(): bool {
return true;
}
/**
* If this field supports course grouping, then this function needs overriding to
* return the formatted values for this.
* @param array $values the used values that need formatting
* @return array
*/
public function course_grouping_format_values($values): array {
$options = $this->get_options();
$ret = [];
foreach ($values as $value) {
if (isset($options[$value])) {
$ret[$value] = $options[$value];
}
}
$ret[BLOCK_MYOVERVIEW_CUSTOMFIELD_EMPTY] = get_string('nocustomvalue', 'block_myoverview',
$this->get_formatted_name());
return $ret;
}
/**
* Locate the value parameter in the field options array, and return it's index
*
* @param string $value
* @return int
*/
public function parse_value(string $value) {
return (int) array_search($value, $this->get_options());
}
}
@@ -0,0 +1,83 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Privacy Subsystem implementation for customfield_select.
*
* @package customfield_select
* @copyright 2018 Daniel Neis Araujo <danielneis@gmail.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace customfield_select\privacy;
use core_customfield\data_controller;
use core_customfield\privacy\customfield_provider;
use core_privacy\local\request\writer;
defined('MOODLE_INTERNAL') || die();
/**
* Privacy Subsystem for customfield_select implementing null_provider.
*
* @copyright 2018 Daniel Neis Araujo <danielneis@gmail.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class provider implements \core_privacy\local\metadata\null_provider, customfield_provider {
/**
* Get the language string identifier with the component's language
* file to explain why this plugin stores no data.
*
* @return string
*/
public static function get_reason(): string {
return 'privacy:metadata';
}
/**
* Preprocesses data object that is going to be exported
*
* @param data_controller $data
* @param \stdClass $exportdata
* @param array $subcontext
*/
public static function export_customfield_data(data_controller $data, \stdClass $exportdata, array $subcontext) {
$context = $data->get_context();
$exportdata->value = $data->export_value();
writer::with_context($context)
->export_data($subcontext, $exportdata);
}
/**
* Allows plugins to delete everything they store related to the data (usually files)
*
* @param string $dataidstest
* @param array $params
* @param array $contextids
* @return mixed|void
*/
public static function before_delete_data(string $dataidstest, array $params, array $contextids) {
}
/**
* Allows plugins to delete everything they store related to the field configuration (usually files)
*
* @param string $fieldidstest
* @param array $params
* @param array $contextids
*/
public static function before_delete_fields(string $fieldidstest, array $params, array $contextids) {
}
}
@@ -0,0 +1,33 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Customfield text field plugin strings
*
* @package customfield_select
* @copyright 2018 Toni Barbera <toni@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$string['errordefaultvaluenotinlist'] = 'The default value must be one of the options from the list above.';
$string['errornotenoughoptions'] = 'Please provide at least two options, with each on a new line.';
$string['invalidoption'] = 'Invalid option selected';
$string['menuoptions'] = 'Menu options (one per line)';
$string['pluginname'] = 'Dropdown menu';
$string['privacy:metadata'] = 'The Dropdown menu field type plugin doesn\'t store any personal data; it uses tables defined in core.';
$string['specificsettings'] = 'Dropdown menu field settings';
@@ -0,0 +1,85 @@
@customfield @customfield_select @javascript
Feature: Managers can manage course custom fields select
In order to have additional data on the course
As a manager
I need to create, edit, remove and sort custom fields
Background:
Given the following "custom field categories" exist:
| name | component | area | itemid |
| Category for test | core_course | course | 0 |
And I log in as "admin"
And I navigate to "Courses > Default settings > Course custom fields" in site administration
Scenario: Create a custom course select field
When I click on "Add a new custom field" "link"
And I click on "Dropdown menu" "link"
And I set the following fields to these values:
| Name | Test field |
| Short name | testfield |
And I set the field "Menu options (one per line)" to multiline:
"""
a
b
"""
And I click on "Save changes" "button" in the "Adding a new Dropdown menu" "dialogue"
Then I should see "Test field"
And I log out
Scenario: Edit a custom course select field
When I click on "Add a new custom field" "link"
And I click on "Dropdown menu" "link"
And I set the following fields to these values:
| Name | Test field |
| Short name | testfield |
And I set the field "Menu options (one per line)" to multiline:
"""
a
b
"""
And I click on "Save changes" "button" in the "Adding a new Dropdown menu" "dialogue"
And I click on "Edit" "link" in the "Test field" "table_row"
And I set the following fields to these values:
| Name | Edited field |
And I click on "Save changes" "button" in the "Updating Test field" "dialogue"
Then I should see "Edited field"
And I should not see "Test field"
And I log out
Scenario: Delete a custom course select field
When I click on "Add a new custom field" "link"
And I click on "Dropdown menu" "link"
And I set the following fields to these values:
| Name | Test field |
| Short name | testfield |
And I set the field "Menu options (one per line)" to multiline:
"""
a
b
"""
And I click on "Save changes" "button" in the "Adding a new Dropdown menu" "dialogue"
And I click on "Delete" "link" in the "Test field" "table_row"
And I click on "Yes" "button" in the "Confirm" "dialogue"
Then I should not see "Test field"
And I log out
Scenario: Validation of custom course select field configuration
When I click on "Add a new custom field" "link"
And I click on "Dropdown menu" "link"
And I set the following fields to these values:
| Name | Test field |
| Short name | testfield |
And I click on "Save changes" "button" in the "Adding a new Dropdown menu" "dialogue"
And I should see "Please provide at least two options, with each on a new line." in the "Menu options (one per line)" "form_row"
And I set the field "Menu options (one per line)" to multiline:
"""
a
b
"""
And I set the field "Default value" to "c"
And I click on "Save changes" "button" in the "Adding a new Dropdown menu" "dialogue"
And I should see "The default value must be one of the options from the list above" in the "Default value" "form_row"
And I set the field "Default value" to "b"
And I click on "Save changes" "button" in the "Adding a new Dropdown menu" "dialogue"
And "testfield" "text" should exist in the "Test field" "table_row"
And I log out
@@ -0,0 +1,225 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace customfield_select;
use core_customfield_generator;
use core_customfield_test_instance_form;
use stdClass;
/**
* Functional test for customfield_select
*
* @package customfield_select
* @covers \customfield_select\data_controller
* @covers \customfield_select\field_controller
* @copyright 2019 Marina Glancy
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
final class plugin_test extends \advanced_testcase {
/** @var stdClass[] */
private $courses = [];
/** @var \core_customfield\category_controller */
private $cfcat;
/** @var \core_customfield\field_controller[] */
private $cfields;
/** @var \core_customfield\data_controller[] */
private $cfdata;
/**
* Tests set up.
*/
public function setUp(): void {
$this->resetAfterTest();
$this->cfcat = $this->get_generator()->create_category();
$this->cfields[1] = $this->get_generator()->create_field(
['categoryid' => $this->cfcat->get('id'), 'shortname' => 'myfield1', 'type' => 'select',
'configdata' => ['options' => "a\nb\nc"]]);
$this->cfields[2] = $this->get_generator()->create_field(
['categoryid' => $this->cfcat->get('id'), 'shortname' => 'myfield2', 'type' => 'select',
'configdata' => ['required' => 1, 'options' => "a\nb\nc"]]);
$this->cfields[3] = $this->get_generator()->create_field(
['categoryid' => $this->cfcat->get('id'), 'shortname' => 'myfield3', 'type' => 'select',
'configdata' => ['defaultvalue' => 'b', 'options' => "a\nb\nc"]]);
$this->courses[1] = $this->getDataGenerator()->create_course();
$this->courses[2] = $this->getDataGenerator()->create_course();
$this->courses[3] = $this->getDataGenerator()->create_course();
$this->cfdata[1] = $this->get_generator()->add_instance_data($this->cfields[1], $this->courses[1]->id, 1);
$this->cfdata[2] = $this->get_generator()->add_instance_data($this->cfields[1], $this->courses[2]->id, 1);
$this->setUser($this->getDataGenerator()->create_user());
}
/**
* Get generator
* @return core_customfield_generator
*/
protected function get_generator(): core_customfield_generator {
return $this->getDataGenerator()->get_plugin_generator('core_customfield');
}
/**
* Test for initialising field and data controllers
*/
public function test_initialise(): void {
$f = \core_customfield\field_controller::create($this->cfields[1]->get('id'));
$this->assertTrue($f instanceof field_controller);
$f = \core_customfield\field_controller::create(0, (object)['type' => 'select'], $this->cfcat);
$this->assertTrue($f instanceof field_controller);
$d = \core_customfield\data_controller::create($this->cfdata[1]->get('id'));
$this->assertTrue($d instanceof data_controller);
$d = \core_customfield\data_controller::create(0, null, $this->cfields[1]);
$this->assertTrue($d instanceof data_controller);
}
/**
* Test for configuration form functions
*
* Create a configuration form and submit it with the same values as in the field
*/
public function test_config_form(): void {
$this->setAdminUser();
$submitdata = (array)$this->cfields[1]->to_record();
$submitdata['configdata'] = $this->cfields[1]->get('configdata');
$submitdata = \core_customfield\field_config_form::mock_ajax_submit($submitdata);
$form = new \core_customfield\field_config_form(null, null, 'post', '', null, true,
$submitdata, true);
$form->set_data_for_dynamic_submission();
$this->assertTrue($form->is_validated());
$form->process_dynamic_submission();
}
/**
* Test for instance form functions
*/
public function test_instance_form(): void {
global $CFG;
require_once($CFG->dirroot . '/customfield/tests/fixtures/test_instance_form.php');
$this->setAdminUser();
$handler = $this->cfcat->get_handler();
// First try to submit without required field.
$submitdata = (array)$this->courses[1];
core_customfield_test_instance_form::mock_submit($submitdata, []);
$form = new core_customfield_test_instance_form('POST',
['handler' => $handler, 'instance' => $this->courses[1]]);
$this->assertFalse($form->is_validated());
// Now with required field.
$submitdata['customfield_myfield2'] = 1;
core_customfield_test_instance_form::mock_submit($submitdata, []);
$form = new core_customfield_test_instance_form('POST',
['handler' => $handler, 'instance' => $this->courses[1]]);
$this->assertTrue($form->is_validated());
$data = $form->get_data();
$this->assertNotEmpty($data->customfield_myfield1);
$this->assertNotEmpty($data->customfield_myfield2);
$handler->instance_form_save($data);
}
/**
* Test for data_controller::get_value and export_value
*/
public function test_get_export_value(): void {
$this->assertEquals(1, $this->cfdata[1]->get_value());
$this->assertEquals('a', $this->cfdata[1]->export_value());
// Field without data but with a default value.
$d = \core_customfield\data_controller::create(0, null, $this->cfields[3]);
$this->assertEquals(2, $d->get_value());
$this->assertEquals('b', $d->export_value());
}
/**
* Test getting field options, formatted
*/
public function test_get_options(): void {
filter_set_global_state('multilang', TEXTFILTER_ON);
filter_set_applies_to_strings('multilang', true);
$field = $this->get_generator()->create_field([
'categoryid' => $this->cfcat->get('id'),
'type' => 'select',
'shortname' => 'myselect',
'configdata' => [
'options' => <<<EOF
<span lang="en" class="multilang">Beginner</span><span lang="es" class="multilang">Novato</span>
<span lang="en" class="multilang">Intermediate</span><span lang="es" class="multilang">Intermedio</span>
<span lang="en" class="multilang">Advanced</span><span lang="es" class="multilang">Avanzado</span>
EOF,
],
]);
$this->assertEquals([
'',
'Beginner',
'Intermediate',
'Advanced',
], $field->get_options());
}
/**
* Data provider for {@see test_parse_value}
*
* @return array
*/
public static function parse_value_provider(): array {
return [
['Red', 1],
['Blue', 2],
['Green', 3],
['Mauve', 0],
];
}
/**
* Test field parse_value method
*
* @param string $value
* @param int $expected
*
* @dataProvider parse_value_provider
*/
public function test_parse_value(string $value, int $expected): void {
$field = $this->get_generator()->create_field([
'categoryid' => $this->cfcat->get('id'),
'type' => 'select',
'shortname' => 'myselect',
'configdata' => [
'options' => "Red\nBlue\nGreen",
],
]);
$this->assertSame($expected, $field->parse_value($value));
}
/**
* Deleting fields and data
*/
public function test_delete(): void {
$this->cfcat->get_handler()->delete_all();
}
}
+29
View File
@@ -0,0 +1,29 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Customfield Select Type
*
* @package customfield_select
* @copyright 2018 Toni Barbera <toni@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$plugin->component = 'customfield_select';
$plugin->version = 2024042200;
$plugin->requires = 2024041600;
@@ -0,0 +1,116 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Customfields text field plugin
*
* @package customfield_text
* @copyright 2018 Daniel Neis Araujo <daniel@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace customfield_text;
defined('MOODLE_INTERNAL') || die;
use core_customfield\api;
/**
* Class data
*
* @package customfield_text
* @copyright 2018 Daniel Neis Araujo <daniel@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class data_controller extends \core_customfield\data_controller {
/**
* Return the name of the field where the information is stored
* @return string
*/
public function datafield(): string {
return 'charvalue';
}
/**
* Add fields for editing a text field.
*
* @param \MoodleQuickForm $mform
*/
public function instance_form_definition(\MoodleQuickForm $mform) {
$field = $this->get_field();
$config = $field->get('configdata');
$type = $config['ispassword'] ? 'password' : 'text';
$elementname = $this->get_form_element_name();
$mform->addElement($type, $elementname, $this->get_field()->get_formatted_name(), 'size=' . (int)$config['displaysize']);
$mform->setType($elementname, PARAM_TEXT);
if (!empty($config['defaultvalue'])) {
$mform->setDefault($elementname, $config['defaultvalue']);
}
if ($field->get_configdata_property('required')) {
$mform->addRule($elementname, null, 'required', null, 'client');
}
}
/**
* Validates data for this field.
*
* @param array $data
* @param array $files
* @return array
*/
public function instance_form_validation(array $data, array $files): array {
$errors = parent::instance_form_validation($data, $files);
$maxlength = $this->get_field()->get_configdata_property('maxlength');
$elementname = $this->get_form_element_name();
if (($maxlength > 0) && ($maxlength < \core_text::strlen($data[$elementname]))) {
$errors[$elementname] = get_string('errormaxlength', 'customfield_text', $maxlength);
}
return $errors;
}
/**
* Returns the default value as it would be stored in the database (not in human-readable format).
*
* @return mixed
*/
public function get_default_value() {
return $this->get_field()->get_configdata_property('defaultvalue');
}
/**
* Returns value in a human-readable format
*
* @return mixed|null value or null if empty
*/
public function export_value() {
$value = parent::export_value();
if ($value === null) {
return null;
}
$link = $this->get_field()->get_configdata_property('link');
if ($link) {
$linktarget = $this->get_field()->get_configdata_property('linktarget');
$url = str_replace('$$', urlencode($this->get_value()), $link);
$attributes = $linktarget ? ['target' => $linktarget] : [];
$value = \html_writer::link($url, $value, $attributes);
}
return $value;
}
}
@@ -0,0 +1,152 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Customfields text plugin
*
* @package customfield_text
* @copyright 2018 David Matamoros <davidmc@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace customfield_text;
defined('MOODLE_INTERNAL') || die;
/**
* Class field
*
* @copyright 2018 David Matamoros <davidmc@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @package customfield_text
*/
class field_controller extends \core_customfield\field_controller {
/**
* Plugin type text
*/
const TYPE = 'text';
/**
* Add fields for editing a text field.
*
* @param \MoodleQuickForm $mform
*/
public function config_form_definition(\MoodleQuickForm $mform) {
$mform->addElement('header', 'header_specificsettings', get_string('specificsettings', 'customfield_text'));
$mform->setExpanded('header_specificsettings', true);
$mform->addElement('text', 'configdata[defaultvalue]', get_string('defaultvalue', 'core_customfield'),
['size' => 50]);
$mform->setType('configdata[defaultvalue]', PARAM_TEXT);
$mform->addElement('text', 'configdata[displaysize]', get_string('displaysize', 'customfield_text'), ['size' => 6]);
$mform->setType('configdata[displaysize]', PARAM_INT);
if (!$this->get_configdata_property('displaysize')) {
$mform->setDefault('configdata[displaysize]', 50);
}
$mform->addRule('configdata[displaysize]', null, 'numeric', null, 'client');
$mform->addElement('text', 'configdata[maxlength]', get_string('maxlength', 'customfield_text'), ['size' => 6]);
$mform->setType('configdata[maxlength]', PARAM_INT);
if (!$this->get_configdata_property('maxlength')) {
$mform->setDefault('configdata[maxlength]', 1333);
}
$mform->addRule('configdata[maxlength]', null, 'numeric', null, 'client');
$mform->addElement('selectyesno', 'configdata[ispassword]', get_string('ispassword', 'customfield_text'));
$mform->setType('configdata[ispassword]', PARAM_INT);
$mform->addElement('text', 'configdata[link]', get_string('islink', 'customfield_text'), ['size' => 50]);
$mform->setType('configdata[link]', PARAM_RAW_TRIMMED);
$mform->addHelpButton('configdata[link]', 'islink', 'customfield_text');
$mform->disabledIf('configdata[link]', 'configdata[ispassword]', 'eq', 1);
$linkstargetoptions = array(
'' => get_string('none', 'customfield_text'),
'_blank' => get_string('newwindow', 'customfield_text'),
'_self' => get_string('sameframe', 'customfield_text'),
'_top' => get_string('samewindow', 'customfield_text')
);
$mform->addElement('select', 'configdata[linktarget]', get_string('linktarget', 'customfield_text'),
$linkstargetoptions);
$mform->disabledIf('configdata[linktarget]', 'configdata[link]', 'eq', '');
}
/**
* Validate the data on the field configuration form
*
* @param array $data from the add/edit profile field form
* @param array $files
* @return array associative array of error messages
*/
public function config_form_validation(array $data, $files = array()): array {
global $CFG;
$errors = parent::config_form_validation($data, $files);
$maxlength = (int)$data['configdata']['maxlength'];
if ($maxlength < 1 || $maxlength > 1333) {
$errors['configdata[maxlength]'] = get_string('errorconfigmaxlen', 'customfield_text');
}
$displaysize = (int)$data['configdata']['displaysize'];
if ($displaysize < 1 || $displaysize > 200) {
$errors['configdata[displaysize]'] = get_string('errorconfigdisplaysize', 'customfield_text');
}
if (isset($data['configdata']['link'])) {
$link = $data['configdata']['link'];
if (strlen($link)) {
require_once($CFG->dirroot . '/lib/validateurlsyntax.php');
if (strpos($link, '$$') === false) {
$errors['configdata[link]'] = get_string('errorconfiglinkplaceholder', 'customfield_text');
} else if (!validateUrlSyntax(str_replace('$$', 'XYZ', $link), 's+H?S?F-E-u-P-a?I?p?f?q?r?')) {
// This validation is more strict than PARAM_URL - it requires the protocol and it must be either http or https.
$errors['configdata[link]'] = get_string('errorconfiglinksyntax', 'customfield_text');
}
}
}
return $errors;
}
/**
* Does this custom field type support being used as part of the block_myoverview
* custom field grouping?
* @return bool
*/
public function supports_course_grouping(): bool {
return true;
}
/**
* If this field supports course grouping, then this function needs overriding to
* return the formatted values for this.
* @param array $values the used values that need formatting
* @return array
*/
public function course_grouping_format_values($values): array {
$ret = [];
foreach ($values as $value) {
$ret[$value] = format_string($value);
}
$ret[BLOCK_MYOVERVIEW_CUSTOMFIELD_EMPTY] = get_string('nocustomvalue', 'block_myoverview',
$this->get_formatted_name());
return $ret;
}
}
@@ -0,0 +1,84 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Privacy Subsystem implementation for customfield_text.
*
* @package customfield_text
* @copyright 2018 Daniel Neis Araujo <danielneis@gmail.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace customfield_text\privacy;
use core_customfield\data_controller;
use core_customfield\privacy\customfield_provider;
use core_privacy\local\request\writer;
defined('MOODLE_INTERNAL') || die();
/**
* Privacy Subsystem for customfield_text implementing null_provider.
*
* @copyright 2018 Daniel Neis Araujo <danielneis@gmail.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class provider implements \core_privacy\local\metadata\null_provider, customfield_provider {
/**
* Get the language string identifier with the component's language
* file to explain why this plugin stores no data.
*
* @return string
*/
public static function get_reason(): string {
return 'privacy:metadata';
}
/**
* Preprocesses data object that is going to be exported
*
* @param data_controller $data
* @param \stdClass $exportdata
* @param array $subcontext
*/
public static function export_customfield_data(data_controller $data, \stdClass $exportdata, array $subcontext) {
$context = $data->get_context();
// For text fields we want to apply format_string even to raw value to avoid CSS.
$exportdata->{$data->datafield()} = $data->export_value();
writer::with_context($context)
->export_data($subcontext, $exportdata);
}
/**
* Allows plugins to delete everything they store related to the data (usually files)
*
* @param string $dataidstest
* @param array $params
* @param array $contextids
* @return mixed|void
*/
public static function before_delete_data(string $dataidstest, array $params, array $contextids) {
}
/**
* Allows plugins to delete everything they store related to the field configuration (usually files)
*
* @param string $fieldidstest
* @param array $params
* @param array $contextids
*/
public static function before_delete_fields(string $fieldidstest, array $params, array $contextids) {
}
}
@@ -0,0 +1,44 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Customfield text plugin
*
* @package customfield_text
* @copyright 2018 Toni Barbera <toni@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$string['displaysize'] = 'Form input size';
$string['errorconfigdisplaysize'] = 'The form input size must be between 1 and 200 characters.';
$string['errorconfiglinkplaceholder'] = 'The link must contain a placeholder $$.';
$string['errorconfiglinksyntax'] = 'The link must be a valid URL starting with either http:// or https://.';
$string['errorconfigmaxlen'] = 'The maximum number of characters allowed must be between 1 and 1333.';
$string['errormaxlength'] = 'The maximum number of characters allowed in this field is {$a}.';
$string['islink'] = 'Link field';
$string['islink_help'] = 'To transform the text into a link, enter a URL containing $$ as a placeholder, where $$ will be replaced with the text. For example, to transform a Twitter ID to a link, enter https://twitter.com/$$.';
$string['ispassword'] = 'Password field';
$string['linktarget'] = 'Link target';
$string['maxlength'] = 'Maximum number of characters';
$string['newwindow'] = 'New window';
$string['none'] = 'None';
$string['pluginname'] = 'Short text';
$string['privacy:metadata'] = 'The Short text field type plugin doesn\'t store any personal data; it uses tables defined in core.';
$string['sameframe'] = 'Same frame';
$string['samewindow'] = 'Same window';
$string['specificsettings'] = 'Short text field settings';
@@ -0,0 +1,140 @@
@customfield @customfield_text @javascript
Feature: Managers can manage course custom fields text
In order to have additional data on the course
As a manager
I need to create, edit, remove and sort custom fields
Background:
Given the following "custom field categories" exist:
| name | component | area | itemid |
| Category for test | core_course | course | 0 |
And I log in as "admin"
And I navigate to "Courses > Default settings > Course custom fields" in site administration
Scenario: Create a custom course text field
When I click on "Add a new custom field" "link"
And I click on "Short text" "link"
And I set the following fields to these values:
| Name | Test field |
| Short name | testfield |
And I click on "Save changes" "button" in the "Adding a new Short text" "dialogue"
Then I should see "Test field"
And I log out
Scenario: Edit a custom course text field
When I click on "Add a new custom field" "link"
And I click on "Short text" "link"
And I set the following fields to these values:
| Name | Test field |
| Short name | testfield |
And I click on "Save changes" "button" in the "Adding a new Short text" "dialogue"
And I click on "Edit" "link" in the "Test field" "table_row"
And I set the following fields to these values:
| Name | Edited field |
And I click on "Save changes" "button" in the "Updating Test field" "dialogue"
Then I should see "Edited field"
And I navigate to "Reports > Logs" in site administration
And I press "Get these logs"
And I log out
Scenario: Delete a custom course text field
When I click on "Add a new custom field" "link"
And I click on "Short text" "link"
And I set the following fields to these values:
| Name | Test field |
| Short name | testfield |
And I click on "Save changes" "button" in the "Adding a new Short text" "dialogue"
And I click on "Delete" "link" in the "Test field" "table_row"
And I click on "Yes" "button" in the "Confirm" "dialogue"
And I wait until the page is ready
And I wait until "Test field" "text" does not exist
Then I should not see "Test field"
And I log out
Scenario: A text field with a link setting must show link on course listing
Given the following "users" exist:
| username | firstname | lastname | email |
| teacher1 | Teacher | Example 1 | teacher1@example.com |
And the following "courses" exist:
| fullname | shortname | format |
| Course 1 | C1 | topics |
And the following "course enrolments" exist:
| user | course | role |
| teacher1 | C1 | editingteacher |
And I navigate to "Courses > Default settings > Course custom fields" in site administration
And I click on "Add a new custom field" "link"
And I click on "Short text" "link"
And I set the following fields to these values:
| Name | See more on website |
| Short name | testfield |
| Visible to | Everyone |
| Link | https://www.moodle.org/$$ |
And I click on "Save changes" "button" in the "Adding a new Short text" "dialogue"
And I log out
Then I log in as "teacher1"
And I am on "Course 1" course homepage
And I navigate to "Settings" in current page administration
And I set the following fields to these values:
| See more on website | course/view.php?id=35 |
And I press "Save and display"
And I am on site homepage
Then I should see "course/view.php?id=35" in the ".customfields-container .customfieldvalue a" "css_element"
Then I should see "See more on website" in the ".customfields-container .customfieldname" "css_element"
Scenario: A text field with a max length must validate it on course edit form
Given the following "users" exist:
| username | firstname | lastname | email |
| teacher1 | Teacher | Example 1 | teacher1@example.com |
And the following "courses" exist:
| fullname | shortname | format |
| Course 1 | C1 | topics |
And the following "course enrolments" exist:
| user | course | role |
| teacher1 | C1 | editingteacher |
And I navigate to "Courses > Default settings > Course custom fields" in site administration
And I click on "Add a new custom field" "link"
And I click on "Short text" "link"
And I set the following fields to these values:
| Name | Test field |
| Short name | testfield |
| Maximum number of characters | 3 |
And I click on "Save changes" "button" in the "Adding a new Short text" "dialogue"
And I log out
Then I log in as "teacher1"
And I am on "Course 1" course homepage
And I navigate to "Settings" in current page administration
And I set the following fields to these values:
| Test field | 1234 |
And I press "Save and display"
Then I should see "The maximum number of characters allowed in this field is 3."
Scenario: A text field with a default value must be shown on listing but allow empty values that will not be shown
Given the following "users" exist:
| username | firstname | lastname | email |
| teacher1 | Teacher | Example 1 | teacher1@example.com |
And the following "courses" exist:
| fullname | shortname | format |
| Course 1 | C1 | topics |
And the following "course enrolments" exist:
| user | course | role |
| teacher1 | C1 | editingteacher |
And I navigate to "Courses > Default settings > Course custom fields" in site administration
And I click on "Add a new custom field" "link"
And I click on "Short text" "link"
And I set the following fields to these values:
| Name | Test field |
| Short name | testfield |
| Default value | testdefault |
And I click on "Save changes" "button" in the "Adding a new Short text" "dialogue"
And I log out
Then I log in as "teacher1"
When I am on site homepage
Then I should see "Test field: testdefault"
When I am on "Course 1" course homepage
And I navigate to "Settings" in current page administration
Then the "value" attribute of "#id_customfield_testfield" "css_element" should contain "testdefault"
When I set the following fields to these values:
| Test field | |
And I press "Save and display"
And I am on site homepage
And I should not see "Test field"
@@ -0,0 +1,169 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace customfield_text;
use core_customfield_generator;
use core_customfield_test_instance_form;
/**
* Functional test for customfield_text
*
* @package customfield_text
* @copyright 2019 Marina Glancy
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class plugin_test extends \advanced_testcase {
/** @var stdClass[] */
private $courses = [];
/** @var \core_customfield\category_controller */
private $cfcat;
/** @var \core_customfield\field_controller[] */
private $cfields;
/** @var \core_customfield\data_controller[] */
private $cfdata;
/**
* Tests set up.
*/
public function setUp(): void {
$this->resetAfterTest();
$this->cfcat = $this->get_generator()->create_category();
$this->cfields[1] = $this->get_generator()->create_field(
['categoryid' => $this->cfcat->get('id'), 'shortname' => 'myfield1', 'type' => 'text',
'configdata' => ['maxlength' => 30, 'displaysize' => 50], 'description' => null]);
$this->cfields[2] = $this->get_generator()->create_field(
['categoryid' => $this->cfcat->get('id'), 'shortname' => 'myfield2', 'type' => 'text',
'configdata' => ['required' => 1, 'maxlength' => 30, 'displaysize' => 50]]);
$this->cfields[3] = $this->get_generator()->create_field(
['categoryid' => $this->cfcat->get('id'), 'shortname' => 'myfield3', 'type' => 'text',
'configdata' => ['defaultvalue' => 'Defvalue', 'maxlength' => 30, 'displaysize' => 50]]);
$this->cfields[4] = $this->get_generator()->create_field(
['categoryid' => $this->cfcat->get('id'), 'shortname' => 'myfield4', 'type' => 'text',
'configdata' => ['link' => 'https://twitter.com/$$', 'maxlength' => 30, 'displaysize' => 50]]);
$this->courses[1] = $this->getDataGenerator()->create_course();
$this->courses[2] = $this->getDataGenerator()->create_course();
$this->courses[3] = $this->getDataGenerator()->create_course();
$this->cfdata[1] = $this->get_generator()->add_instance_data($this->cfields[1], $this->courses[1]->id,
'Value1');
$this->cfdata[2] = $this->get_generator()->add_instance_data($this->cfields[1], $this->courses[2]->id,
'Value2');
$this->setUser($this->getDataGenerator()->create_user());
}
/**
* Get generator
* @return core_customfield_generator
*/
protected function get_generator(): core_customfield_generator {
return $this->getDataGenerator()->get_plugin_generator('core_customfield');
}
/**
* Test for initialising field and data controllers
*/
public function test_initialise(): void {
$f = \core_customfield\field_controller::create($this->cfields[1]->get('id'));
$this->assertTrue($f instanceof field_controller);
$f = \core_customfield\field_controller::create(0, (object)['type' => 'text'], $this->cfcat);
$this->assertTrue($f instanceof field_controller);
$d = \core_customfield\data_controller::create($this->cfdata[1]->get('id'));
$this->assertTrue($d instanceof data_controller);
$d = \core_customfield\data_controller::create(0, null, $this->cfields[1]);
$this->assertTrue($d instanceof data_controller);
}
/**
* Test for configuration form functions
*
* Create a configuration form and submit it with the same values as in the field
*/
public function test_config_form(): void {
$this->setAdminUser();
$submitdata = (array)$this->cfields[1]->to_record();
$submitdata['configdata'] = $this->cfields[1]->get('configdata');
$submitdata = \core_customfield\field_config_form::mock_ajax_submit($submitdata);
$form = new \core_customfield\field_config_form(null, null, 'post', '', null, true,
$submitdata, true);
$form->set_data_for_dynamic_submission();
$this->assertTrue($form->is_validated());
$form->process_dynamic_submission();
}
/**
* Test for instance form functions
*/
public function test_instance_form(): void {
global $CFG;
require_once($CFG->dirroot . '/customfield/tests/fixtures/test_instance_form.php');
$this->setAdminUser();
$handler = $this->cfcat->get_handler();
// First try to submit without required field.
$submitdata = (array)$this->courses[1];
core_customfield_test_instance_form::mock_submit($submitdata, []);
$form = new core_customfield_test_instance_form('POST',
['handler' => $handler, 'instance' => $this->courses[1]]);
$this->assertFalse($form->is_validated());
// Now with required field.
$submitdata['customfield_myfield2'] = 'Some text';
core_customfield_test_instance_form::mock_submit($submitdata, []);
$form = new core_customfield_test_instance_form('POST',
['handler' => $handler, 'instance' => $this->courses[1]]);
$this->assertTrue($form->is_validated());
$data = $form->get_data();
$this->assertNotEmpty($data->customfield_myfield1);
$this->assertNotEmpty($data->customfield_myfield2);
$handler->instance_form_save($data);
}
/**
* Test for data_controller::get_value and export_value
*/
public function test_get_export_value(): void {
$this->assertEquals('Value1', $this->cfdata[1]->get_value());
$this->assertEquals('Value1', $this->cfdata[1]->export_value());
// Field without data but with a default value.
$d = \core_customfield\data_controller::create(0, null, $this->cfields[3]);
$this->assertEquals('Defvalue', $d->get_value());
$this->assertEquals('Defvalue', $d->export_value());
// Field with a link.
$d = $this->get_generator()->add_instance_data($this->cfields[4], $this->courses[1]->id, 'mynickname');
$this->assertEquals('mynickname', $d->get_value());
$this->assertEquals('<a href="https://twitter.com/mynickname">mynickname</a>', $d->export_value());
}
/**
* Deleting fields and data
*/
public function test_delete(): void {
$this->cfcat->get_handler()->delete_all();
}
}
+29
View File
@@ -0,0 +1,29 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Customfield text plugin
*
* @package customfield_text
* @copyright 2018 Toni Barbera <toni@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$plugin->component = 'customfield_text';
$plugin->version = 2024042200;
$plugin->requires = 2024041600;
@@ -0,0 +1,261 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Customfields textarea plugin
*
* @package customfield_textarea
* @copyright 2018 Daniel Neis Araujo <daniel@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace customfield_textarea;
use backup_nested_element;
defined('MOODLE_INTERNAL') || die;
/**
* Class data
*
* @package customfield_textarea
* @copyright 2018 Daniel Neis Araujo <daniel@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class data_controller extends \core_customfield\data_controller {
/**
* Return the name of the field where the information is stored
* @return string
*/
public function datafield(): string {
return 'value';
}
/**
* Options for the editor
*
* @return array
*/
protected function value_editor_options() {
/** @var field_controller $field */
$field = $this->get_field();
return $field->value_editor_options($this->get('id') ? $this->get_context() : null);
}
/**
* Returns the name of the field to be used on HTML forms.
*
* @return string
*/
public function get_form_element_name(): string {
return parent::get_form_element_name() . '_editor';
}
/**
* Add fields for editing a textarea field.
*
* @param \MoodleQuickForm $mform
*/
public function instance_form_definition(\MoodleQuickForm $mform) {
$field = $this->get_field();
$desceditoroptions = $this->value_editor_options();
$elementname = $this->get_form_element_name();
$mform->addElement('editor', $elementname, $this->get_field()->get_formatted_name(), null, $desceditoroptions);
if ($field->get_configdata_property('required')) {
$mform->addRule($elementname, null, 'required', null, 'client');
}
}
/**
* Saves the data coming from form
*
* @param \stdClass $datanew data coming from the form
*/
public function instance_form_save(\stdClass $datanew) {
$fieldname = $this->get_form_element_name();
if (!property_exists($datanew, $fieldname)) {
return;
}
// Normalise form data, for cases it's come from an external source.
$fromform = $datanew->$fieldname;
if (!is_array($fromform)) {
$fromform = ['text' => $fromform];
$fromform['format'] = $this->get('id') ? $this->get('valueformat') :
$this->get_field()->get_configdata_property('defaultvalueformat');
}
if (!$this->get('id')) {
$this->data->set('value', '');
$this->data->set('valueformat', FORMAT_MOODLE);
$this->data->set('valuetrust', false);
$this->save();
}
if (array_key_exists('text', $fromform)) {
$textoptions = $this->value_editor_options();
$context = $textoptions['context'];
$data = (object) ['field_editor' => $fromform];
$data = file_postupdate_standard_editor($data, 'field', $textoptions, $context,
'customfield_textarea', 'value', $this->get('id'));
$this->data->set('value', $data->field);
$this->data->set('valueformat', $data->fieldformat);
$this->data->set('valuetrust', trusttext_trusted($context));
$this->save();
}
}
/**
* Prepares the custom field data related to the object to pass to mform->set_data() and adds them to it
*
* This function must be called before calling $form->set_data($object);
*
* @param \stdClass $instance the entity that has custom fields, if 'id' attribute is present the custom
* fields for this entity will be added, otherwise the default values will be added.
*/
public function instance_form_before_set_data(\stdClass $instance) {
$textoptions = $this->value_editor_options();
$context = $textoptions['context'];
if ($this->get('id')) {
$text = $this->get('value');
$format = $this->get('valueformat');
$temp = (object) ['field' => $text, 'fieldformat' => $format, 'fieldtrust' => trusttext_trusted($context)];
file_prepare_standard_editor($temp, 'field', $textoptions, $context, 'customfield_textarea',
'value', $this->get('id'));
$value = $temp->field_editor;
} else {
$text = $this->get_field()->get_configdata_property('defaultvalue');
$format = $this->get_field()->get_configdata_property('defaultvalueformat');
$temp = (object) ['field' => $text, 'fieldformat' => $format, 'fieldtrust' => trusttext_trusted($context)];
file_prepare_standard_editor($temp, 'field', $textoptions, $context, 'customfield_textarea',
'defaultvalue', $this->get_field()->get('id'));
$value = $temp->field_editor;
}
$instance->{$this->get_form_element_name()} = $value;
}
/**
* Checks if the value is empty, overriding the base method to ensure it's the "text" element of our value being compared
*
* @param string|string[] $value
* @return bool
*/
protected function is_empty($value): bool {
if (is_array($value)) {
$value = $value['text'];
}
return html_is_blank($value);
}
/**
* Checks if the value is unique, overriding the base method to ensure it's the "text" element of our value being compared
*
* @param mixed $value
* @return bool
*/
protected function is_unique($value): bool {
return parent::is_unique($value['text']);
}
/**
* Delete data
*
* @return bool
*/
public function delete() {
get_file_storage()->delete_area_files($this->get('contextid'), 'customfield_textarea',
'value', $this->get('id'));
return parent::delete();
}
/**
* Returns the default value as it would be stored in the database (not in human-readable format).
*
* @return mixed
*/
public function get_default_value() {
return $this->get_field()->get_configdata_property('defaultvalue');
}
/**
* Implement the backup callback for the custom field element.
* This includes any embedded files in the custom field element.
*
* @param \backup_nested_element $customfieldelement The custom field element to be backed up.
*/
public function backup_define_structure(backup_nested_element $customfieldelement): void {
$annotations = $customfieldelement->get_file_annotations();
if (!isset($annotations['customfield_textarea']['value'])) {
$customfieldelement->annotate_files('customfield_textarea', 'value', 'id');
}
}
/**
* Implement the restore callback for the custom field element.
* This includes restoring any embedded files in the custom field element.
*
* @param \restore_structure_step $step The restore step instance.
* @param int $newid The new ID for the custom field data after restore.
* @param int $oldid The original ID of the custom field data before backup.
*/
public function restore_define_structure(\restore_structure_step $step, int $newid, int $oldid): void {
if (!$step->get_mappingid('customfield_data', $oldid)) {
$step->set_mapping('customfield_data', $oldid, $newid, true);
$step->add_related_files('customfield_textarea', 'value', 'customfield_data');
}
}
/**
* Returns value in a human-readable format
*
* @return mixed|null value or null if empty
*/
public function export_value() {
global $CFG;
require_once($CFG->libdir . '/filelib.php');
$value = $this->get_value();
if ($this->is_empty($value)) {
return null;
}
if ($dataid = $this->get('id')) {
$context = $this->get_context();
$processed = file_rewrite_pluginfile_urls($value, 'pluginfile.php',
$context->id, 'customfield_textarea', 'value', $dataid);
$value = format_text($processed, $this->get('valueformat'), [
'context' => $context,
'trusted' => $this->get('valuetrust'),
]);
} else {
$field = $this->get_field();
$context = $field->get_handler()->get_configuration_context();
$processed = file_rewrite_pluginfile_urls($value, 'pluginfile.php',
$context->id, 'customfield_textarea', 'defaultvalue', $field->get('id'));
$value = format_text($processed, $field->get_configdata_property('defaultvalueformat'), [
'context' => $context,
'trusted' => true,
]);
}
return $value;
}
}
@@ -0,0 +1,152 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Customfield textarea plugin
*
* @package customfield_textarea
* @copyright 2018 David Matamoros <davidmc@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace customfield_textarea;
defined('MOODLE_INTERNAL') || die;
/**
* Class field
*
* @package customfield_textarea
* @copyright 2018 David Matamoros <davidmc@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class field_controller extends \core_customfield\field_controller {
/**
* Const type
*/
const TYPE = 'textarea';
/**
* Before delete bulk actions
*/
public function delete(): bool {
global $DB;
$fs = get_file_storage();
// Delete files in the defaultvalue.
$fs->delete_area_files($this->get_handler()->get_configuration_context()->id, 'customfield_textarea',
'defaultvalue', $this->get('id'));
// Delete files in the data. We can not use $fs->delete_area_files_select() because context may be different.
$params = ['component' => 'customfield_textarea', 'filearea' => 'value', 'fieldid' => $this->get('id')];
$where = "component = :component AND filearea = :filearea
AND itemid IN (SELECT cfd.id FROM {customfield_data} cfd WHERE cfd.fieldid = :fieldid)";
$filerecords = $DB->get_recordset_select('files', $where, $params);
foreach ($filerecords as $filerecord) {
$fs->get_file_instance($filerecord)->delete();
}
$filerecords->close();
// Delete data and field.
return parent::delete();
}
/**
* Prepare the field data to set in the configuration form
*
* Necessary if some preprocessing required for editor or filemanager fields
*
* @param \stdClass $formdata
*/
public function prepare_for_config_form(\stdClass $formdata) {
if (!empty($formdata->configdata['defaultvalue'])) {
$textoptions = $this->value_editor_options();
$context = $textoptions['context'];
$record = new \stdClass();
$record->defaultvalue = $formdata->configdata['defaultvalue'];
$record->defaultvalueformat = $formdata->configdata['defaultvalueformat'];
file_prepare_standard_editor($record, 'defaultvalue', $textoptions, $context,
'customfield_textarea', 'defaultvalue', $formdata->id);
$formdata->configdata['defaultvalue_editor'] = $record->defaultvalue_editor;
}
}
/**
* Add fields for editing a textarea field.
*
* @param \MoodleQuickForm $mform
*/
public function config_form_definition(\MoodleQuickForm $mform) {
$mform->addElement('header', 'header_specificsettings', get_string('specificsettings', 'customfield_textarea'));
$mform->setExpanded('header_specificsettings', true);
$desceditoroptions = $this->value_editor_options();
$mform->addElement('editor', 'configdata[defaultvalue_editor]', get_string('defaultvalue', 'core_customfield'),
null, $desceditoroptions);
}
/**
* Options for editor
*
* @param \context|null $context context if known, otherwise configuration context will be used
* @return array
*/
public function value_editor_options(\context $context = null) {
global $CFG;
require_once($CFG->libdir.'/formslib.php');
if (!$context) {
$context = $this->get_handler()->get_configuration_context();
}
return [
'context' => $context,
'trusttext' => true,
'maxfiles' => EDITOR_UNLIMITED_FILES,
'maxbytes' => $CFG->maxbytes,
];
}
/**
* Saves the field configuration
*/
public function save() {
$configdata = $this->get('configdata');
if (!array_key_exists('defaultvalue_editor', $configdata)) {
$this->field->save();
return;
}
if (!$this->get('id')) {
$this->field->save();
}
// Store files.
$textoptions = $this->value_editor_options();
$tempvalue = (object) ['defaultvalue_editor' => $configdata['defaultvalue_editor']];
$tempvalue = file_postupdate_standard_editor($tempvalue, 'defaultvalue', $textoptions, $textoptions['context'],
'customfield_textarea', 'defaultvalue', $this->get('id'));
$configdata['defaultvalue'] = $tempvalue->defaultvalue;
$configdata['defaultvalueformat'] = $tempvalue->defaultvalueformat;
unset($configdata['defaultvalue_editor']);
$this->field->set('configdata', json_encode($configdata));
$this->field->save();
}
}
@@ -0,0 +1,97 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Privacy Subsystem implementation for customfield_textarea.
*
* @package customfield_textarea
* @copyright 2018 Daniel Neis Araujo <danielneis@gmail.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace customfield_textarea\privacy;
use core_customfield\data_controller;
use core_customfield\privacy\customfield_provider;
use core_privacy\local\request\writer;
defined('MOODLE_INTERNAL') || die();
/**
* Privacy Subsystem for customfield_textarea implementing null_provider.
*
* @copyright 2018 Daniel Neis Araujo <danielneis@gmail.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class provider implements \core_privacy\local\metadata\null_provider, customfield_provider {
/**
* Get the language string identifier with the component's language
* file to explain why this plugin stores no data.
*
* @return string
*/
public static function get_reason(): string {
return 'privacy:metadata';
}
/**
* Preprocesses data object that is going to be exported
*
* @param data_controller $data
* @param \stdClass $exportdata
* @param array $subcontext
*/
public static function export_customfield_data(data_controller $data, \stdClass $exportdata, array $subcontext) {
$context = $data->get_context();
$exportdata->value = writer::with_context($context)
->rewrite_pluginfile_urls($subcontext, 'customfield_textarea', 'value',
$exportdata->id, $exportdata->value);
writer::with_context($context)
->export_data($subcontext, $exportdata)
->export_area_files($subcontext, 'customfield_textarea', 'value', $exportdata->id);
}
/**
* Allows plugins to delete everything they store related to the data (usually files)
*
* @param string $dataidstest
* @param array $params
* @param array $contextids
* @return mixed|void
*/
public static function before_delete_data(string $dataidstest, array $params, array $contextids) {
$fs = get_file_storage();
foreach ($contextids as $contextid) {
$fs->delete_area_files_select($contextid, 'customfield_textarea', 'value', $dataidstest, $params);
}
}
/**
* Allows plugins to delete everything they store related to the field configuration (usually files)
*
* The implementation should not delete data or anything related to the data, since "before_delete_data" is
* invoked separately.
*
* @param string $fieldidstest
* @param array $params
* @param array $contextids
*/
public static function before_delete_fields(string $fieldidstest, array $params, array $contextids) {
$fs = get_file_storage();
foreach ($contextids as $contextid) {
$fs->delete_area_files_select($contextid, 'customfield_textarea', 'defaultvalue', $fieldidstest, $params);
}
}
}
@@ -0,0 +1,29 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Customfield textarea plugin
*
* @package customfield_textarea
* @copyright 2018 Toni Barbera <toni@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$string['pluginname'] = 'Text area';
$string['privacy:metadata'] = 'The Text area field type plugin doesn\'t store any personal data; it uses tables defined in core.';
$string['specificsettings'] = 'Text area field settings';
+76
View File
@@ -0,0 +1,76 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Callbacks
*
* @package customfield_textarea
* @copyright 2018 Marina Glancy
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die;
/**
* Serve the files from the customfield_textarea file areas
*
* @param stdClass $course the course object
* @param stdClass $cm the course module object
* @param context $context the context
* @param string $filearea the name of the file area
* @param array $args extra arguments (itemid, path)
* @param bool $forcedownload whether or not force download
* @param array $options additional options affecting the file serving
* @return bool false if the file not found, just send the file otherwise and do not return
*/
function customfield_textarea_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
global $DB;
$itemid = array_shift($args);
if ($filearea === 'value') {
// Value of the data, itemid = id in data table.
$datarecord = $DB->get_record(\core_customfield\data::TABLE, ['id' => $itemid], '*', MUST_EXIST);
$field = \core_customfield\field_controller::create($datarecord->fieldid);
$data = \core_customfield\data_controller::create(0, $datarecord, $field);
$handler = $field->get_handler();
if ($field->get('type') !== 'textarea' || !$handler->can_view($field, $data->get('instanceid'))
|| $data->get_context()->id != $context->id) {
send_file_not_found();
}
} else if ($filearea === 'defaultvalue') {
// Default value of the field, itemid = id in the field table.
$field = \core_customfield\field_controller::create($itemid);
$handler = $field->get_handler();
if ($field->get('type') !== 'textarea' || $handler->get_configuration_context()->id != $context->id) {
send_file_not_found();
}
} else {
send_file_not_found();
}
$filename = array_pop($args); // The last item in the $args array.
$filepath = '/' . ($args ? implode('/', $args) . '/' : '');
// Retrieve the file from the Files API.
$fs = get_file_storage();
$file = $fs->get_file($context->id, 'customfield_textarea', $filearea, $itemid, $filepath, $filename);
if (!$file) {
send_file_not_found();
}
// We can now send the file back to the browser - in this case with a cache lifetime of 1 day and no filtering.
send_stored_file($file, DAYSECS, 0, $forcedownload, $options);
}
@@ -0,0 +1,81 @@
@customfield @customfield_textarea @javascript @editor_tiny
Feature: Default value for the textarea custom field can contain images
In order to see images on custom fields
As a manager
I need to be able to add images to the default value
Background:
Given the following "users" exist:
| username | firstname | lastname | email |
| teacher | Teacher | 1 | teacher1@example.com |
| manager | Manager | 1 | manager1@example.com |
And the following "courses" exist:
| fullname | shortname | format |
| Course 1 | C1 | topics |
And the following "course enrolments" exist:
| user | course | role |
| teacher | C1 | editingteacher |
And the following "system role assigns" exist:
| user | course | role |
| manager | Acceptance test site | manager |
And the following "custom field categories" exist:
| name | component | area | itemid |
| Category for test | core_course | course | 0 |
And the following "user private files" exist:
| user | filepath |
| admin | lib/tests/fixtures/gd-logo.png |
And I log in as "admin"
And I navigate to "Courses > Default settings > Course custom fields" in site administration
And I click on "Add a new custom field" "link"
And I click on "Text area" "link"
And I set the following fields to these values:
| Name | Test field |
| Short name | testfield |
# Embed the image into Default value.
And I click on "Image" "button" in the "Default value" "form_row"
And I click on "Browse repositories" "button"
And I click on "Private files" "link" in the ".fp-repo-area" "css_element"
And I click on "gd-logo.png" "link"
And I click on "Select this file" "button"
And I set the field "How would you describe this image to someone who can't see it?" to "Example"
And I click on "Save" "button" in the "Image details" "dialogue"
And I click on "Save changes" "button" in the "Adding a new Text area" "dialogue"
And I log out
Scenario: For the courses that existed before the custom field was created the default value is displayed
When I am on site homepage
Then the image at "//*[contains(@class, 'frontpage-course-list-all')]//*[contains(@class, 'customfield_textarea')]//img[contains(@src, 'pluginfile.php') and contains(@src, '/customfield_textarea/defaultvalue/') and @alt='Example']" "xpath_element" should be identical to "lib/tests/fixtures/gd-logo.png"
Scenario: Teacher will see textarea default value when editing a course created before custom field was created
# Teacher will see the image when editing existing course.
When I log in as "teacher"
And I am on "Course 1" course homepage
And I navigate to "Settings" in current page administration
And I expand all fieldsets
And I switch to the "Test field" TinyMCE editor iframe
Then "//img[contains(@src, 'draftfile.php') and contains(@src, '/gd-logo.png') and @alt='Example']" "xpath_element" should exist
And I switch to the main frame
# Save the course without changing the default value.
And I press "Save and display"
And I log out
# Now the same image is displayed as "value" and not as "defaultvalue".
And I am on site homepage
Then "//img[contains(@src, '/customfield_textarea/defaultvalue/')]" "xpath_element" should not exist
And the image at "//*[contains(@class, 'frontpage-course-list-all')]//*[contains(@class, 'customfield_textarea')]//img[contains(@src, 'pluginfile.php') and contains(@src, '/customfield_textarea/value/') and @alt='Example']" "xpath_element" should be identical to "lib/tests/fixtures/gd-logo.png"
Scenario: Manager can create a course and the default value for textarea custom field will apply.
When I log in as "manager"
And I go to the courses management page
And I click on "Create new course" "link" in the "#course-listing" "css_element"
And I set the following fields to these values:
| Course full name | Course 2 |
| Course short name | C2 |
And I expand all fieldsets
And I switch to the "Test field" TinyMCE editor iframe
Then "//img[contains(@src, 'draftfile.php') and contains(@src, '/gd-logo.png') and @alt='Example']" "xpath_element" should exist
And I switch to the main frame
And I press "Save and display"
And I log out
# Now the same image is displayed as "value" and not as "defaultvalue".
And I am on site homepage
Then the image at "//*[contains(@class, 'frontpage-course-list-all')]//*[contains(@class, 'customfield_textarea')]//img[contains(@src, 'pluginfile.php') and contains(@src, '/customfield_textarea/value/') and @alt='Example']" "xpath_element" should be identical to "lib/tests/fixtures/gd-logo.png"
@@ -0,0 +1,49 @@
@customfield @customfield_textarea @javascript
Feature: Managers can manage course custom fields textarea
In order to have additional data on the course
As a manager
I need to create, edit, remove and sort custom fields
Background:
Given the following "custom field categories" exist:
| name | component | area | itemid |
| Category for test | core_course | course | 0 |
And I log in as "admin"
And I navigate to "Courses > Default settings > Course custom fields" in site administration
Scenario: Create a custom course textarea field
When I click on "Add a new custom field" "link"
And I click on "Text area" "link"
And I set the following fields to these values:
| Name | Test field |
| Short name | testfield |
And I click on "Save changes" "button" in the "Adding a new Text area" "dialogue"
Then I should see "Test field"
And I log out
Scenario: Edit a custom course textarea field
When I click on "Add a new custom field" "link"
And I click on "Text area" "link"
And I set the following fields to these values:
| Name | Test field |
| Short name | testfield |
And I click on "Save changes" "button" in the "Adding a new Text area" "dialogue"
And I click on "Edit" "link" in the "Test field" "table_row"
And I set the following fields to these values:
| Name | Edited field |
And I click on "Save changes" "button" in the "Updating Test field" "dialogue"
Then I should see "Edited field"
And I should not see "Test field"
And I log out
Scenario: Delete a custom course textarea field
When I click on "Add a new custom field" "link"
And I click on "Text area" "link"
And I set the following fields to these values:
| Name | Test field |
| Short name | testfield |
And I click on "Save changes" "button" in the "Adding a new Text area" "dialogue"
And I click on "Delete" "link" in the "Test field" "table_row"
And I click on "Yes" "button" in the "Confirm" "dialogue"
Then I should not see "Test field"
And I log out
@@ -0,0 +1,327 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace customfield_textarea;
use core_customfield_generator;
use core_customfield_test_instance_form;
use context_user;
use context_course;
use context_system;
/**
* Functional test for customfield_textarea
*
* @package customfield_textarea
* @copyright 2019 Marina Glancy
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @covers \customfield_textarea\field_controller
* @covers \customfield_textarea\data_controller
*/
class plugin_test extends \advanced_testcase {
/** @var \stdClass[] */
private $courses = [];
/** @var \core_customfield\category_controller */
private $cfcat;
/** @var \core_customfield\field_controller[] */
private $cfields;
/** @var \core_customfield\data_controller[] */
private $cfdata;
/**
* Tests set up.
*/
public function setUp(): void {
$this->resetAfterTest();
$this->cfcat = $this->get_generator()->create_category();
$this->cfields[1] = $this->get_generator()->create_field(
['categoryid' => $this->cfcat->get('id'), 'shortname' => 'myfield1', 'type' => 'textarea']);
$this->cfields[2] = $this->get_generator()->create_field(
['categoryid' => $this->cfcat->get('id'), 'shortname' => 'myfield2', 'type' => 'textarea',
'configdata' => ['required' => 1]]);
$this->cfields[3] = $this->get_generator()->create_field(
['categoryid' => $this->cfcat->get('id'), 'shortname' => 'myfield3', 'type' => 'textarea',
'configdata' => ['defaultvalue' => 'Value3', 'defaultvalueformat' => FORMAT_MOODLE]]);
$this->courses[1] = $this->getDataGenerator()->create_course();
$this->courses[2] = $this->getDataGenerator()->create_course();
$this->courses[3] = $this->getDataGenerator()->create_course();
$this->cfdata[1] = $this->get_generator()->add_instance_data($this->cfields[1], $this->courses[1]->id,
['text' => 'Value1', 'format' => FORMAT_MOODLE]);
$this->cfdata[2] = $this->get_generator()->add_instance_data($this->cfields[1], $this->courses[2]->id,
['text' => '<br />', 'format' => FORMAT_MOODLE]);
$this->setUser($this->getDataGenerator()->create_user());
}
/**
* Get generator
* @return core_customfield_generator
*/
protected function get_generator(): core_customfield_generator {
return $this->getDataGenerator()->get_plugin_generator('core_customfield');
}
/**
* Test for initialising field and data controllers
*/
public function test_initialise(): void {
$f = \core_customfield\field_controller::create($this->cfields[1]->get('id'));
$this->assertTrue($f instanceof field_controller);
$f = \core_customfield\field_controller::create(0, (object)['type' => 'textarea'], $this->cfcat);
$this->assertTrue($f instanceof field_controller);
$d = \core_customfield\data_controller::create($this->cfdata[1]->get('id'));
$this->assertTrue($d instanceof data_controller);
$d = \core_customfield\data_controller::create(0, null, $this->cfields[1]);
$this->assertTrue($d instanceof data_controller);
}
/**
* Test for configuration form functions
*
* Create a configuration form and submit it with the same values as in the field
*/
public function test_config_form(): void {
$this->setAdminUser();
$submitdata = (array)$this->cfields[3]->to_record();
$submitdata['configdata'] = $this->cfields[3]->get('configdata');
$submitdata = \core_customfield\field_config_form::mock_ajax_submit($submitdata);
$form = new \core_customfield\field_config_form(null, null, 'post', '', null, true,
$submitdata, true);
$form->set_data_for_dynamic_submission();
$this->assertTrue($form->is_validated());
$form->process_dynamic_submission();
}
/**
* Test for instance form functions
*/
public function test_instance_form(): void {
global $CFG;
require_once($CFG->dirroot . '/customfield/tests/fixtures/test_instance_form.php');
$this->setAdminUser();
$handler = $this->cfcat->get_handler();
// First try to submit without required field.
$submitdata = (array)$this->courses[1];
core_customfield_test_instance_form::mock_submit($submitdata, []);
$form = new core_customfield_test_instance_form('POST',
['handler' => $handler, 'instance' => $this->courses[1]]);
$this->assertFalse($form->is_validated());
// Now with required field.
$submitdata['customfield_myfield2_editor'] = ['text' => 'Some text', 'format' => FORMAT_HTML];
core_customfield_test_instance_form::mock_submit($submitdata, []);
$form = new core_customfield_test_instance_form('POST',
['handler' => $handler, 'instance' => $this->courses[1]]);
$this->assertTrue($form->is_validated());
$data = $form->get_data();
$this->assertNotEmpty($data->customfield_myfield1_editor);
$this->assertNotEmpty($data->customfield_myfield2_editor);
$handler->instance_form_save($data);
}
/**
* Test that instance form save empties the field content for blank values
*/
public function test_instance_form_save_clear(): void {
global $CFG;
require_once("{$CFG->dirroot}/customfield/tests/fixtures/test_instance_form.php");
$this->setAdminUser();
$handler = $this->cfcat->get_handler();
// Set our custom field to a known value.
$submitdata = (array) $this->courses[1] + [
'customfield_myfield1_editor' => ['text' => 'I can see it in your eyes', 'format' => FORMAT_HTML],
'customfield_myfield2_editor' => ['text' => 'I can see it in your smile', 'format' => FORMAT_HTML],
];
core_customfield_test_instance_form::mock_submit($submitdata, []);
$form = new core_customfield_test_instance_form('post', ['handler' => $handler, 'instance' => $this->courses[1]]);
$handler->instance_form_save($form->get_data());
$this->assertEquals($submitdata['customfield_myfield1_editor']['text'],
\core_customfield\data_controller::create($this->cfdata[1]->get('id'))->export_value());
// Now empty our non-required field.
$submitdata['customfield_myfield1_editor']['text'] = '';
core_customfield_test_instance_form::mock_submit($submitdata, []);
$form = new core_customfield_test_instance_form('post', ['handler' => $handler, 'instance' => $this->courses[1]]);
$handler->instance_form_save($form->get_data());
$this->assertNull(\core_customfield\data_controller::create($this->cfdata[1]->get('id'))->export_value());
}
/**
* Test for data_controller::get_value and export_value
*/
public function test_get_export_value(): void {
$this->assertEquals('Value1', $this->cfdata[1]->get_value());
$this->assertEquals('<div class="text_to_html">Value1</div>', $this->cfdata[1]->export_value());
// Field with empty data.
$this->assertNull($this->cfdata[2]->export_value());
// Field without data but with a default value.
$d = \core_customfield\data_controller::create(0, null, $this->cfields[3]);
$this->assertEquals('Value3', $d->get_value());
$this->assertEquals('<div class="text_to_html">Value3</div>', $d->export_value());
}
/**
* Deleting fields and data
*/
public function test_delete(): void {
$this->cfcat->get_handler()->delete_all();
}
/**
* Test embedded file backup and restore.
*
* @covers \customfield_textarea\data_controller::backup_define_structure
* @covers \customfield_textarea\data_controller::backup_restore_structure
*/
public function test_embedded_file_backup_and_restore(): void {
global $CFG, $USER, $DB;
require_once($CFG->dirroot . '/customfield/tests/fixtures/test_instance_form.php');
$this->setAdminUser();
$handler = $this->cfcat->get_handler();
// Create a file.
$fs = get_file_storage();
$filerecord = [
'contextid' => context_user::instance($USER->id)->id,
'component' => 'user',
'filearea' => 'draft',
'itemid' => file_get_unused_draft_itemid(),
'filepath' => '/',
'filename' => 'mytextfile.txt',
];
$fs->create_file_from_string($filerecord, 'Some text contents');
// Add the file to the custom field.
$submitdata = (array) $this->courses[1];
$submitdata['customfield_myfield1_editor'] = [
'text' => 'Here is a file: @@PLUGINFILE@@/mytextfile.txt',
'format' => FORMAT_HTML,
'itemid' => $filerecord['itemid'],
];
// Set the required field and submit.
$submitdata['customfield_myfield2_editor'] = ['text' => 'Some text', 'format' => FORMAT_HTML];
core_customfield_test_instance_form::mock_submit($submitdata, []);
$form = new core_customfield_test_instance_form('POST',
['handler' => $handler, 'instance' => $this->courses[1]]);
$this->assertTrue($form->is_validated());
$data = $form->get_data();
$this->assertNotEmpty($data->customfield_myfield1_editor);
$this->assertNotEmpty($data->customfield_myfield2_editor);
$handler->instance_form_save($data);
// Check if the draft file exists.
$context = context_course::instance($this->courses[1]->id);
$file = $fs->get_file($filerecord['contextid'], $filerecord['component'], $filerecord['filearea'], $filerecord['itemid'],
$filerecord['filepath'], $filerecord['filename']);
$this->assertNotEmpty($file);
// Check if the permanent file exists.
$file = $fs->get_file($context->id, 'customfield_textarea', 'value', $this->cfdata[1]->get('id'), '/', 'mytextfile.txt');
$this->assertNotEmpty($file);
// Backup and restore the course.
$backupid = $this->backup($this->courses[1]);
$newcourseid = $this->restore($backupid, $this->courses[1], '_copy');
$newcontext = context_course::instance($newcourseid);
$newcfdata = $DB->get_record('customfield_data', ['instanceid' => $newcourseid, 'fieldid' => $this->cfields[1]->get('id')]);
// Check if the permanent file exists in the new course after restore.
$file = $fs->get_file($newcontext->id, 'customfield_textarea', 'value', $newcfdata->id, '/', 'mytextfile.txt');
$this->assertNotEmpty($file);
}
/**
* Backs a course up to temp directory.
*
* @param \stdClass $course Course object to backup
* @return string ID of backup
*/
protected function backup($course): string {
global $USER, $CFG;
require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
// Turn off file logging, otherwise it can't delete the file (Windows).
$CFG->backup_file_logger_level = \backup::LOG_NONE;
// Do backup with default settings. MODE_IMPORT means it will just
// create the directory and not zip it.
$bc = new \backup_controller(\backup::TYPE_1COURSE, $course->id,
\backup::FORMAT_MOODLE, \backup::INTERACTIVE_NO, \backup::MODE_IMPORT,
$USER->id);
$bc->get_plan()->get_setting('users')->set_status(\backup_setting::NOT_LOCKED);
$bc->get_plan()->get_setting('users')->set_value(true);
$bc->get_plan()->get_setting('logs')->set_value(true);
$backupid = $bc->get_backupid();
$bc->execute_plan();
$bc->destroy();
return $backupid;
}
/**
* Restores a course from temp directory.
*
* @param string $backupid Backup id
* @param \stdClass $course Original course object
* @param string $suffix Suffix to add after original course shortname and fullname
* @return int New course id
* @throws \restore_controller_exception
*/
protected function restore(string $backupid, $course, string $suffix): int {
global $USER, $CFG;
require_once($CFG->dirroot . '/backup/util/includes/restore_includes.php');
// Do restore to new course with default settings.
$newcourseid = \restore_dbops::create_new_course(
$course->fullname . $suffix, $course->shortname . $suffix, $course->category);
$rc = new \restore_controller($backupid, $newcourseid,
\backup::INTERACTIVE_NO, \backup::MODE_GENERAL, $USER->id,
\backup::TARGET_NEW_COURSE);
$rc->get_plan()->get_setting('logs')->set_value(true);
$rc->get_plan()->get_setting('users')->set_value(true);
$this->assertTrue($rc->execute_precheck());
$rc->execute_plan();
$rc->destroy();
return $newcourseid;
}
}
+29
View File
@@ -0,0 +1,29 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Customfield text area plugin
*
* @package customfield_textarea
* @copyright 2018 David Matamoros <toni@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$plugin->component = 'customfield_textarea';
$plugin->version = 2024042200;
$plugin->requires = 2024041600;
+5
View File
@@ -0,0 +1,5 @@
This files describes API changes in /customfield/field/* - customfield field types,
information provided here is intended especially for developers.
=== 3.8 ===
* supports_course_grouping() and course_grouping_format_values() functions added to support use of custom fields in block_myoverview