Why My Rules Doesn't Work?

I have this function in my controller :


public function actionRequestTV() {

        $this->layout = '//layouts/column1';

        $this->bodyclass = 'bodygrey_without_leftbg';


        $model = new Reqtv();


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

            if ($model->validate()) {

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

                $model->STATUS = 1;

                if ($model->save())

                    $this->redirect(array('step2', 'id' => $model->REQTVID));

            }

        }elseif (isset($_POST['BP'])) {

            if ($model->validate()) {

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

                $model->STATUS = 1;

                if (!$model->save()) {

                    print_r($model->getErrors());

                }else

                    $this->redirect(array('step2B', 'id' => $model->REQTVID));

            }

        }else

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

                'model' => $model,

            ));

    }

that function will be rendered into 2 forms, reqtvform_step1 and reqtvform_step2:

step1 :


<?php

CMBreadcrumbs::b(array(

    'Request TeamViewer',

));

?>


<div class="left">


    <h1 class="pageTitle">Request TeamViewer</h1>





        <div class="notification msgalert">

            <a class="close"></a>

            Apakah Anda Telah Berlangganan Premium Support?

        </div>


        <?php

        $form = $this->beginWidget('CActiveForm', array(

            'id' => 'contact-form',

            'enableClientValidation' => true,

            'clientOptions' => array(

                'validateOnSubmit' => true,

            ),

                ));

        ?>


        <div class="form_default">


            <fieldset>


                <legend>Fields with <span class="required">*</span> are required.</legend>


                <p>

                    <input type="radio" id="ps" name="status"> Ya, Saya telah berlangganan Premium Support<br/>

                </p>

                <p class="pss">

                    <?php echo CLabel::l($model, 'PSNO'); ?>

                    <?php echo $form->textField($model, 'PSNO', array('class' => 'pss','disabled'=>true)); ?>

                    <?php echo CLabel::e($model, 'PSNO'); ?>

                </p>


                <br/>

                <p>

                    <input type="radio" id="nops" name="status"> Tidak, Saya belum berlangganan Premium Support<br/>

                </p>

                <p class="nopss">

                    <?php echo CLabel::l($model, 'BPCP'); ?>

                    <?php echo CHtml::textField('BP[BPCP]','', array('id'=>'BP_BPCP','disabled'=>true, 'class' => 'nopss')); ?>

                    <?php echo CLabel::e($model, 'BPCP'); ?>

                </p>

                <p class="nopss">

                    <?php echo CLabel::l($model, 'BPMOBILE'); ?>

                    <?php echo CHtml::textField('BP[BPMOBILE]','', array('id'=>'BP_BPMOBILE','disabled'=>true, 'class' => 'nopss')); ?>

                    <?php echo CLabel::e($model, 'BPMOBILE'); ?>

                </p>

                <p class="nopss">

                    <?php echo CLabel::l($model, 'BPEMAIL'); ?>

                    <?php echo CHtml::textField('BP[BPEMAIL]','', array('id'=>'BP_BPEMAIL','disabled'=>true, 'class' => 'nopss')); ?>

                    <?php echo CLabel::e($model, 'BPEMAIL'); ?>

                </p>


                <p>

                    <?php echo CButton::b('Submit'); ?>

                </p>


            </fieldset>


        </div><!-- form -->


        <?php $this->endWidget(); ?>





</div>


<?php

Yii::app()->clientScript->registerScript('JQuery', "

$('#ps').click(function(){

    $('#BP_BPCP').val(''),

    $('#BP_BPMOBILE').val(''),

    $('#BP_BPEMAIL').val(''),

    $('.nopss').prop('disabled',true),

    $('.pss').prop('disabled',false);

});


$('#nops').click(function(){ 

    $('#Reqtv_PSNO').val(''),

    $('.nopss').prop('disabled',false),

    $('.pss').prop('disabled',true);

});

    ");

?>

step2:


<?php

CMBreadcrumbs::b(array(

    'Request TeamViewer',

));

?>


<div class="left">


    <h1 class="pageTitle">Request TeamViewer</h1>


        <div class="notification msgalert">

            <a class="close"></a>

            Silahkan mengisi formulir berikut. Centang Syarat dan Ketentuan untuk melanjutkan

        </div>


        <?php

        $form = $this->beginWidget('CActiveForm', array(

            'id' => 'contact-form',

            'action' => $this->createUrl('reqtv/updateContent1', array('id' => $id)),

            'enableClientValidation' => true,

            'clientOptions' => array(

                'validateOnSubmit' => true,

            ),

                ));

        ?>


        <div class="form_default">


            <fieldset>

                <legend>Fields with <span class="required">*</span> are required.</legend>


                <p>

                    <?php echo CLabel::l($model, 'PROBLEM'); ?>

                    <?php echo $form->textArea($model, 'PROBLEM', array('rows' => 5, 'cols' => 35)); ?>

                    <?php echo CLabel::e($model, 'PROBLEM'); ?>

                </p>

                <p>

                    <?php echo CLabel::l($model, 'IMG'); ?>

                    <?php echo CHtml::image(Yii::app()->baseUrl.'/images/cs.jpg', 'contoh penginputan Id TV dan Password TV', array('title' => 'contoh penginputan TVID dan Password TV'));?>

                </p>

                <p>

                    <?php echo CLabel::l($model, 'TVID'); ?>

                    <?php echo $form->textField($model, 'TVID'); ?>

                    <?php echo CLabel::e($model, 'TVID'); ?>

                </p>

                <p>

                    <?php echo CLabel::l($model, 'TVPASS'); ?>

                    <?php echo $form->passwordField($model, 'TVPASS'); ?>

                    <?php echo CLabel::e($model, 'TVPASS'); ?>

                </p>

                <br/>

                <p>

                    <?php echo CHtml::textArea('Syarat Ketentuan', 'Saya setuju dengan ketentuan untuk bla bla bla', array('rows' => 10, 'cols' => 56, 'readonly' => 'readonly')); ?><br/>

                    <?php echo $form->checkBox($model, 'SK', array('value'=>1, 'uncheckValue'=>0)); ?> Saya menyetujui syarat dan ketentuan tersebut diatas

                    <?php echo CLabel::e($model, 'SK'); ?>

                </p>

                <p>

                    <?php echo CButton::b('Submit'); ?>

                </p>


            </fieldset>


        </div><!-- form -->


        <?php $this->endWidget(); ?>




</div>




my question is, why my whole rules doesn’t work? here is my model:


<?php


/**

 * This is the model class for table "reqtv".

 *

 * The followings are the available columns in table 'reqtv':

 * @property integer $REQTVID

 * @property integer $BPID

 * @property string $TVID

 * @property string $TVPASS

 * @property string $PROBLEM

 * @property integer $SK

 */

class Reqtv extends CActiveRecord {


    public $BPCP;

    public $BPEMAIL;

    public $BPMOBILE;

    public $PSNO;

    public $ps;

    public $IMG;

    public $STAFFID;


//    public $step = 1;


    /**

     * Returns the static model of the specified AR class.

     * @param string $className active record class name.

     * @return Reqtv the static model class

     */

    public static function model($className = __CLASS__) {

        return parent::model($className);

    }


    /**

     * @return string the associated database table name

     */

    public function tableName() {

        return 'reqtv';

    }


    /**

     * @return array validation rules for model attributes.

     */

    public function rules() {

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

        // will receive user inputs.

        return array(

            array('BPID, SK, STAFFID', 'numerical', 'integerOnly' => true),

            array('BPMOBILE', 'numerical'),

            array('TGLREQ', 'safe'),

            array('TVID, TVPASS', 'length', 'max' => 50),

            array('PROBLEM', 'length', 'max' => 250),

            array('BPCP, BPMOBILE, BPEMAIL', 'length', 'max' => 255),

            array('SK', 'ceksk'),

            array('BPEMAIL', 'email'),

            array('PSNO', 'cekPSNO'),

//            array('SK, PROBLEM, TVID, TVPASS', 'required', 'on' => 'step2'),

            // The following rule is used by search().

            // Please remove those attributes that should not be searched.

            array('REQTVID, BPID, TVID, TVPASS, STATUS, TGLREQ, PROBLEM, SK, BPCP, BPMOBILE, BPEMAIL, PSNO', 'safe', 'on' => 'search'),

        );

    }


    /**

     * @return array relational rules.

     */

    public function relations() {

        // NOTE: you may need to adjust the relation name and the related

        // class name for the relations automatically generated below.

        return array(

            'BP' => array(self::BELONGS_TO, 'Customer', 'BPID'),

            'PS' => array(self::BELONGS_TO, 'Ps', 'PSID'),

            'STAFF' => array(self::BELONGS_TO, 'Staff', 'STAFFID'),

        );

    }


    /**

     * @return array customized attribute labels (name=>label)

     */

    public function attributeLabels() {

        return array(

            'REQTVID' => 'Reqtvid',

            'BPID' => 'Customer',

            'TVID' => 'Id TeamViewer',

            'TVPASS' => 'Password TeamViewer',

            'PROBLEM' => 'Problem',

            'SK' => 'Syarat & Ketentuan',

            'PSNO' => 'Nomor PS',

            'BPCP' => 'Nama',

            'BPEMAIL' => 'Email',

            'BPMOBILE' => 'HP',

            'IMG' => '',

            'TGLREQ' => 'Tanggal Request',

            'STAFFID' => 'Staff',

            'STATUS' => 'Status',

        );

    }


    /**

     * Retrieves a list of models based on the current search/filter conditions.

     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.

     */

    public function search() {

        // Warning: Please modify the following code to remove attributes that

        // should not be searched.


        $criteria = new CDbCriteria;


        $criteria->compare('REQTVID', $this->REQTVID);

        $criteria->compare('BPID', $this->BPID);

        $criteria->compare('PSNO', $this->PSNO);

        $criteria->compare('TVID', $this->TVID, true);

        $criteria->compare('TVPASS', $this->TVPASS, true);

        $criteria->compare('PROBLEM', $this->PROBLEM, true);

        $criteria->compare('SK', $this->SK);

        $criteria->compare('TGLREQ', $this->TGLREQ, true);

        $criteria->compare('STATUS', $this->STATUS = 1);

        $criteria->compare('BPCP', $this->BPCP, true);

        $criteria->compare('BPMOBILE', $this->BPMOBILE, true);

        $criteria->compare('BPEMAIL', $this->BPEMAIL, true);


        return new CActiveDataProvider($this, array(

                    'criteria' => $criteria,

                    'sort' => array(

                        'defaultOrder' => 'TGLREQ asc',

                    ),

                ));

    }


    public function cekPSNO() {

        if ($this->PSNO) {

            $psno = Ps::model()->findByAttributes(array('PSNO' => $this->PSNO));


            //check cdsn ada atau tidak

            if ($psno === null) {

                $this->addError('PSNO', 'Nomor PS tidak ditemukan, silahkan periksa Nomor PS anda !');


                return false;

            } else {

                if (date('Y-m-d') > $psno->TGLBERAKHIR) {

                    $this->addError('PSNO', 'Premium Support sudah expired !');

                    return false;

                }

            }

        }

    }


    public function ceksk() {


        if ($this->SK) {

            if ($this->SK != 0)

                return true;

            else

                $this->addError('', 'Maaf, anda harus mencentang persetujuan syarat & ketentuan sebelum melanjutkan');

                return false;

            

        }

    }


}

note: my cekPSNO rule is working. but when it get the error, it won’t give the error, but give me a blank white page instead. but when I try to getError, it give me a correct error result, so why it give me a blank white page when it can give a correct error result?. and my ceksk rule won’t work at all. it supposed to give error when my SK checkbox isn’t checked. anybody can help? thanks in advance :)

I noticed 2 mistakes in the controller.

  1. You have to do the massive assignment before the validation.



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

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

            if ($model->validate()) {



  1. Your controller does nothing at all when $model->validate() has failed. You have to render the view even when the validation has failed.



        } /* else */

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

             'model' => $model,

        ));



I didn’t read the rest of the code, so I’m not sure about the view script and the model. But the problem seems to be explained by those errors in the controller.

hi softark, thank you for replying. I’ve followed your advice, so I changed my controller into this one:




    public function actionRequestTV() {

        $this->layout = '//layouts/column1';

        $this->bodyclass = 'bodygrey_without_leftbg';


        $model = new Reqtv();


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

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

            $model->STATUS = 1;

            if ($model->validate()) {

                if ($model->save())

                    $this->redirect(array('step2', 'id' => $model->REQTVID));

            }else {

                $this->redirect(array('step2', 'id' => $model->REQTVID));

            }

        } elseif (isset($_POST['BP'])) {

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

            $model->STATUS = 1;

            if ($model->validate()) {

                if (!$model->save()) {

                    print_r($model->getErrors());

                }else

                    $this->redirect(array('step2B', 'id' => $model->REQTVID));

            }else {

                $this->redirect(array('step2B', 'id' => $model->REQTVID));

            }

        }else

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

                'model' => $model,

            ));

    }


//

    public function actionStep2($id) {

        $this->layout = '//layouts/column1';

        $this->bodyclass = 'bodygrey_without_leftbg';


        $model = Reqtv::model()->findByPk($id);


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

            'model' => $model,

            'id' => $model->REQTVID,

        ));

    }


    public function actionStep2B($id) {

        $this->layout = '//layouts/column1';

        $this->bodyclass = 'bodygrey_without_leftbg';


        $model = Reqtv::model()->findByPk($id);


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

            'model' => $model,

            'id' => $model->REQTVID,

        ));

    }


    public function actionUpdateContent1($id) {


        $model = Reqtv::model()->findByPk($id);

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

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

            $ps = Ps::model()->findByAttributes(array('PSNO' => $model->PSNO));

            $bp = Customer::model()->findByPk($ps->BPID);

            $model->BPID = $bp->BPID;

            $model->BPCP = $bp->BPCP;

            $model->BPEMAIL = $bp->BPEMAIL;

            $model->BPMOBILE = $bp->BPMOBILE;

            $model->TGLREQ = date('Y-m-d H:i:s');

            if ($model->validate()) {

                if ($model->save())

                    Yii::app()->user->setFlash('success', 'Terimakasih, Request TeamViewer anda akan segera kami proses.');

                $this->redirect(array('view', 'id' => $id));

            }else {

                Yii::app()->user->setFlash('success', 'Maaf, Request TeamViewer anda tidak bisa kami proses karena kesalahan dalam validasi');

                $this->redirect(array('view', 'id' => $id));

            }

        }

    }


    public function actionUpdateContent2($id) {


        $model = Reqtv::model()->findByPk($id);

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

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

            $model->TGLREQ = date('Y-m-d H:i:s');

            if ($model->validate()) {

                if ($model->save())

                    Yii::app()->user->setFlash('success', 'Terimakasih, Request TeamViewer anda akan segera kami proses.');

                $this->redirect(array('view', 'id' => $id));

            }else{

                Yii::app()->user->setFlash('success', 'Maaf, Request TeamViewer anda tidak bisa kami proses karena kesalahan dalam validasi');

                $this->redirect(array('view', 'id' => $id));

            }

        }

    }

but the rules still won’t work. any other ideas? sorry for the very very long post anyway :rolleyes:

note: my ceksk rule is already working. but I decided to use JQuery instead of a custom rule.

Don’t redirect when validation has failed.

By redirecting, you will lose all the error information stored in the model.