Skip to content

Commit

Permalink
Added DecimalInput
Browse files Browse the repository at this point in the history
  • Loading branch information
janpecha committed Oct 8, 2021
1 parent c38c297 commit f460f03
Show file tree
Hide file tree
Showing 2 changed files with 127 additions and 1 deletion.
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
"nette/utils": "^2.4"
},
"require-dev": {
"inteve/types": "^0.4",
"inteve/types": "^1.0",
"nette/application": "^2.4",
"nette/tester": "^2.0"
},
Expand Down
126 changes: 126 additions & 0 deletions src/DecimalInput.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
<?php

namespace Inteve\Forms;

use Inteve\Types\Decimal;
use Nette;
use Nette\Forms\Form;


class DecimalInput extends Nette\Forms\Controls\BaseControl
{
/** @var Decimal|NULL */
private $decimal;

/** @var int|NULL */
private $places;

/** @var string */
private $rawValue = '';

/** @var bool */
private $isValid = TRUE;


/**
* @param string|NULL $caption
* @param int|NULL $places
* @param string $errorMessage
*/
public function __construct($caption = NULL, $places = NULL, $errorMessage = 'Invalid value.2')
{
parent::__construct($caption);
$this->setRequired(FALSE);
$this->addRule([__CLASS__, 'validateValue'], $errorMessage);

$this->places = $places;
}


/**
* @param Decimal|NULL $value
* @return static
*/
public function setValue($value)
{
if ($value === NULL) {
$this->decimal = NULL;
$this->rawValue = '';
$this->isValid = TRUE;

} elseif ($value instanceof Decimal) {
$this->decimal = $value;
$this->rawValue = str_replace('.', ',', $value->toString());
$this->isValid = TRUE;

} else {
throw new InvalidArgumentException('Value of type ' . gettype($value) . ' is not supported.');
}

return $this;
}


/**
* @return Decimal|NULL
*/
public function getValue()
{
return $this->decimal;
}


/**
* @return bool
*/
public function isFilled()
{
return $this->rawValue !== '';
}


/**
* @return void
*/
public function loadHttpData()
{
$value = $this->getHttpData(Form::DATA_LINE);
$this->rawValue = $value;
$this->decimal = NULL;
$this->isValid = FALSE;

$value = str_replace([' ', ','], ['', '.'], $value);

if ($value === '') {
$this->decimal = NULL;
$this->isValid = TRUE;

} elseif (\Nette\Utils\Validators::isNumeric($value)) {
$this->decimal = Decimal::from((float) $value, $this->places);
$this->isValid = TRUE;
}
}


/**
* @return Nette\Utils\Html
*/
public function getControl()
{
$control = parent::getControl();
assert($control instanceof Nette\Utils\Html);
$control->value = $this->rawValue;
$control->type = 'text';
$control->style('width', 'auto'); // TODO
return $control;
}


/**
* @return bool
*/
public static function validateValue(self $control)
{
return $control->isValid;
}
}

0 comments on commit f460f03

Please sign in to comment.