diff --git a/user/profile/field/text/field.class.php b/user/profile/field/text/field.class.php index b88d8735b75..8d85f2b129c 100644 --- a/user/profile/field/text/field.class.php +++ b/user/profile/field/text/field.class.php @@ -70,6 +70,33 @@ class profile_field_text extends profile_field_base { $mform->setType($this->inputname, PARAM_TEXT); } + /** + * Process the data before it gets saved in database + * + * @param string|null $data + * @param stdClass $datarecord + * @return string|null + */ + public function edit_save_data_preprocess($data, $datarecord) { + if ($data === null) { + return null; + } + return core_text::substr($data, 0, $this->field->param2); + } + + /** + * Convert external data (csv file) from value to key for processing later by edit_save_data_preprocess + * + * @param string $data + * @return string|null + */ + public function convert_external_data($data) { + if (core_text::strlen($data) > $this->field->param2) { + return null; + } + return $data; + } + /** * Return the field type and null properties. * This will be used for validating the data submitted by a user. diff --git a/user/profile/field/text/tests/field_class_test.php b/user/profile/field/text/tests/field_class_test.php index bdde7f88d65..e0936f845ac 100644 --- a/user/profile/field/text/tests/field_class_test.php +++ b/user/profile/field/text/tests/field_class_test.php @@ -69,5 +69,49 @@ class field_class_test extends \advanced_testcase { 'emoticons_filter' => ['No emoticons filter :-(', 'No emoticons filter :-('] ]; } + + /** + * Test preprocess data validation + */ + public function test_edit_save_data_preprocess(): void { + $this->resetAfterTest(); + + $fielddata = $this->getDataGenerator()->create_custom_profile_field([ + 'datatype' => 'text', + 'name' => 'Test', + 'shortname' => 'test', + 'param2' => 5, // Max length. + ]); + $field = new profile_field_text(0, 0, $fielddata); + + $value = $field->edit_save_data_preprocess('ABCDE', new \stdClass()); + $this->assertEquals('ABCDE', $value); + + // Exceed max length. + $value = $field->edit_save_data_preprocess('ABCDEF', new \stdClass()); + $this->assertEquals('ABCDE', $value); + } + + /** + * Test external data validation + */ + public function test_convert_external_data(): void { + $this->resetAfterTest(); + + $fielddata = $this->getDataGenerator()->create_custom_profile_field([ + 'datatype' => 'text', + 'name' => 'Test', + 'shortname' => 'test', + 'param2' => 5, // Max length. + ]); + $field = new profile_field_text(0, 0, $fielddata); + + $value = $field->convert_external_data('ABCDE'); + $this->assertEquals('ABCDE', $value); + + // Exceed max length. + $value = $field->convert_external_data('ABCDEF'); + $this->assertNull($value); + } }