Генерация форм регистрации

Общие вопросы по использованию фреймворка. Если не знаете как что-то сделать и это про Yii, вам сюда.
Закрыто
Аватара пользователя
Dzhemal
Сообщения: 20
Зарегистрирован: 2014.11.18, 12:00

Генерация форм регистрации

Сообщение Dzhemal »

Доброго времени суток.
Возможно этот вопрос уже встречался, но к сожалению не смог найти для себя ответ. Только начал разбираться с YII, но уже 2й день не могу решить проблему. Хотел сделать простую форму регистрации, состоящую из трех форм. Но не справился пока даже с этой задачей. Постоянно выдает ошибку - Fatal error: Call to a member function getErrors() on a non-object in C:\OpenServer\domains\localhost\framework\web\helpers\CHtml.php on line 2002. Код приведен ниже:

Код: Выделить всё

class UserController extends Controller
{
    public function actionIndex()
    {
        $this->render('RegisterForm');
    }

    // Uncomment the following methods and override them if needed
    /*
    public function filters()
    {
        // return the filter configuration for this controller, e.g.:
        return array(
            'inlineFilterName',
            array(
                'class'=>'path.to.FilterClass',
                'propertyName'=>'propertyValue',
            ),
        );
    }
    */

    public function actions()
    {
        // return external action classes, e.g.:
        return array(
            'Register'=>'application.models.Users',
        );
    }
    
}
model

Код: Выделить всё

<?php

/**
 * This is the model class for table "Users".
 *
 * The followings are the available columns in table 'Users':
 * @property integer $id
 * @property string $login
 * @property string $password
 * @property string $email
 */
class Users extends CActiveRecord
{
    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'Users';
    }

    /**
     * @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('login, password, email', 'required'),
            array('login, password, email', 'length', 'max'=>32),
            // The following rule is used by search().
            // @todo Please remove those attributes that should not be searched.
            array('id, login, password, email', '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(
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => 'ID',
            'login' => 'Login',
            'password' => 'Password',
            'email' => 'Email',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     *
     * Typical usecase:
     * - Initialize the model fields with values from filter form.
     * - Execute this method to get CActiveDataProvider instance which will filter
     * models according to data in model fields.
     * - Pass data provider to CGridView, CListView or any similar widget.
     *
     * @return CActiveDataProvider the data provider that can return the models
     * based on the search/filter conditions.
     */
    public function search()
    {
        // @todo Please modify the following code to remove attributes that should not be searched.

        $criteria=new CDbCriteria;

        $criteria->compare('id',$this->id);
        $criteria->compare('login',$this->login,true);
        $criteria->compare('password',$this->password,true);
        $criteria->compare('email',$this->email,true);

        return new CActiveDataProvider($this, array(
            'criteria'=>$criteria,
        ));
    }

    /**
     * Returns the static model of the specified AR class.
     * Please note that you should have this exact method in all your CActiveRecord descendants!
     * @param string $className active record class name.
     * @return Users the static model class
     */
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }
    
    public function actionRegister()
{
    $form = new CForm('application.views.user.RegisterForm');
    $form['user']->model = new User;
    $form['password']->model = new Password;
    $form['email']->model = new Email;
    if($form->submitted('register') && $form->validate())
    {
        $user = $form['user']->model;
        $profile = $form['password']->model;
        $email = $form['email']->model;
        if($user->save(false))
        {
            $profile->userID = $user->id;
            $profile->save(false);
            $this->redirect(array('site/index'));
        }
    }
 
    $this->render('register', array('form'=>$form));
}
}
view

Код: Выделить всё

<?php
/* @var $this UsersController */
/* @var $model Users */
/* @var $form CActiveForm */
?>

<div class="form">

<?php $myWidget=$this->beginWidget('CActiveForm', array(
    'id'=>'users-RegisterForm-form',
    // Please note: When you enable ajax validation, make sure the corresponding
    // controller action is handling ajax validation correctly.
    // See class documentation of CActiveForm for details on this,
    // you need to use the performAjaxValidation()-method described there.
    'enableAjaxValidation'=>false,
)); ?>

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

    <?php echo $myWidget->errorSummary($model); ?>

    <div class="row">
        <?php echo $myWidget->labelEx($model,'login'); ?>
        <?php echo $myWidget->textField($model,'login'); ?>
        <?php echo $myWidget->error($model,'login'); ?>
    </div>

    <div class="row">
        <?php echo $myWidget->labelEx($model,'password'); ?>
        <?php echo $myWidget->textField($model,'password'); ?>
        <?php echo $myWidget->error($model,'password'); ?>
    </div>

    <div class="row">
        <?php echo $myWidget->labelEx($model,'email'); ?>
        <?php echo $myWidget->textField($model,'email'); ?>
        <?php echo $myWidget->error($model,'email'); ?>
    </div>


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

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

</div><!-- form -->
Помогите пожалуйста ;) Для Вас это 2х минутное дело, для меня уже 2х дневное пыхтение.
badjo
Сообщения: 188
Зарегистрирован: 2013.10.10, 12:39

Re: Генерация форм регистрации

Сообщение badjo »

Код: Выделить всё

class UserController extends Controller
{
    public function actionIndex()
    {
        $model = new Users;
        $this->render('RegisterForm',array('model'=>$model));
    }
    
} 
Аватара пользователя
Dzhemal
Сообщения: 20
Зарегистрирован: 2014.11.18, 12:00

Re: Генерация форм регистрации

Сообщение Dzhemal »

badjo писал(а):

Код: Выделить всё

class UserController extends Controller
{
    public function actionIndex()
    {
        $model = new Users;
        $this->render('RegisterForm',array('model'=>$model));
    }
    
}
Большое Вам спасибо. Помогло.
Закрыто