From b2511369a6894d00efb9a421bdfbbff19e527b6e Mon Sep 17 00:00:00 2001 From: Maximilian Haye Date: Thu, 19 Dec 2024 18:16:58 +0100 Subject: [PATCH] feat: add generated_id_element See: questionpy-org/questionpy-sdk#140 --- classes/form/elements/form_element.php | 3 +- .../form/elements/generated_id_element.php | 60 +++++++++++++++++++ 2 files changed, 62 insertions(+), 1 deletion(-) create mode 100644 classes/form/elements/generated_id_element.php diff --git a/classes/form/elements/form_element.php b/classes/form/elements/form_element.php index 852b3ae..fcc3ca0 100644 --- a/classes/form/elements/form_element.php +++ b/classes/form/elements/form_element.php @@ -27,7 +27,7 @@ * @copyright 2022 TU Berlin, innoCampus {@link https://www.questionpy.org} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -#[array_polymorphic('kind', variants: [ +#[array_polymorphic(discriminator: 'kind', variants: [ 'checkbox' => checkbox_element::class, 'checkbox_group' => checkbox_group_element::class, 'group' => group_element::class, @@ -38,6 +38,7 @@ 'static_text' => static_text_element::class, 'input' => text_input_element::class, 'textarea' => text_area_element::class, + 'id' => generated_id_element::class, ], fallbackvariant: fallback_element::class)] abstract class form_element implements qpy_renderable { } diff --git a/classes/form/elements/generated_id_element.php b/classes/form/elements/generated_id_element.php new file mode 100644 index 0000000..44ca247 --- /dev/null +++ b/classes/form/elements/generated_id_element.php @@ -0,0 +1,60 @@ +. + +namespace qtype_questionpy\form\elements; + +use core\uuid; +use qtype_questionpy\form\context\render_context; + + +/** + * Generates a unique ID which won't change across form saves. + * + * @package qtype_questionpy + * @author Maximilian Haye + * @copyright 2024 TU Berlin, innoCampus {@link https://www.questionpy.org} + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class generated_id_element extends form_element { + /** + * Trivial constructor. + * + * @param string $name + */ + public function __construct( + /** @var string $name */ + public string $name + ) { + } + + /** + * Render this item to the given context. + * + * @param render_context $context target context + * @package qtype_questionpy + */ + public function render_to(render_context $context): void { + $mangledname = $context->mangle_name($this->name); + $value = $context->moodleform->optional_param( + $mangledname, + null, + PARAM_ALPHANUMEXT + ) ?? $context->data[$this->name] ?? uuid::generate(); + + $context->add_element('hidden', $mangledname, $value); + $context->set_type($this->name, PARAM_ALPHANUMEXT); + } +} \ No newline at end of file