Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

The function for a field can be:

  • An existing field formatter class name or instance (we ship it with string_field_formatter, text_field_formatter, date_field_formatter)
  • Any custom method name defined within the same class
  • A Closure taking only the value as argument, for simple value modifications
  • A Closure taking the value and a type-hinted field formatter, the field formatter will be automatically instantiated

...

Code Block
languagephp
titleField formatter example
class custom_field_formatter extends \core\webapi\formatter\field\base {

    protected function validate_format(): bool {
        // validate whether $this->format is the expected one
		// A good practice is to validate against constants
		// for example:
		return defined('self::FORMAT_.'.strtoupper($this->format));
    }

    protected function get_default_format($value) {
		// This is called when there's no specific format_...() function
        // If all relevant formats are covered by functions you do not need to override this
        return ...;
    }

    protected function format_html($value) {
        // This is called for format == 'html'
        // implement functions for your specific format by following the format_[formatname]() pattern
    }

}


Testing formatters 

We have a model, model_client_settings. Let's try using the formatter to format one field on it:


$context = context_helper::instance_by_id(CONTEXT_SYSTEM);

$formatter = new client_settings_formatter($model_client_settings, $context);

 

// Operate

$field = 'default_token_expiry_time';

$formatted_field_result = $formatter->format($field);

 

// Assert

self::assertEquals((string)$model_client_settings->default_token_expiry_time, $formatted_field_result);