Craig
Craig

Reputation: 8294

Symfony2 validation changes invalid integer to 0

I added validation to a form and found that in some cases it is losing the invalid data I am feeding it and saving 0s instead. The output at the bottom shows that if I post the latitude as 'zzzzzz', which is clearly not a number nor between -90 and 90, the form is declared as valid and saved with the value 0.

How can that happen given that I have declared the input must be a number?

ProxyType.php buildForm():

$builder
        ->add('siteName', null, array('label' => 'Site name'))
        ....
        ->add('latitude', 'number', array('label' => 'Latitude'))
        ->add('longitude', 'number', array('label' => 'Longitude'))
        ....
    ;

ProxyController.php createAction:

    ....
    $postData = $request->request->get('niwa_pictbundle_proxytype');
    $this->get('logger')->info('Posted latitude = '.$postData['latitude']);

    $form    = $this->createForm(new ProxyType(), $entity);
    $form->bindRequest($request);

    if ($form->isValid()) {
        $this->get('logger')->info('Form declared valid : latlong ('.$entity->getLatitude().','.$entity->getLongitude().')');
        ....

validation.yml:

Acme\PictBundle\Entity\Proxy:
properties: 
    longitude:
        - Min: { limit: -180 }
        - Max: { limit: 180 }
    latitude:
        - Max: { limit: 90 }
        - Min: { limit: -90 }

Output:

[2012-09-28 02:05:30] app.INFO: Posted latitude = zzzzzz [] []
[2012-09-28 02:05:30] app.INFO: Form declared valid : latlong (0,0) [] []

Upvotes: 2

Views: 2304

Answers (2)

fd8s0
fd8s0

Reputation: 1927

What's happening is you're not using a number validation, but rather bounding the form field to be a number, thus when you bind the request to the form it transforms the string into a number (which for any string which starts without a number will be 0). A form field being a number means it expects to come as a number, or rather, there should be some validation in the front-end of such thing or the front-end should not allow a non-number to be set.

I think what you seem to want is a form field of type text with a number validation.

For actual validation use the constraint type (additional to your min and max values).

http://symfony.com/doc/current/book/validation.html

http://symfony.com/doc/current/reference/constraints/Type.html

Upvotes: 5

Asish AP
Asish AP

Reputation: 4441

Add the following constarins in your validation.yaml. Then only it validated the fields. In your form type you mention only which type(number) of widget you need. Thats not enough. so try to add this validation in your

Validation.yml

latitude
    - Type:
        type: integer
        message: latitude should be numeric
longitude
    - Type:
        type: integer
        message: longitude should be numeric

Hope this helps.

Upvotes: -1

Related Questions