Reputation: 113
When I try to save a Symfony 2.8 form field of type "percent" with a fractional value, the validation returns
This value should not be null.
I have set up the field in my entity as per instructions:
/**
* @var decimal
*
* @ORM\Column(
name="total_percent",
type="decimal",
precision=14,
scale=8,
nullable=false
)
* @Assert\NotNull()
*/
private $percent;
and I create my field as such:
->add('percent',
PercentType::class,
array(
'scale' => 8,
'attr' => array('class' => 'percent_field'))
)
I have double checked the database and I can create entries with fractions, so the issue seems to be with Symfony's forms. However, I cannot find the issue in my code. Has anyone successfully implemented this. In essence I want to be able to save a percent like 1.5%. Any constructive ideas (pertaining to the issue at hand) are appreciated.
Upvotes: 0
Views: 626
Reputation: 3500
As stated in the Doctrine documentation:
precision: The precision for a decimal (exact numeric) column (applies only for decimal column), which is the maximum number of digits that are stored for the values.
scale: The scale for a decimal (exact numeric) column (applies only for decimal column), which represents the number of digits to the right of the decimal point and must not be greater than precision.
to store a simple percentage value like 1.5
% and a relative (positive) range from 0.0
to 100.0
you should modify the column mapping:
/**
* @var decimal
*
* @ORM\Column(
* name="total_percent",
* type="decimal",
* precision=4, # <-- THIS IS NEEDED TO BE ALLOWED TO STORE ALSO 100.0,
* scale=1, # <-- THIS ALLOWS ONLY 1 DECIMAL
* nullable=false
* )
* @Assert\NotNull()
* @Assert\Range(
* min = 0,
* max = 100,
* minMessage = "Min % is 0",
* maxMessage = "Max % is 100"
* )
*/
private $percent;
and the form field:
->add('percent',
PercentType::class,
array(
'type' => 'integer', # <-- SET THE TYPE AS INTEGER!
'scale' => 1,
'attr' => array('class' => 'percent_field')
)
)
To avoid values upper then 100.0
use the Range
constraint like in my example.
In my tests this configuration works pretty well, allowing decimal separed by commas like "34,2
" or "1,5
" and all the values like "23,5543
" will be rounded to the closest value in defect or excess (in this case will be "23,6
").
Upvotes: 1