File tree Expand file tree Collapse file tree 2 files changed +68
-0
lines changed Expand file tree Collapse file tree 2 files changed +68
-0
lines changed Original file line number Diff line number Diff line change @@ -20,6 +20,9 @@ class HiddenField extends BaseControl
2020 /** @var bool */
2121 private $ persistValue ;
2222
23+ /** @var bool */
24+ private $ nullable = false ;
25+
2326
2427 public function __construct ($ persistentValue = null )
2528 {
@@ -53,6 +56,38 @@ public function setValue($value)
5356 }
5457
5558
59+ /**
60+ * Returns control's value.
61+ * @return mixed
62+ */
63+ public function getValue ()
64+ {
65+ return $ this ->nullable && $ this ->value === '' ? null : $ this ->value ;
66+ }
67+
68+
69+ /**
70+ * Sets whether getValue() returns null instead of empty string.
71+ * @return static
72+ */
73+ public function setNullable (bool $ value = true )
74+ {
75+ $ this ->nullable = $ value ;
76+ return $ this ;
77+ }
78+
79+
80+ /**
81+ * Appends input string filter callback.
82+ * @return static
83+ */
84+ public function addFilter (callable $ filter )
85+ {
86+ $ this ->getRules ()->addFilter ($ filter );
87+ return $ this ;
88+ }
89+
90+
5691 /**
5792 * Generates control's HTML element.
5893 */
Original file line number Diff line number Diff line change @@ -74,6 +74,21 @@ test(function () { // object
7474});
7575
7676
77+ test (function () { // object from string by filter
78+ $ date = new Nette \Utils \DateTime ('2013-07-05 ' );
79+ $ _POST = ['text ' => (string ) $ date ];
80+ $ form = new Form ;
81+ $ input = $ form ->addHidden ('text ' );
82+ $ input ->addFilter (function ($ value ) {
83+ return $ value ? new \Nette \Utils \DateTime ($ value ) : $ value ;
84+ });
85+
86+ Assert::same ((string ) $ date , $ input ->getValue ());
87+ $ input ->validate ();
88+ Assert::equal ($ date , $ input ->getValue ());
89+ });
90+
91+
7792test (function () { // int from string
7893 $ _POST = ['text ' => '10 ' ];
7994 $ form = new Form ;
@@ -93,3 +108,21 @@ test(function () { // persistent
93108
94109 Assert::same ('persistent ' , $ input ->getValue ());
95110});
111+
112+
113+ test (function () { // nullable
114+ $ form = new Form ;
115+ $ input = $ form ->addHidden ('hidden ' );
116+ $ input ->setValue ('' );
117+ $ input ->setNullable ();
118+ Assert::null ($ input ->getValue ());
119+ });
120+
121+
122+ test (function () { // nullable
123+ $ form = new Form ;
124+ $ input = $ form ->addHidden ('hidden ' );
125+ $ input ->setValue (null );
126+ $ input ->setNullable ();
127+ Assert::null ($ input ->getValue ());
128+ });
You can’t perform that action at this time.
0 commit comments