Browse code

Add default value to select single value select fields

Benjamin Roth authored on14/06/2017 21:19:53
Showing3 changed files
... ...
@@ -13,4 +13,5 @@
13 13
  */
14 14
 
15 15
 //$GLOBALS['TL_CSS']['formilicious'] = 'system/modules/eSM_formilicious/assets/css/form.min.css||static';
16
-$GLOBALS['TL_HOOKS']['loadDataContainer'][] = array('\FormiliciousHooks','eSMLoadDataContainer');
17 16
\ No newline at end of file
17
+$GLOBALS['TL_HOOKS']['loadDataContainer'][] = array('\FormiliciousHooks','eSMLoadDataContainer');
18
+$GLOBALS['TL_HOOKS']['loadFormField'][] = array('\FormiliciousHooks','eSMLoadFormField');
18 19
\ No newline at end of file
... ...
@@ -12,6 +12,11 @@
12 12
  * @author     Benjamin Roth <benjamin@esales-media.de>
13 13
  */
14 14
 
15
+/**
16
+ * Palettes
17
+ */
18
+$GLOBALS['TL_DCA']['tl_form_field']['palettes']['select'] = str_replace(',class,', ',class,value,',$GLOBALS['TL_DCA']['tl_form_field']['palettes']['select']);
19
+
15 20
 
16 21
 /**
17 22
  * Add fields to tl_form_field
... ...
@@ -73,4 +73,46 @@ class FormiliciousHooks extends \Controller
73 73
 			}
74 74
 		}
75 75
 	}
76
+
77
+  /**
78
+   * Hook for adding default value functionality to single value select fields
79
+   * @param \Widget $objWidget
80
+   * @param $strForm
81
+   * @param $arrForm
82
+   * @return \Widget
83
+   */
84
+  public function eSMLoadFormField(\Widget $objWidget, $strForm, $arrForm)
85
+  {
86
+    // Only apply to select fields with multiple off
87
+    if ($objWidget->type == 'select' && !$objWidget->multiple && $objWidget->value != '')
88
+    {
89
+      $arrOptions = (array) $objWidget->options;
90
+      $intSelOption = null;
91
+
92
+      // Iterate options and search for selected values
93
+      foreach ($arrOptions as $k => $option)
94
+      {
95
+        if (!$option['group'] && $option['value'] == $objWidget->value)
96
+        {
97
+          $intSelOption = $k;
98
+          break;
99
+        } else if (!$option['group'] && $option['default'])
100
+        {
101
+          $intSelOption = $k;
102
+        }
103
+        unset($arrOptions[$k]['default']);
104
+      }
105
+
106
+      // Set proper default option
107
+      if ($intSelOption !== null)
108
+      {
109
+        $arrOptions[$intSelOption]['default'] = '1';
110
+      }
111
+
112
+      // Override widget with new options array
113
+      $objWidget->options = $arrOptions;
114
+    }
115
+
116
+    return $objWidget;
117
+  }
76 118
 }
77 119
\ No newline at end of file