Snippets

Create an account or login to be able to add, comment and rate snippets.

Navigation

YML validation in actions

Currently i had to do different validations of data depending the data entered by the user.

The solution i found, using the symfony built-in yml validation was:

action:

$validated = true;
$validationConfig = $this->getModuleName().'/'.sfConfig::get('sf_app_module_validate_dir_name').'/'.$validationFile.'.yml';
 
if (null !== $validateFile = sfConfigCache::getInstance()->checkConfig(sfConfig::get('sf_app_module_dir_name').'/'.$validationConfig, true))
{
    $context = $this->getContext();
    $validatorManager = new  sfValidatorManager();
        $validatorManager->initialize($context);
    require($validateFile);
    $validated = $validatorManager->execute();
}
 

refactoring:

public function validateParamsYml($validationFile) {
        $validated = true;
        $validationConfig = $this->getModuleName().'/'.sfConfig::get('sf_app_module_validate_dir_name').'/'.$validationFile.'.yml';
 
        if (null !== $validateFile = sfConfigCache::getInstance()->checkConfig(sfConfig::get('sf_app_module_dir_name').'/'.$validationConfig, true))
        {
            $context = $this->getContext();
            $validatorManager = new sfValidatorManager();
            $validatorManager->initialize($context);
            require($validateFile);
            $validated = $validatorManager->execute();
        }
        return $validated;
    }
 

Then you can call any validations rules at your action:

public function executeXXX() {
  [...]
  [...]
  $this->validateParamsYml('yml_1');
  $this->validateParamsYml('yml_2');
  [...]
}
 

and finally check if everything was validated then forward/save the data:

if($this->getRequest()->hasErrors()) {
            return $this->handleErrorXXXX();
        }
 

Cheers

by Lucas Peres on 2007-10-02, tagged validation 
You need to create an account or log in to post a comment or rate this snippet.