From c71f6676ca20fb82df54964e2969cbd6a1b1e326 Mon Sep 17 00:00:00 2001 From: Jared Hancock <jared@osticket.com> Date: Mon, 24 Nov 2014 13:52:09 -0600 Subject: [PATCH] forms: Add getState() and loadState() methods This allows stashing a forms current state and restoring it later --- include/class.forms.php | 48 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/include/class.forms.php b/include/class.forms.php index cac2c73cd..e929c8450 100644 --- a/include/class.forms.php +++ b/include/class.forms.php @@ -162,6 +162,51 @@ class Form { break; } } + + /** + * getState + * + * Retrieves an array of information which can be passed to the + * ::loadState method later to recreate the current state of the form + * fields and values. + */ + function getState() { + $info = array(); + foreach ($this->getFields() as $f) { + // Skip invisible fields + if (!$f->isVisible()) + continue; + + // Skip fields set to default values + $v = $f->getClean(); + $d = $f->get('default'); + if ($v == $d) + continue; + + // Skip empty values + if (!$v) + continue; + + $info[$f->get('name')] = $f->to_database($v); + } + return $info; + } + + /** + * loadState + * + * Reset this form to the state previously recorded by the ::getState() + * method + */ + function loadState($state) { + foreach ($this->getFields() as $f) { + $name = $f->get('name'); + $f->reset(); + if (isset($state[$name])) { + $f->value = $f->to_php($state[$name]); + } + } + } } require_once(INCLUDE_DIR . "class.json.php"); @@ -269,6 +314,9 @@ class FormField { if ($this->isVisible()) $this->validateEntry($this->_clean); + + if (!isset($this->_clean) && ($d = $this->get('default'))) + $this->_clean = $d; } return $this->_clean; } -- GitLab