From 0e85a156dce72666ec7c736f403ac2d6dc29d7c5 Mon Sep 17 00:00:00 2001
From: JediKev <kevin@enhancesoft.com>
Date: Tue, 12 Sep 2017 11:24:59 -0500
Subject: [PATCH] oops: Dept Field Display

This addresses an issue where the Department field does not save or
display the value correctly. This updates all the display/save methods in
the DepartmentField Class to save and display the value correctly.
---
 include/class.forms.php | 45 ++++++++++++++++++++++++++++++++++-------
 1 file changed, 38 insertions(+), 7 deletions(-)

diff --git a/include/class.forms.php b/include/class.forms.php
index c097dd995..57df48b57 100644
--- a/include/class.forms.php
+++ b/include/class.forms.php
@@ -1628,6 +1628,8 @@ class ChoiceField extends FormField {
         $deleted = array_diff($B, $A);
         $added = array_map(array($this, 'display'), $added);
         $deleted = array_map(array($this, 'display'), $deleted);
+        $added = array_filter($added);
+        $deleted = array_filter($deleted);
 
         if ($added && $deleted) {
             $desc = sprintf(
@@ -2368,23 +2370,52 @@ class DepartmentField extends ChoiceField {
     }
 
     function to_php($value, $id=false) {
-        if (is_array($id)) {
-            reset($id);
-            $id = key($id);
+        if ($id) {
+            if (is_array($id)) {
+                reset($id);
+                $id = key($id);
+            }
+            return $id;
+        } else {
+            return $value;
         }
-        return $id;
     }
 
     function to_database($dept) {
-        return ($dept instanceof Dept)
-            ? array($dept->getName(), $dept->getId())
-            : $dept;
+        if ($dept instanceof Dept)
+            return array($dept->getName(), $dept->getId());
+
+        if (!is_array($dept)) {
+            $choices = $this->getChoices();
+            if (isset($choices[$dept]))
+                $dept = array($choices[$dept], $dept);
+        }
+        if (!$dept)
+            $dept = array();
+
+        return $dept;
     }
 
     function toString($value) {
+        if (!is_array($value))
+            $value = $this->getChoice($value);
+        if (is_array($value))
+            return implode(', ', $value);
         return (string) $value;
     }
 
+    function getChoice($value) {
+        $choices = $this->getChoices();
+        $selection = array();
+        if ($value && is_array($value)) {
+            $selection = $value;
+        } elseif (isset($choices[$value])) {
+            $selection[] = $choices[$value];
+        }
+
+        return $selection;
+    }
+
     function searchable($value) {
         return null;
     }
-- 
GitLab