| 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 |
declare (strict_types=1); |
| 8 |
namespace Packetery\Nette\Forms\Controls; |
| 9 |
|
| 10 |
use Packetery\Nette; |
| 11 |
/** |
| 12 |
* Hidden form control used to store a non-displayed value. |
| 13 |
*/ |
| 14 |
class HiddenField extends BaseControl |
| 15 |
{ |
| 16 |
/** @var bool */ |
| 17 |
private $persistValue; |
| 18 |
/** @var bool */ |
| 19 |
private $nullable = \false; |
| 20 |
public function __construct($persistentValue = null) |
| 21 |
{ |
| 22 |
parent::__construct(); |
| 23 |
$this->control->type = 'hidden'; |
| 24 |
$this->setOption('type', 'hidden'); |
| 25 |
if ($persistentValue !== null) { |
| 26 |
$this->unmonitor(\Packetery\Nette\Forms\Form::class); |
| 27 |
$this->persistValue = \true; |
| 28 |
$this->value = (string) $persistentValue; |
| 29 |
} |
| 30 |
} |
| 31 |
/** |
| 32 |
* Sets control's value. |
| 33 |
* @return static |
| 34 |
* @internal |
| 35 |
*/ |
| 36 |
public function setValue($value) |
| 37 |
{ |
| 38 |
if ($value === null) { |
| 39 |
$value = ''; |
| 40 |
} elseif (!\is_scalar($value) && !(\is_object($value) && \method_exists($value, '__toString'))) { |
| 41 |
throw new \Packetery\Nette\InvalidArgumentException(\sprintf("Value must be scalar or null, %s given in field '%s'.", \gettype($value), $this->name)); |
| 42 |
} |
| 43 |
if (!$this->persistValue) { |
| 44 |
$this->value = $value; |
| 45 |
} |
| 46 |
return $this; |
| 47 |
} |
| 48 |
public function getValue() |
| 49 |
{ |
| 50 |
return $this->nullable && $this->value === '' ? null : $this->value; |
| 51 |
} |
| 52 |
/** |
| 53 |
* Sets whether getValue() returns null instead of empty string. |
| 54 |
* @return static |
| 55 |
*/ |
| 56 |
public function setNullable(bool $value = \true) |
| 57 |
{ |
| 58 |
$this->nullable = $value; |
| 59 |
return $this; |
| 60 |
} |
| 61 |
public function getControl() : \Packetery\Nette\Utils\Html |
| 62 |
{ |
| 63 |
$this->setOption('rendered', \true); |
| 64 |
$el = clone $this->control; |
| 65 |
return $el->addAttributes(['name' => $this->getHtmlName(), 'disabled' => $this->isDisabled(), 'value' => (string) $this->value]); |
| 66 |
} |
| 67 |
/** |
| 68 |
* Bypasses label generation. |
| 69 |
*/ |
| 70 |
public function getLabel($caption = null) |
| 71 |
{ |
| 72 |
return null; |
| 73 |
} |
| 74 |
/** |
| 75 |
* Adds error message to the list. |
| 76 |
* @param string|object $message |
| 77 |
*/ |
| 78 |
public function addError($message, bool $translate = \true) : void |
| 79 |
{ |
| 80 |
$this->getForm()->addError($message, $translate); |
| 81 |
} |
| 82 |
} |
| 83 |
|