Skip to content

Commit b839134

Browse files
MilanPaladg
authored andcommitted
HiddenField: added setNullable() and addFilter() [Closes #171]
1 parent ba33f20 commit b839134

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed

src/Forms/Controls/HiddenField.php

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff 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
*/

tests/Forms/Controls.HiddenField.loadData.phpt

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff 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+
7792
test(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+
});

0 commit comments

Comments
 (0)