phpvalidationpropel

How to add Validation Rules to Propel Models after Model Generation?


How would I add validation rules to my columns after Models have been generated. I know you can extend propel's validation, but I didn't see an option for applying these validation rules to my model's columns after I have generated these models from the schema.

To clarify, I know you add these rules in the actual schema, but I would prefer to not do that.


Solution

  • in any propel generated main class (e.g. User) you can override doValidate($column=null) method. See the example below...the return logic part may require improvements.

    public function doValidate($columns = null){
        $parentErrors = parent::doValidate($columns);
        $validationErrors = array();
        if(mb_strlen($this->getFirstName()) == 0){
            $message = '...';
            $vf = new ValidationFailed(UserPeer::FIRST_NAME, $message);
            $validationErrors[] = $vf;
        }
    
    
    
        if(is_array($parentErrors)){
            if(!empty($validationErrors)){
                $validationErrors = array_merge($parentErrors, $validationErrors);
            }else{
                $validationErrors = $parentErrors;
            }
            return $validationErrors;
        }elseif($parentErrors === true){
            if(empty($validationErrors)){
                return true;
            }else{
                return $validationErrors;
            }
        }else{
            throw UnexpectedValueException('Unexpected validation state.');
        }
    }
    

    Afterwards you can run $validationErrors = $user->validate(); anywhere in your application and check the return value.

    I hope this answers your question.