From b1bd4f250aabea15ec81cc45009cbca9d406abc0 Mon Sep 17 00:00:00 2001
From: Peter Rotich <peter@enhancesoft.com>
Date: Mon, 9 Mar 2015 15:59:51 +0000
Subject: [PATCH] forms: Include all dynamic fields

Get all dynamic fields in DynamicFormEntry, not just fields with answers
---
 include/class.dynamic_forms.php | 17 +++++++++++++++--
 include/class.forms.php         | 10 +++++++---
 2 files changed, 22 insertions(+), 5 deletions(-)

diff --git a/include/class.dynamic_forms.php b/include/class.dynamic_forms.php
index 364d29dfa..6793ba2db 100644
--- a/include/class.dynamic_forms.php
+++ b/include/class.dynamic_forms.php
@@ -706,11 +706,24 @@ class DynamicFormEntry extends VerySimpleModel {
     function getFields() {
         if (!isset($this->_fields)) {
             $this->_fields = array();
+            // Get all dynamic fields associated with the form
+            //  even when stored elsewhere -- important during validation
+            foreach ($this->getForm()->getDynamicFields() as $field) {
+                $field->setForm($this);
+                $this->_fields[$field->get('id')] = $field->getImpl($field);
+            }
+            // Get answers to entries
             foreach ($this->getAnswers() as $a) {
-                $T = $this->_fields[] = $a->getField();
-                $T->setForm($this);
+                if (!($f = $a->getField())) continue;
+                if (isset($this->_fields[$f->get('id')]))
+                    $this->_fields[$f->get('id')] = $f;
+                else { // Perhaps an answer of deleted field
+                    $f->setForm($this);
+                    $this->_fields[] = $f;
+                }
             }
         }
+
         return $this->_fields;
     }
 
diff --git a/include/class.forms.php b/include/class.forms.php
index 46f76905a..70c0510a6 100644
--- a/include/class.forms.php
+++ b/include/class.forms.php
@@ -962,7 +962,7 @@ class ChoiceField extends FormField {
         $config = $this->getConfiguration();
         if (!$config['multiselect'] && is_array($value) && count($value) < 2) {
             reset($value);
-            return key($value);
+            $value = key($value);
         }
         return $value;
     }
@@ -1899,9 +1899,12 @@ class ChoicesWidget extends Widget {
     }
 
     function getValue() {
-        $value = parent::getValue();
 
-        if (!$value) return null;
+        if (!($value = parent::getValue()))
+            return null;
+
+        if ($value && !is_array($value))
+            $value = array($value);
 
         // Assume multiselect
         $values = array();
@@ -1912,6 +1915,7 @@ class ChoicesWidget extends Widget {
                     $values[$v] = $choices[$v];
             }
         }
+
         return $values;
     }
 
-- 
GitLab