Packages

  • Nette
    • Application
      • Diagnostics
      • Responses
      • Routers
      • UI
    • Caching
      • Storages
    • ComponentModel
    • Config
      • Adapters
      • Extensions
    • Database
      • Diagnostics
      • Drivers
      • Reflection
      • Table
    • DI
      • Diagnostics
    • Diagnostics
    • Forms
      • Controls
      • Rendering
    • Http
    • Iterators
    • Latte
      • Macros
    • Loaders
    • Localization
    • Mail
    • Reflection
    • Security
      • Diagnostics
    • Templating
    • Utils
      • PhpGenerator
  • NetteModule
  • None
  • PHP

Classes

  • Button
  • Checkbox
  • FormControl
  • HiddenField
  • ImageButton
  • MultiSelectBox
  • RadioList
  • SelectBox
  • SubmitButton
  • TextArea
  • TextBase
  • TextInput
  • UploadControl
  • Overview
  • Package
  • Class
  • Tree
  • Deprecated
  1: <?php
  2: 
  3: /**
  4:  * This file is part of the Nette Framework (http://nette.org)
  5:  *
  6:  * Copyright (c) 2004 David Grudl (http://davidgrudl.com)
  7:  *
  8:  * For the full copyright and license information, please view
  9:  * the file license.txt that was distributed with this source code.
 10:  * @package Nette\Forms\Controls
 11:  */
 12: 
 13: 
 14: 
 15: /**
 16:  * Base class that implements the basic functionality common to form controls.
 17:  *
 18:  * @author     David Grudl
 19:  *
 20:  * @property-read Form $form
 21:  * @property-read string $htmlName
 22:  * @property   string $htmlId
 23:  * @property-read array $options
 24:  * @property   ITranslator|NULL $translator
 25:  * @property   mixed $value
 26:  * @property-read bool $filled
 27:  * @property-write $defaultValue
 28:  * @property   bool $disabled
 29:  * @property-read Html $control
 30:  * @property-read Html $label
 31:  * @property-read Html $controlPrototype
 32:  * @property-read Html $labelPrototype
 33:  * @property-read Rules $rules
 34:  * @property   bool $required
 35:  * @property-read array $errors
 36:  * @package Nette\Forms\Controls
 37:  */
 38: abstract class FormControl extends Component implements IFormControl
 39: {
 40:     /** @var string */
 41:     public static $idMask = 'frm%s-%s';
 42: 
 43:     /** @var string textual caption or label */
 44:     public $caption;
 45: 
 46:     /** @var mixed unfiltered control value */
 47:     protected $value;
 48: 
 49:     /** @var Html  control element template */
 50:     protected $control;
 51: 
 52:     /** @var Html  label element template */
 53:     protected $label;
 54: 
 55:     /** @var array */
 56:     private $errors = array();
 57: 
 58:     /** @var bool */
 59:     private $disabled = FALSE;
 60: 
 61:     /** @var string */
 62:     private $htmlId;
 63: 
 64:     /** @var string */
 65:     private $htmlName;
 66: 
 67:     /** @var Rules */
 68:     private $rules;
 69: 
 70:     /** @var ITranslator */
 71:     private $translator = TRUE; // means autodetect
 72: 
 73:     /** @var array user options */
 74:     private $options = array();
 75: 
 76: 
 77: 
 78:     /**
 79:      * @param  string  caption
 80:      */
 81:     public function __construct($caption = NULL)
 82:     {
 83:         $this->monitor('Form');
 84:         parent::__construct();
 85:         $this->control = Html::el('input');
 86:         $this->label = Html::el('label');
 87:         $this->caption = $caption;
 88:         $this->rules = new Rules($this);
 89:     }
 90: 
 91: 
 92: 
 93:     /**
 94:      * This method will be called when the component becomes attached to Form.
 95:      * @param  IComponent
 96:      * @return void
 97:      */
 98:     protected function attached($form)
 99:     {
100:         if (!$this->disabled && $form instanceof Form && $form->isAnchored() && $form->isSubmitted()) {
101:             $this->htmlName = NULL;
102:             $this->loadHttpData();
103:         }
104:     }
105: 
106: 
107: 
108:     /**
109:      * Returns form.
110:      * @param  bool   throw exception if form doesn't exist?
111:      * @return Form
112:      */
113:     public function getForm($need = TRUE)
114:     {
115:         return $this->lookup('Form', $need);
116:     }
117: 
118: 
119: 
120:     /**
121:      * Returns HTML name of control.
122:      * @return string
123:      */
124:     public function getHtmlName()
125:     {
126:         if ($this->htmlName === NULL) {
127:             $name = str_replace(self::NAME_SEPARATOR, '][', $this->lookupPath('Form'), $count);
128:             if ($count) {
129:                 $name = substr_replace($name, '', strpos($name, ']'), 1) . ']';
130:             }
131:             if (is_numeric($name) || in_array($name, array('attributes','children','elements','focus','length','reset','style','submit','onsubmit'))) {
132:                 $name .= '_';
133:             }
134:             $this->htmlName = $name;
135:         }
136:         return $this->htmlName;
137:     }
138: 
139: 
140: 
141:     /**
142:      * Changes control's HTML id.
143:      * @param  string new ID, or FALSE or NULL
144:      * @return FormControl  provides a fluent interface
145:      */
146:     public function setHtmlId($id)
147:     {
148:         $this->htmlId = $id;
149:         return $this;
150:     }
151: 
152: 
153: 
154:     /**
155:      * Returns control's HTML id.
156:      * @return string
157:      */
158:     public function getHtmlId()
159:     {
160:         if ($this->htmlId === FALSE) {
161:             return NULL;
162: 
163:         } elseif ($this->htmlId === NULL) {
164:             $this->htmlId = sprintf(self::$idMask, $this->getForm()->getName(), $this->lookupPath('Form'));
165:         }
166:         return $this->htmlId;
167:     }
168: 
169: 
170: 
171:     /**
172:      * Changes control's HTML attribute.
173:      * @param  string name
174:      * @param  mixed  value
175:      * @return FormControl  provides a fluent interface
176:      */
177:     public function setAttribute($name, $value = TRUE)
178:     {
179:         $this->control->$name = $value;
180:         return $this;
181:     }
182: 
183: 
184: 
185:     /**
186:      * Sets user-specific option.
187:      * Options recognized by DefaultFormRenderer
188:      * - 'description' - textual or Html object description
189:      *
190:      * @param  string key
191:      * @param  mixed  value
192:      * @return FormControl  provides a fluent interface
193:      */
194:     public function setOption($key, $value)
195:     {
196:         if ($value === NULL) {
197:             unset($this->options[$key]);
198: 
199:         } else {
200:             $this->options[$key] = $value;
201:         }
202:         return $this;
203:     }
204: 
205: 
206: 
207:     /**
208:      * Returns user-specific option.
209:      * @param  string key
210:      * @param  mixed  default value
211:      * @return mixed
212:      */
213:     final public function getOption($key, $default = NULL)
214:     {
215:         return isset($this->options[$key]) ? $this->options[$key] : $default;
216:     }
217: 
218: 
219: 
220:     /**
221:      * Returns user-specific options.
222:      * @return array
223:      */
224:     final public function getOptions()
225:     {
226:         return $this->options;
227:     }
228: 
229: 
230: 
231:     /********************* translator ****************d*g**/
232: 
233: 
234: 
235:     /**
236:      * Sets translate adapter.
237:      * @return FormControl  provides a fluent interface
238:      */
239:     public function setTranslator(ITranslator $translator = NULL)
240:     {
241:         $this->translator = $translator;
242:         return $this;
243:     }
244: 
245: 
246: 
247:     /**
248:      * Returns translate adapter.
249:      * @return ITranslator|NULL
250:      */
251:     final public function getTranslator()
252:     {
253:         if ($this->translator === TRUE) {
254:             return $this->getForm(FALSE) ? $this->getForm()->getTranslator() : NULL;
255:         }
256:         return $this->translator;
257:     }
258: 
259: 
260: 
261:     /**
262:      * Returns translated string.
263:      * @param  string
264:      * @param  int      plural count
265:      * @return string
266:      */
267:     public function translate($s, $count = NULL)
268:     {
269:         $translator = $this->getTranslator();
270:         return $translator === NULL || $s == NULL ? $s : $translator->translate($s, $count); // intentionally ==
271:     }
272: 
273: 
274: 
275:     /********************* interface IFormControl ****************d*g**/
276: 
277: 
278: 
279:     /**
280:      * Sets control's value.
281:      * @param  mixed
282:      * @return FormControl  provides a fluent interface
283:      */
284:     public function setValue($value)
285:     {
286:         $this->value = $value;
287:         return $this;
288:     }
289: 
290: 
291: 
292:     /**
293:      * Returns control's value.
294:      * @return mixed
295:      */
296:     public function getValue()
297:     {
298:         return $this->value;
299:     }
300: 
301: 
302: 
303:     /**
304:      * Is control filled?
305:      * @return bool
306:      */
307:     public function isFilled()
308:     {
309:         return (string) $this->getValue() !== ''; // NULL, FALSE, '' ==> FALSE
310:     }
311: 
312: 
313: 
314:     /**
315:      * Sets control's default value.
316:      * @param  mixed
317:      * @return FormControl  provides a fluent interface
318:      */
319:     public function setDefaultValue($value)
320:     {
321:         $form = $this->getForm(FALSE);
322:         if (!$form || !$form->isAnchored() || !$form->isSubmitted()) {
323:             $this->setValue($value);
324:         }
325:         return $this;
326:     }
327: 
328: 
329: 
330:     /**
331:      * Loads HTTP data.
332:      * @return void
333:      */
334:     public function loadHttpData()
335:     {
336:         $path = explode('[', strtr(str_replace(array('[]', ']'), '', $this->getHtmlName()), '.', '_'));
337:         $this->setValue(Arrays::get((array) $this->getForm()->getHttpData(), $path, NULL));
338:     }
339: 
340: 
341: 
342:     /**
343:      * Disables or enables control.
344:      * @param  bool
345:      * @return FormControl  provides a fluent interface
346:      */
347:     public function setDisabled($value = TRUE)
348:     {
349:         $this->disabled = (bool) $value;
350:         return $this;
351:     }
352: 
353: 
354: 
355:     /**
356:      * Is control disabled?
357:      * @return bool
358:      */
359:     public function isDisabled()
360:     {
361:         return $this->disabled;
362:     }
363: 
364: 
365: 
366:     /********************* rendering ****************d*g**/
367: 
368: 
369: 
370:     /**
371:      * Generates control's HTML element.
372:      * @return Html
373:      */
374:     public function getControl()
375:     {
376:         $this->setOption('rendered', TRUE);
377: 
378:         $control = clone $this->control;
379:         $control->name = $this->getHtmlName();
380:         $control->disabled = $this->disabled;
381:         $control->id = $this->getHtmlId();
382:         $control->required = $this->isRequired();
383: 
384:         $rules = self::exportRules($this->rules);
385:         $rules = substr(PHP_VERSION_ID >= 50400 ? json_encode($rules, JSON_UNESCAPED_UNICODE) : json_encode($rules), 1, -1);
386:         $rules = preg_replace('#"([a-z0-9_]+)":#i', '$1:', $rules);
387:         $rules = preg_replace('#(?<!\\\\)"(?!:[^a-z])([^\\\\\',]*)"#i', "'$1'", $rules);
388:         $control->data('nette-rules', $rules ? $rules : NULL);
389: 
390:         return $control;
391:     }
392: 
393: 
394: 
395:     /**
396:      * Generates label's HTML element.
397:      * @param  string
398:      * @return Html
399:      */
400:     public function getLabel($caption = NULL)
401:     {
402:         $label = clone $this->label;
403:         $label->for = $this->getHtmlId();
404:         if ($caption !== NULL) {
405:             $label->setText($this->translate($caption));
406: 
407:         } elseif ($this->caption instanceof Html) {
408:             $label->add($this->caption);
409: 
410:         } else {
411:             $label->setText($this->translate($this->caption));
412:         }
413:         return $label;
414:     }
415: 
416: 
417: 
418:     /**
419:      * Returns control's HTML element template.
420:      * @return Html
421:      */
422:     final public function getControlPrototype()
423:     {
424:         return $this->control;
425:     }
426: 
427: 
428: 
429:     /**
430:      * Returns label's HTML element template.
431:      * @return Html
432:      */
433:     final public function getLabelPrototype()
434:     {
435:         return $this->label;
436:     }
437: 
438: 
439: 
440:     /********************* rules ****************d*g**/
441: 
442: 
443: 
444:     /**
445:      * Adds a validation rule.
446:      * @param  mixed      rule type
447:      * @param  string     message to display for invalid data
448:      * @param  mixed      optional rule arguments
449:      * @return FormControl  provides a fluent interface
450:      */
451:     public function addRule($operation, $message = NULL, $arg = NULL)
452:     {
453:         $this->rules->addRule($operation, $message, $arg);
454:         return $this;
455:     }
456: 
457: 
458: 
459:     /**
460:      * Adds a validation condition a returns new branch.
461:      * @param  mixed     condition type
462:      * @param  mixed      optional condition arguments
463:      * @return Rules      new branch
464:      */
465:     public function addCondition($operation, $value = NULL)
466:     {
467:         return $this->rules->addCondition($operation, $value);
468:     }
469: 
470: 
471: 
472:     /**
473:      * Adds a validation condition based on another control a returns new branch.
474:      * @param  IFormControl form control
475:      * @param  mixed      condition type
476:      * @param  mixed      optional condition arguments
477:      * @return Rules      new branch
478:      */
479:     public function addConditionOn(IFormControl $control, $operation, $value = NULL)
480:     {
481:         return $this->rules->addConditionOn($control, $operation, $value);
482:     }
483: 
484: 
485: 
486:     /**
487:      * @return Rules
488:      */
489:     final public function getRules()
490:     {
491:         return $this->rules;
492:     }
493: 
494: 
495: 
496:     /**
497:      * Makes control mandatory.
498:      * @param  string  error message
499:      * @return FormControl  provides a fluent interface
500:      */
501:     final public function setRequired($message = NULL)
502:     {
503:         return $this->addRule(Form::FILLED, $message);
504:     }
505: 
506: 
507: 
508:     /**
509:      * Is control mandatory?
510:      * @return bool
511:      */
512:     final public function isRequired()
513:     {
514:         foreach ($this->rules as $rule) {
515:             if ($rule->type === Rule::VALIDATOR && !$rule->isNegative && $rule->operation === Form::FILLED) {
516:                 return TRUE;
517:             }
518:         }
519:         return FALSE;
520:     }
521: 
522: 
523: 
524:     /**
525:      * @return array
526:      */
527:     protected static function exportRules($rules)
528:     {
529:         $payload = array();
530:         foreach ($rules as $rule) {
531:             if (!is_string($op = $rule->operation)) {
532:                 $op = new Callback($op);
533:                 if (!$op->isStatic()) {
534:                     continue;
535:                 }
536:             }
537:             if ($rule->type === Rule::VALIDATOR) {
538:                 $item = array('op' => ($rule->isNegative ? '~' : '') . $op, 'msg' => $rules->formatMessage($rule, FALSE));
539: 
540:             } elseif ($rule->type === Rule::CONDITION) {
541:                 $item = array(
542:                     'op' => ($rule->isNegative ? '~' : '') . $op,
543:                     'rules' => self::exportRules($rule->subRules),
544:                     'control' => $rule->control->getHtmlName()
545:                 );
546:                 if ($rule->subRules->getToggles()) {
547:                     $item['toggle'] = $rule->subRules->getToggles();
548:                 }
549:             }
550: 
551:             if (is_array($rule->arg)) {
552:                 foreach ($rule->arg as $key => $value) {
553:                     $item['arg'][$key] = $value instanceof IFormControl ? (object) array('control' => $value->getHtmlName()) : $value;
554:                 }
555:             } elseif ($rule->arg !== NULL) {
556:                 $item['arg'] = $rule->arg instanceof IFormControl ? (object) array('control' => $rule->arg->getHtmlName()) : $rule->arg;
557:             }
558: 
559:             $payload[] = $item;
560:         }
561:         return $payload;
562:     }
563: 
564: 
565: 
566:     /********************* validation ****************d*g**/
567: 
568: 
569: 
570:     /**
571:      * Equal validator: are control's value and second parameter equal?
572:      * @param  IFormControl
573:      * @param  mixed
574:      * @return bool
575:      */
576:     public static function validateEqual(IFormControl $control, $arg)
577:     {
578:         $value = $control->getValue();
579:         foreach ((is_array($value) ? $value : array($value)) as $val) {
580:             foreach ((is_array($arg) ? $arg : array($arg)) as $item) {
581:                 if ((string) $val === (string) ($item instanceof IFormControl ? $item->value : $item)) {
582:                     return TRUE;
583:                 }
584:             }
585:         }
586:         return FALSE;
587:     }
588: 
589: 
590: 
591:     /**
592:      * Filled validator: is control filled?
593:      * @param  IFormControl
594:      * @return bool
595:      */
596:     public static function validateFilled(IFormControl $control)
597:     {
598:         return $control->isFilled();
599:     }
600: 
601: 
602: 
603:     /**
604:      * Valid validator: is control valid?
605:      * @return bool
606:      */
607:     public static function validateValid(IFormControl $control)
608:     {
609:         return $control->rules->validate(TRUE);
610:     }
611: 
612: 
613: 
614:     /**
615:      * Adds error message to the list.
616:      * @param  string  error message
617:      * @return void
618:      */
619:     public function addError($message)
620:     {
621:         if (!in_array($message, $this->errors, TRUE)) {
622:             $this->errors[] = $message;
623:         }
624:         $this->getForm()->addError($message);
625:     }
626: 
627: 
628: 
629:     /**
630:      * Returns errors corresponding to control.
631:      * @return array
632:      */
633:     public function getErrors()
634:     {
635:         return $this->errors;
636:     }
637: 
638: 
639: 
640:     /**
641:      * @return bool
642:      */
643:     public function hasErrors()
644:     {
645:         return (bool) $this->errors;
646:     }
647: 
648: 
649: 
650:     /**
651:      * @return void
652:      */
653:     public function cleanErrors()
654:     {
655:         $this->errors = array();
656:     }
657: 
658: }
659: 
Nette Framework 2.0.8 (for PHP 5.2, un-prefixed) API API documentation generated by ApiGen 2.8.0