Skip to content

Commit c94b94f

Browse files
norbedg
authored andcommitted
SelectBox: added isOk(), validation moved to rule
1 parent 3566bab commit c94b94f

File tree

2 files changed

+56
-7
lines changed

2 files changed

+56
-7
lines changed

src/Forms/Controls/SelectBox.php

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ public function __construct($label = NULL, array $items = NULL)
2929
{
3030
parent::__construct($label, $items);
3131
$this->setOption('type', 'select');
32+
$this->addRule([$this, 'isOk'], Nette\Forms\Validator::$messages[self::VALID]);
3233
}
3334

3435

@@ -101,15 +102,15 @@ public function getControl()
101102

102103

103104
/**
104-
* Performs the server side validation.
105-
* @return void
105+
* @return bool
106106
*/
107-
public function validate()
107+
public function isOk()
108108
{
109-
parent::validate();
110-
if (!$this->isDisabled() && $this->prompt === FALSE && $this->getValue() === NULL && $this->options && $this->control->size < 2) {
111-
$this->addError(Nette\Forms\Validator::$messages[self::VALID]);
112-
}
109+
return $this->isDisabled()
110+
|| $this->prompt !== FALSE
111+
|| $this->getValue() !== NULL
112+
|| !$this->options
113+
|| $this->control->size > 1;
113114
}
114115

115116
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
<?php
2+
3+
/**
4+
* Test: Nette\Forms\Controls\SelectBox::isOk()
5+
*/
6+
7+
use Nette\Forms\Validator;
8+
use Nette\Forms\Form;
9+
use Tester\Assert;
10+
11+
12+
require __DIR__ . '/../bootstrap.php';
13+
14+
15+
$form = new Form;
16+
$select = $form->addSelect('foo', NULL, ['bar' => 'Bar']);
17+
18+
Assert::false($select->isOk());
19+
20+
$select->setDisabled(TRUE);
21+
Assert::true($select->isOk());
22+
$select->setDisabled(FALSE);
23+
24+
$select->setPrompt('Empty');
25+
Assert::true($select->isOk());
26+
$select->setPrompt(FALSE);
27+
28+
$select->setValue('bar');
29+
Assert::true($select->isOk());
30+
$select->setValue(NULL);
31+
32+
$select->setItems([]);
33+
Assert::true($select->isOk());
34+
$select->setItems(['bar' => 'Bar']);
35+
36+
$select->getControlPrototype()->size = 2;
37+
Assert::true($select->isOk());
38+
$select->getControlPrototype()->size = 1;
39+
Assert::false($select->isOk());
40+
41+
42+
// error message is processed via Rules
43+
$_SERVER['REQUEST_METHOD'] = 'POST';
44+
Validator::$messages[Nette\Forms\Controls\SelectBox::VALID] = 'SelectBox "%label" must be filled.';
45+
$form = new Form;
46+
$form->addSelect('foo', 'Foo', ['bar' => 'Bar']);
47+
$form->fireEvents();
48+
Assert::same(['SelectBox "Foo" must be filled.'], $form->getErrors());

0 commit comments

Comments
 (0)