diff --git a/lib/adminlib.php b/lib/adminlib.php index 8b2f4029364..c6a3219fc61 100644 --- a/lib/adminlib.php +++ b/lib/adminlib.php @@ -3234,6 +3234,8 @@ class admin_setting_configselect extends admin_setting { public $optgroups; /** @var callable|null Loader function for choices */ protected $choiceloader = null; + /** @var callable|null Validation function */ + protected $validatefunction = null; /** * Constructor. @@ -3267,6 +3269,19 @@ class admin_setting_configselect extends admin_setting { parent::__construct($name, $visiblename, $description, $defaultsetting); } + /** + * Sets a validate function. + * + * The callback will be passed one parameter, the new setting value, and should return either + * an empty string '' if the value is OK, or an error message if not. + * + * @param callable|null $validatefunction Validate function or null to clear + * @since Moodle 4.0 + */ + public function set_validate_function(?callable $validatefunction = null) { + $this->validatefunction = $validatefunction; + } + /** * This function may be used in ancestors for lazy loading of choices * @@ -3332,9 +3347,32 @@ class admin_setting_configselect extends admin_setting { return ''; // ignore it } + // Validate the new setting. + $error = $this->validate_setting($data); + if ($error) { + return $error; + } + return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin')); } + /** + * Validate the setting. This uses the callback function if provided; subclasses could override + * to carry out validation directly in the class. + * + * @param string $data New value being set + * @return string Empty string if valid, or error message text + * @since Moodle 4.0 + */ + protected function validate_setting(string $data): string { + // If validation function is specified, call it now. + if ($this->validatefunction) { + return call_user_func($this->validatefunction, $data); + } else { + return ''; + } + } + /** * Returns XHTML select field * diff --git a/lib/upgrade.txt b/lib/upgrade.txt index 5c14744310c..60a675eba42 100644 --- a/lib/upgrade.txt +++ b/lib/upgrade.txt @@ -34,6 +34,8 @@ information provided here is intended especially for developers. * The class coursecat_sortable_records has been removed. * Admin setting admin_setting_configselect now supports lazy-loading the options list by supplying a callback function instead of an array of options. +* Admin setting admin_setting_configselect now supports validating the selection by supplying a + callback function. === 3.9 === * Following function has been deprecated, please use \core\task\manager::run_from_cli().