Tell me more ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I'm developing a web application using php and yii framework. Yii generates validation rules based on your tables and checks user input before the data is entered. I would like to validate the data against yii's rules but not enter the data into the database yet, but rather store it in a session? Is that possible and how can i accomplish that?

share|improve this question
I've found a very simple answer to my question!!!! Instead of calling Model::save() which validates and then saves into the database if valid, you call Model::validate() which validates against the same validation rules but doesn't save. I hope this helps anyone. – Diane Sep 4 '12 at 17:00
1  
maybe you could submit your comment as an answer and mark it as an answer? – Marco Sep 25 '12 at 8:15

1 Answer

to receive a proper validation first all the rules have to be set in the model. like this

public function rules()
{
    return array(
        array('username, password', 'required'),
        array('password_repeat', 'required', 'on'=>'register'),
        array('password', 'compare', 'compareAttribute'=>'password_repeat', 'on'=>'register'),
    );
}

f.e. if you want to validate user input from a CHtml::form you do domething like this

if(!empty($_GET['User'])){
    $model->attributes = $_GET['User'];
    if(!$model->validate()){
        // do something with $model->getErrors();
    } else {
        $model->save();
    }
}

its also possible to validate a CHtml::form with ajax.... just add this to the controller

protected function performAjaxValidation($model)
{
    if(isset($_POST['ajax']) && $_POST['ajax']==='user-form')
    {
        echo CActiveForm::validate($model);
        Yii::app()->end();
    }
}

the form wold look like this then with enableAjaxValidation = true,

$form=$this->beginWidget('CActiveForm', array(
    'id' => 'node-form',
    'enableClientValidation'=>true,
    'clientOptions'=>array( 
        'validateOnSubmit'=>true)
    )); 
?>

there are also the methods beforeValidate and afterValidate... validate() in general is always called before save ... but if you really want to access the errors before wanting to save them ... validate() and getErrors() could help you

share|improve this answer
1  
haha.. sorry you already answered your question on our own – Mik Nov 30 '12 at 23:54
1  
Please consider expanding upon your answer as it answers the question in a more clear manner than what the OP did with a comment to the question. – GlenH7 Dec 1 '12 at 3:31

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.