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