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 self
31: */
32: public function setValue($value)
33: {
34: if ($value === NULL) {
35: $value = '';
36: } elseif (!is_scalar($value) && !method_exists($value, '__toString')) {
37: throw new Nette\InvalidArgumentException(sprintf("Value must be scalar or NULL, %s given in field '%s'.", gettype($value), $this->name));
38: }
39: $this->rawValue = $this->value = $value;
40: return $this;
41: }
42:
43:
44: /**
45: * Returns control's value.
46: * @return string
47: */
48: public function getValue()
49: {
50: return $this->value === Strings::trim($this->translate($this->emptyValue)) ? '' : $this->value;
51: }
52:
53:
54: /**
55: * Sets the special value which is treated as empty string.
56: * @param string
57: * @return self
58: */
59: public function setEmptyValue($value)
60: {
61: $this->emptyValue = (string) $value;
62: return $this;
63: }
64:
65:
66: /**
67: * Returns the special value which is treated as empty string.
68: * @return string
69: */
70: public function getEmptyValue()
71: {
72: return $this->emptyValue;
73: }
74:
75:
76: /**
77: * Sets the maximum number of allowed characters.
78: * @param int
79: * @return self
80: */
81: public function setMaxLength($length)
82: {
83: $this->control->maxlength = $length;
84: return $this;
85: }
86:
87:
88: /**
89: * Appends input string filter callback.
90: * @param callable
91: * @return self
92: */
93: public function addFilter($filter)
94: {
95: $this->rules->addFilter($filter);
96: return $this;
97: }
98:
99:
100: public function getControl()
101: {
102: $el = parent::getControl();
103: if ($this->emptyValue !== '') {
104: $el->attrs['data-nette-empty-value'] = Strings::trim($this->translate($this->emptyValue));
105: }
106: if (isset($el->placeholder)) {
107: $el->placeholder = $this->translate($el->placeholder);
108: }
109: return $el;
110: }
111:
112:
113: public function addRule($validator, $message = NULL, $arg = NULL)
114: {
115: if ($validator === Form::LENGTH || $validator === Form::MAX_LENGTH) {
116: $tmp = is_array($arg) ? $arg[1] : $arg;
117: if (is_scalar($tmp)) {
118: $this->control->maxlength = isset($this->control->maxlength) ? min($this->control->maxlength, $tmp) : $tmp;
119: }
120: }
121: return parent::addRule($validator, $message, $arg);
122: }
123:
124: }
125: