How to show a Captcha in Yii CForm?

7:30 PM Unknown 0 Comments

In this wiki I will show how could use a Captcha in yii CForm. The easy way to show captcha image is create a form using CHtml method & CActiveForm, but CForm also should be able to show a captcha.
In your components -
Create a widget MyCaptcha.php
class MyCaptcha extends CCaptcha
{
   public $model;
   public $attribute;
 
   public function run(){
 
       parent::run();
       echo CHtml::activeTextField($this->model, $this->attribute);
    }
}
Add this into your contoller, to show the captcha image.
public function actions()
 {
   return array(
      'captcha'=>array(
      'class'=>'CCaptchaAction',
      'backColor'=>0xFFFFFF,
     ),
   );
}
in view, your CForm like -
return array(
    'title'=>'Please provide your login credential',
 
    'elements'=>array(
        'username'=>array(
            'type'=>'text',
            'maxlength'=>32,
        ),
        'password'=>array(
            'type'=>'password',
            'maxlength'=>32,
        ),
        'verifyCode'=>array(
        'type'=>'MyCaptcha',   //render the captcha image & text field.
     ),
    ),
 
    'buttons'=>array(
        'login'=>array(
            'type'=>'submit',
            'label'=>'Login',
        ),
    ),
);
Try this way it's working fine :)..

0 comments :