I have a custom form type for a "Rating" entity in my Symfony2 project. It has a value field, that is integer. Then, I created the form for this entity. Here follows the code:
class RatingType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options){
$builder->add('value', 'hidden', array('data' => 113));
}
public function getDefaultOptions(array $options){
return array(
'data_class' => 'Acme\ArticleBundle\Entity\Rating',
);
}
public function getName() {
return 'spesax_productbundle_pratingtype';
}
}
When I press the submit button in my html page, the form is not validated and a "not an integer" error message is displayed on the screen!
Why Symfony2 doesn't cast the value 113 to integer?
What can I do to solve this problem?
When using the type hidden
instead of integer
in your FormType, symfony does not know what to expect from the field, so it assumes a string. When binding the form to the entity, the hidden field gets stored into the entity field as a string.
Validating the entity fails if you validate with type="integer"
, as the value is not an integer but a string which could be casted to an integer (Saving it will work because doctrine looks if it can convert to the given type).
The trick is to use type="numeric
" in your entity validation annotation. This will check if the field can be transformed into an integer, not if the value is a real integer right now.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With