Quantcast
Viewing latest article 2
Browse Latest Browse All 10

Access the form values in prevalidator

I’m using a preValidator to validate a price in a form. Say the user enters "22,35", I want to format this string to "22.35". And I need to do this before the actual validator (sfValidatorNumber) of the field, so that the string "22,35" will be formatted and pass the sfValidatorNumber.

How to do this? Set a preValidator:

public function configure()
{
        $this->validatorSchema->setPreValidator(
               new sfValidatorCallback(array('callback' => array($this, 'validatePrice')))
         );
}

public function validatePrice($validator, $values)
{
        ...

    	$values['price'] = str_replace(',', '.', $values['price']);
    	return $values;
}

Easy.

But this does not work ! Image may be NSFW.
Clik here to view.
:D
Contrary to postValidators, $values are not modified in preValidators.

I found a little patch to fix this (after one hour trying to fix it on my own by overriding proccessForm() method etc…), on this ticket of symfony trac.

There’s no need to complicate, our time is short (Jason Mraz – I’m Yours ♫):

//lib/vendor/symfony/lib/validator.sfValidatorSchema.class.php
-LINES-
                    // pre validator
            	    try
           	    {
                         // Replace this line
123	 	          $this->preClean($values);
                         // with this one
 		          $values = $this->preClean($values);
             	    }
        	    catch (sfValidatorErrorSchema $e)
        	    {
…	…
              	  {
        	   if (is_null($validator = $this->getPreValidator()))
	           {
                         //Replace this line
221  	                  return;
                         // with this one
 		          return $values;
	            }
	             //Replace this line
224	 	     $validator->clean($values);
                    // with this one
 		     return $validator->clean($values);
	  }

Now it works !

I think that this is an important fix to have.

I use symfony 1.2.6, i didn’t try 1.2.8 but I didn’t see the patch in the changelog.


Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.

Viewing latest article 2
Browse Latest Browse All 10

Trending Articles