Model Data Is Not Available During Validation

I am trying to validate uniqueness of two columns(composite index), using below validation rule @model site

/*USING Yii 1.1.13 */

public function rules() {

    // NOTE: you should only define rules for those attributes that


    // will receive user inputs.     


    return array(


        array('name','unique','criteria'=>array(


            'condition'=>'`course_id`=:courseId',


            'params'=>array(':courseId'=>$this->course_id)


        )),


        array('name, course_id, start_date, end_date', 'required'),

But, this is not working.

below is the code from controller :

public function actionCreate() {

    $model = new Batch;


    


    // Uncomment the following line if AJAX validation is needed


    // $this->performAjaxValidation($model);





    if (isset($_POST['Batch'])) {            


        $model->attributes = $_POST['Batch'];            





        if ($model->start_date != null && $model->course_id != null) {


            $duration = Yii::app()->db->createCommand()


                    ->select('duration')


                    ->from('course')


                    ->where('id=:Id', array(':Id' => $model->course_id))


                    ->queryScalar();





            $model->end_date = $this->calculateBatchEndDate($model->start_date, $duration);


        }





        try {


            if ($model->save()) {


                Yii::app()->user->setFlash('newBatchSuccess', 'Successfully created Batch ' . CHtml::link($model->name, array('/admin/batch/view', 'id' => $model->id, 'newwindow' => 0)));


                $this->redirect(array('create'));


            }


        } catch (Exception $e) {


            Yii::app()->user->setFlash('newBatchError', 'Error occured during Batch creation. Try again later' . $e->getMessage());


        }


    }





    $this->render('create', array(


        'model' => $model,


    ));


}

Please help ;

I noticed that :

  1. If I manually set the course_id,in controller,just after model creation. Then it is working but it always checking with the one I’ve set manually.

public function actionCreate() {

    $model = new Batch;





    $model->course_id=3;// Setiing course_id manually





    // Uncomment the following line if AJAX validation is needed


    // $this->performAjaxValidation($model);





    if (isset($_POST['Batch'])) {            


        $model->attributes = $_POST['Batch'];  // COurse_id required to be set by the value from FORM..          





        if ($model->start_date != null && $model->course_id != null) {


            $duration = Yii::app()->db->createCommand()


                    ->select('duration')


                    ->from('course')


                    ->where('id=:Id', array(':Id' => $model->course_id))


                    ->queryScalar();





            $model->end_date = $this->calculateBatchEndDate($model->start_date, $duration);


        }





        try {


            if ($model->save()) {


                Yii::app()->user->setFlash('newBatchSuccess', 'Successfully created Batch ' . CHtml::link($model->name, array('/admin/batch/view', 'id' => $model->id, 'newwindow' => 0)));


                $this->redirect(array('create'));


            }


        } catch (Exception $e) {


            Yii::app()->user->setFlash('newBatchError', 'Error occured during Batch creation. Try again later' . $e->getMessage());


        }


    }





    $this->render('create', array(


        'model' => $model,


    ));


}

you cannot access data in rules() function because rules are needed BEFORE data is assigned. consider this case:




$model = new Model();

$model->attributes = $_POST['Model'];



in order to perform massive assignement in second line Yii gets rules() to check which attributes are safe and which are not. Only after that actual assignement is made. This is why you cannot depend on local data in rules().

@Chandrakanta: Just a small info. Always use code snipset (second button to the right on second toolbar – <>) to format your code and make it more readable by others. Thanks and welcome to the community.

Hi

What you can do is use a custom validator, then you can access other attributes of the model. (Maybe you’ll have to change the rules order (not sure)).

http://www.yiiframework.com/doc/guide/1.1/en/form.model#declaring-validation-rules

in fact he needs: http://www.yiiframework.com/extension/unique-multiple-columns-validate/ (unique multiple column validator)