From 0c2c3b0c7935a053c148d15cb61d5c3e8a00ef2b Mon Sep 17 00:00:00 2001 From: Ad Schellevis Date: Sun, 15 Oct 2023 13:13:22 +0200 Subject: [PATCH] mvc: UnqiueIdField - enforce uniqueness and remove validation message. closes https://github.com/opnsense/core/issues/6877 This field type is hardly used, but the intention was to generate a new uniqueid on creation and make it stick. Trying to remember the last know stored value is rather tricky (certainly when it comes to cloning), but making sure we ignore values saved isn't that hard. Although this doesn't win the beauty contest, at least it does make sure uniqid() is called for every new field. Either when cloning the field or calling a set on an empty entry. --- .../Base/FieldTypes/UniqueIdField.php | 49 +++++++++++-------- 1 file changed, 29 insertions(+), 20 deletions(-) diff --git a/src/opnsense/mvc/app/models/OPNsense/Base/FieldTypes/UniqueIdField.php b/src/opnsense/mvc/app/models/OPNsense/Base/FieldTypes/UniqueIdField.php index f179cee76..ca4ee9aff 100644 --- a/src/opnsense/mvc/app/models/OPNsense/Base/FieldTypes/UniqueIdField.php +++ b/src/opnsense/mvc/app/models/OPNsense/Base/FieldTypes/UniqueIdField.php @@ -1,7 +1,7 @@ internalValue) && empty($this->initialValue)) { - // trigger initial value on change, before returning validators - // (new nodes will always be marked as "changed", see isFieldChanged()) - // Maybe we should add an extra event handler if this kind of scenarios happen more often, similar to - // actionPostLoadingEvent. (which is not triggered on setting data for a complete new structure node) - $this->internalValue = uniqid('', true); - $this->initialValue = $this->internalValue; + if (empty((string)$this) && $this->fieldLoaded) { + parent::setValue(uniqid('', true)); + } elseif (empty((string)$this) && !$this->fieldLoaded) { + parent::setValue($value); } - $validators = parent::getValidators(); - // unique id may not change.. - $validators[] = new InclusionIn([ - 'message' => gettext('Unique ID is immutable.'), - 'domain' => [$this->initialValue], - ]); - return $validators; } + + /** + * {@inheritdoc} + */ + protected function actionPostLoadingEvent() + { + parent::actionPostLoadingEvent(); + $this->fieldLoaded = true; + } + + /** + * {@inheritdoc} + */ + public function applyDefault() + { + /** When cloned (add), set our default to a new uniqueid */ + $this->fieldLoaded = true; + $this->setValue(null); + } + }