From 1df98b3b42ef8ca733d0f89047f8c9843bd99c1b Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Fran=C3=A7ois=20Grand?= <francois.grand@inrae.fr>
Date: Fri, 27 Jan 2023 15:51:26 +0100
Subject: [PATCH] fix: modify SelectField.findAndSetDefaultValue() to use nub
 value for associated property

refs #592
---
 .../elements/select/select-field.ts           | 23 +++++++++++++++----
 1 file changed, 19 insertions(+), 4 deletions(-)

diff --git a/src/app/formulaire/elements/select/select-field.ts b/src/app/formulaire/elements/select/select-field.ts
index 4de4cfcaa..4e1c92b50 100644
--- a/src/app/formulaire/elements/select/select-field.ts
+++ b/src/app/formulaire/elements/select/select-field.ts
@@ -132,22 +132,37 @@ export abstract class SelectField extends Field {
     }
 
     /**
-     * try to find a default value to select
+     * Try to find a default value to select.
+     * Priority order :
+     *   - passed parameter
+     *   - nub value for associated property
+     *   - default value from configuration file
+     *   - first select entry
      */
     protected findAndSetDefaultValue(value?: string) {
         // default to first available entry if any
         if (this._entries.length > 0) {
             let val: SelectEntry;
+
             if (value !== undefined) {
                 val = this.getEntryFromValue(enumValueFromString(this._associatedProperty, value));
-            } else if (this._configDefaultValue === undefined) {
-                val = this._entries[0];
-            } else {
+                if (val === undefined) {
+                    throw Error("invalid select default value " + value + " for " + this._associatedProperty + " property");
+                }
+            } else if (this.nub !== undefined) {
+                val = this.getEntryFromValue(this.nub.getPropValue(this._associatedProperty));
+                if (val === undefined) {
+                    throw Error("invalid select default value for " + this._associatedProperty + " property");
+                }
+            } else if (this._configDefaultValue !== undefined) {
                 val = this.getEntryFromValue(enumValueFromString(this._associatedProperty, this._configDefaultValue));
                 if (val === undefined) {
                     throw Error("invalid select default value " + this._configDefaultValue + " for " + this._associatedProperty + " property");
                 }
+            } else {
+                val = this._entries[0];
             }
+
             if (this._multiple) {
                 this.setValue([val]);
             } else {
-- 
GitLab