1

Classic problem:

verify that a user accepted the contract terms but the value of the acceptance is not stored (bound) in the database...

  1. Extend CFormModel rather than CActiveForm (because CActiveForm binds values to DB)
  2. Post a CFormModel to a controller action
  3. Validate a CFormModel

I'm asking this question to answer it because the existing questions end in see the documentation...

David Urry
  • 807
  • 1
  • 8
  • 15

1 Answers1

0

extend CFormModle, define the rules and got to validate. With bound variables you validated as part of save. Now you validate() by itself but Validate requires a list of attributes which is not defined in CFormModel. So, what do you do? You do this:

$contract->validate($contract->attributeNames())

Here's the full example:

class Contract extends CFormModel
{
...
    public $agree = false;
...
    public function rules()
    {
        return array(
            array('agree', 'required', 'requiredValue' => 1, 'message' => 'You must accept term to use our service'),
        );
    }
    public function attributeLabels()
    {
        return array(
                'agree'=>' I accept the contract terms'
        );
    }
}

Then in the controller you do this:

public function actionAgree(){
    $contract = new Contract;
    if(isset($_POST['Contract'])){
        //$contract->attributes=$_POST['Contract'];  //contract attributes not defined in CFormModel
        ...
        $contract->agree = $_POST['Contract']['agree'];
        ...
    }
    if(!$contract->validate($contract->attributeNames())){
        //re-render the form here and it will show up with validation errors marked!
    }   

The results: enter image description here enter image description here

David Urry
  • 807
  • 1
  • 8
  • 15