1: <?php
2:
3: /**
4: * This file is part of the Nette Framework (https://nette.org)
5: * Copyright (c) 2004 David Grudl (https://davidgrudl.com)
6: */
7:
8: namespace Nette\Forms\Controls;
9:
10: use Nette;
11: use Nette\Forms\Form;
12: use Nette\Utils\Strings;
13:
14:
15: /**
16: * Implements the basic functionality common to text input controls.
17: */
18: abstract class TextBase extends BaseControl
19: {
20: /** @var string */
21: protected $emptyValue = '';
22:
23: /** @var mixed unfiltered submitted value */
24: protected $rawValue = '';
25:
26:
27: /**
28: * Sets control's value.
29: * @param string
30: * @return static
31: * @internal
32: */
33: public function setValue($value)
34: {
35: if ($value === NULL) {
36: $value = '';
37: } elseif (!is_scalar($value) && !method_exists($value, '__toString')) {
38: throw new Nette\InvalidArgumentException(sprintf("Value must be scalar or NULL, %s given in field '%s'.", gettype($value), $this->name));
39: }
40: $this->rawValue = $this->value = $value;
41: return $this;
42: }
43:
44:
45: /**
46: * Returns control's value.
47: * @return string
48: */
49: public function getValue()
50: {
51: return $this->value === Strings::trim($this->translate($this->emptyValue)) ? '' : $this->value;
52: }
53:
54:
55: /**
56: * Sets the special value which is treated as empty string.
57: * @param string
58: * @return static
59: */
60: public function setEmptyValue($value)
61: {
62: $this->emptyValue = (string) $value;
63: return $this;
64: }
65:
66:
67: /**
68: * Returns the special value which is treated as empty string.
69: * @return string
70: */
71: public function getEmptyValue()
72: {
73: return $this->emptyValue;
74: }
75:
76:
77: /**
78: * Sets the maximum number of allowed characters.
79: * @param int
80: * @return static
81: */
82: public function setMaxLength($length)
83: {
84: $this->control->maxlength = $length;
85: return $this;
86: }
87:
88:
89: /**
90: * Appends input string filter callback.
91: * @param callable
92: * @return static
93: */
94: public function addFilter($filter)
95: {
96: $this->rules->addFilter($filter);
97: return $this;
98: }
99:
100:
101: public function getControl()
102: {
103: $el = parent::getControl();
104: if ($this->emptyValue !== '') {
105: $el->attrs['data-nette-empty-value'] = Strings::trim($this->translate($this->emptyValue));
106: }
107: if (isset($el->placeholder)) {
108: $el->placeholder = $this->translate($el->placeholder);
109: }
110: return $el;
111: }
112:
113:
114: public function addRule($validator, $message = NULL, $arg = NULL)
115: {
116: if ($validator === Form::LENGTH || $validator === Form::MAX_LENGTH) {
117: $tmp = is_array($arg) ? $arg[1] : $arg;
118: if (is_scalar($tmp)) {
119: $this->control->maxlength = isset($this->control->maxlength) ? min($this->control->maxlength, $tmp) : $tmp;
120: }
121: }
122: return parent::addRule($validator, $message, $arg);
123: }
124:
125: }
126: