表格和验证不适用于yii

时间:2015-04-09 07:11:33

标签: php yii php-5.3

这是我与YII framework有关的第二个问题 我在YII framework创建了一个表单。它没有发布任何数据。验证也无效。

以下是我的Controller类的代码:

   class RegisterController extends Controller
   {
    public function actionIndex()
    {
        $model = new C_regsiter();

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

            // do something
            $model->data = $_POST['C_register'];
            $model->username = $_POST['C_register']['username'];
            $model->Password = $_POST['C_register']['Password'];
            $model->email = $_POST['C_register']['email'];

            if ($model->validate()) {
              //do something
          }
        } else {}

        $this->render('index', array(
            'model' => $model
        ));
    }
    }

以下是我的模型类的代码:

    class C_regsiter extends CFormModel{

    public $username;
    public $Password;
    public $email;
    public $data;
    protected  $id;

    public function rules(){

    return array(
    array('username,password,email','required','on'=>'Register'),
    array('email','email'),         
    );

    }

    public function attributelabel(){

    return array(
     'username'=>'User Name',
     'password'=>'Password',
     'email'=>'Email Address '
    ); 

    }
    }

以下是我的View类的代码

   <div class="form">
   <?php echo CHtml::beginForm(); ?>
   <?php echo CHtml::errorSummary($model); ?>

   <div class="row">
   <?php  echo CHtml::activeLabel($model, 'username'); ?>
   <?php echo CHtml::activeTextField($model, 'username'); ?>
   <?php echo CHtml::error($model, 'username') ?>
   </div>

   <div class="row">
        <?php echo CHtml::activeLabel($model,'email'); ?>
        <?php echo TbHtml::activeEmailField($model , 'email') ?>
        <?php echo CHtml::error($model, 'email') ?>
   </div>

   <div class="row">
   <?php  echo CHtml::activeLabel($model, 'password'); ?>
   <?php  echo  CHtml::activePasswordField($model, 'Password');  ?>
   <?php echo CHtml::error($model, 'password') ?>
   </div>

   <div class="row">
     <?php echo CHtml::submitButton('Register') ;?>
   </div>

   <?php echo CHtml::endForm(); ?>  
   </p>

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

您必须设置模型属性在您的操作中尝试此操作

class RegisterController extends Controller
 {

    public function actionIndex()
    {
        $model = new C_regsiter();
       if (isset($_POST['C_register'])) {
            $model->attributes = $_POST['C_register'];

            if ($model->validate()) {
               //do something

        }
    }

    $this->render('index', array('model' => $model));
    }
 }

答案 1 :(得分:0)

不是这个,因为你的名字中有拼写错误吗? C_regsiter而不是C_register,您检查C_register POST数据。无论如何使用它。

public function actionIndex()
{
    $model = new C_regsiter();

    $data = Yii::app()->request->getPost('C_regsiter');
    if ($data) {
        $model->setAttributes($data);
        if ($model->validate()) {
            // ....
        }
    }

    $this->render('index', array(
        'model' => $model
    ));
}