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 :
- 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,
));
}