Не сохраняет в Таблицу Users новое поле

Общие вопросы по использованию фреймворка. Если не знаете как что-то сделать и это про Yii, вам сюда.
Ответить
geniy
Сообщения: 62
Зарегистрирован: 2014.03.17, 17:02
Контактная информация:

Не сохраняет в Таблицу Users новое поле

Сообщение geniy »

Здравствуйте уважаемые!
После захода с сервиса "Вконтакте" хочу сохранить в базу данных нового пользователя, но этого не делает...

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

class LoginController extends Controller
{
if(Yii::app()->user->isGuest) // если гость
                        {
                            $prov = Service::model()->findByAttributes(array('identity'=>$eauth->id));
if($prov !== null) //проверка, есть ли такой айди контакта в Users 
                            {
                                // есть в базе - извлекаем данные(зайти)
                                Yii::app()->user->login($identity);
                                $eauth->redirect();
                                //$this->setState('user_id', $user->id);
                            }else{
                                //иначе - занести в Users - username и активировать
                                $user=new User();
                                if ($identity->screen_name == null) {
                                    $user->username = $identity->first_name . ' ' . $identity->last_name;
                                } else {
                                    $user->username = $identity->screen_name;
                                }
                                $user->status=User::STATUS_ACTIVE;
                                $user->superuser=0;
                                $a=$user->validate(); // до этого этапа дошёл!

 if($a)
                                {
                                    $this->lastViset();
                                    if (Yii::app()->getBaseUrl()."/index.php" === Yii::app()->user->returnUrl)
                                        $this->redirect(Yii::app()->controller->module->returnUrl);
                                    else
                                        $this->redirect(Yii::app()->user->returnUrl);
                                }
                                $x=$user->save();
                                if($x)
                                {
                                    $authenticatedName = Rights::module()->authenticatedName;
                                    Rights::assign($authenticatedName, $user->id);

                                    Profile::$regMode = true;
                                    $profile=new Profile();
                                    $profile->user_id=$user->id;
                                    $profile->first_name= $eauth->first_name;
                                    $profile->last_name= $eauth->last_name;
                                    $profile->save();

                                    $service = new Service();
                                    $service->user_id=$user->id;
                                    $service->identity = $eauth->id;;
                                    $service->service_name = $eauth->serviceName;
                                    $service->save();
                                } else {
                                    $user->getErrors();
                                }
                                if( $user->save()){
                                    $eauth->redirect();
                                    Yii::app()->user->login($identity);
                                }
                                // $posts=Service::model()->with('author')->findAll();
                            }
                        }
                        else
                        { //здесь нажимая на кнопку присваиваем сервис к таблице users
                            $eauth->redirectUrl = $this->createAbsoluteUrl('/user/profile');
                            $eauth->cancelUrl = $this->createAbsoluteUrl('/user/profile');

                            $service = new Service();
                            $service->identity = $eauth->id;
                            $service->service_name = $eauth->serviceName;
                            $service->user_id = Yii::app()->user->id;

                            if ($service->save()) {
                                $eauth->redirect();
                            }
                        }
                    }
                    else
                    {
                        // закрытие popup-окна
                        $eauth->cancel();
                    }
                }
                $this->redirect(array('user/login'));
            }
            catch (EAuthException $e)
            {
                Yii::app()->user->setFlash('error',
                    'EAuthException: '.$e->getMessage());
                $eauth->redirect($eauth->getCancelUrl());
            }
        }
        elseif (Yii::app()->user->isGuest)
        {
            $model=new UserLogin;
            // collect user input data
            if(isset($_POST['UserLogin']))
            {
                $model->attributes=$_POST['UserLogin'];
                // validate user input and redirect to previous page if valid
                if($model->validate())
                {
                    $this->lastViset();
                    if (Yii::app()->getBaseUrl()."/index.php" === Yii::app()->user->returnUrl)
                        $this->redirect(Yii::app()->controller->module->returnUrl);
                    else
                        $this->redirect(Yii::app()->user->returnUrl);
                }
            }
            // display the login form
            $this->render('/user/login',array('model'=>$model));
        } else
            $this->redirect(Yii::app()->controller->module->returnUrl);
    }
    
    private function lastViset() {
        $lastVisit = User::model()->notsafe()->findByPk(Yii::app()->user->id);
        $lastVisit->lastvisit_at = date('Y-m-d H:i:s');
        $lastVisit->save();
    }

}
Незнаю как посмотреть переменную $x, так как пользуюсь xDebug в phpstorm.

Не делает сохранение нового пользователя... в модели User:

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

<?php

class User extends CActiveRecord
{
    const STATUS_NOACTIVE=0;
    const STATUS_ACTIVE=1;
    const STATUS_BANNED=-1;
    
    //TODO: Delete for next version (backward compatibility)
    const STATUS_BANED=-1;
    
    /**
     * The followings are the available columns in table 'users':
     * @var integer $id
     * @var string $username
     * @var string $password
     * @var string $email
     * @var string $activkey
     * @var integer $createtime
     * @var integer $lastvisit
     * @var integer $superuser
     * @var integer $status
     * @var timestamp $create_at
     * @var timestamp $lastvisit_at
     */

    /**
     * Returns the static model of the specified AR class.
     * @return CActiveRecord 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 Yii::app()->getModule('user')->tableUsers;
}

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.CConsoleApplication
        return ((get_class(Yii::app())=='CConsoleApplication' || (get_class(Yii::app())!='CConsoleApplication' && Yii::app()->getModule('user')->isAdmin()))?array(
            array('username', 'length', 'max'=>120, 'min' => 2,'message' => UserModule::t("Incorrect username (length between 3 and 20 characters).")),
            array('password', 'length', 'max'=>128, 'min' => 4,'message' => UserModule::t("Incorrect password (minimal length 4 symbols).")),
            array('email', 'email'),
            array('username', 'unique', 'message' => UserModule::t("This user's name already exists.")),
            array('email', 'unique', 'message' => UserModule::t("This user's email address already exists.")),
            array('username', 'match', 'pattern' => '/^[A-Za-z0-9_]+$/u','message' => UserModule::t("Incorrect symbols (A-z0-9).")),
            array('status', 'in', 'range'=>array(self::STATUS_NOACTIVE,self::STATUS_ACTIVE,self::STATUS_BANNED)),
            array('superuser', 'in', 'range'=>array(0,1)),
            array('create_at', 'default', 'value' => date('Y-m-d H:i:s'), 'setOnEmpty' => true, 'on' => 'insert'),
            array('lastvisit_at', 'default', 'value' => '0000-00-00 00:00:00', 'setOnEmpty' => true, 'on' => 'insert'),
            array('username, superuser, status', 'required'),
            array('superuser, status', 'numerical', 'integerOnly'=>true),
            array('id, username, password, email, activkey, create_at, lastvisit_at, superuser, status', 'safe', 'on'=>'search'),
        ):((Yii::app()->user->id==$this->id)?array(
            array('username', 'required'),
            array('username', 'length', 'max'=>120, 'min' => 2,'message' => UserModule::t("Incorrect username (length between 3 and 20 characters).")),
            array('email', 'email'),
            array('username', 'unique', 'message' => UserModule::t("This user's name already exists.")),
            array('username', 'match', 'pattern' => '/^[A-Za-z0-9_]+$/u','message' => UserModule::t("Incorrect symbols (A-z0-9).")),
            array('email', 'unique', 'message' => UserModule::t("This user's email address already exists.")),
        ):array()));
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        $relations = Yii::app()->getModule('user')->relations;
        if (!isset($relations['profile']))
            $relations['profile'] = array(self::HAS_ONE, 'Profile', 'user_id');
        return $relations;
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => UserModule::t("Id"),
            'username'=>UserModule::t("username"),
            'password'=>UserModule::t("password"),
            'verifyPassword'=>UserModule::t("Retype Password"),
            'email'=>UserModule::t("E-mail"),
            'verifyCode'=>UserModule::t("Verification Code"),
            'activkey' => UserModule::t("activation key"),
            'createtime' => UserModule::t("Registration date"),
            'create_at' => UserModule::t("Registration date"),
            
            'lastvisit_at' => UserModule::t("Last visit"),
            'superuser' => UserModule::t("Superuser"),
            'status' => UserModule::t("Status"),
        );
    }
    
    public function scopes()
    {
        return array(
            'active'=>array(
                'condition'=>'status='.self::STATUS_ACTIVE,
            ),
            'notactive'=>array(
                'condition'=>'status='.self::STATUS_NOACTIVE,
            ),
            'banned'=>array(
                'condition'=>'status='.self::STATUS_BANNED,
            ),
            'superuser'=>array(
                'condition'=>'superuser=1',
            ),
            'notsafe'=>array(
                'select' => 'id, username, password, email, activkey, create_at, lastvisit_at, superuser, status',
            ),
        );
    }
    
    public function defaultScope()
    {
        return CMap::mergeArray(Yii::app()->getModule('user')->defaultScope,array(
            'alias'=>'user',
            'select' => 'user.id, user.username, user.email, user.create_at, user.lastvisit_at, user.superuser, user.status',
        ));
    }
    
    public static function itemAlias($type,$code=NULL) {
        $_items = array(
            'UserStatus' => array(
                self::STATUS_NOACTIVE => UserModule::t('Not active'),
                self::STATUS_ACTIVE => UserModule::t('Active'),
                self::STATUS_BANNED => UserModule::t('Banned'),
            ),
            'AdminStatus' => array(
                '0' => UserModule::t('No'),
                '1' => UserModule::t('Yes'),
            ),
        );
        if (isset($code))
            return isset($_items[$type][$code]) ? $_items[$type][$code] : false;
        else
            return isset($_items[$type]) ? $_items[$type] : false;
    }
    
/**
     * 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('id',$this->id);
        $criteria->compare('username',$this->username,true);
        $criteria->compare('password',$this->password);
        $criteria->compare('email',$this->email,true);
        $criteria->compare('activkey',$this->activkey);
        $criteria->compare('create_at',$this->create_at);
        $criteria->compare('lastvisit_at',$this->lastvisit_at);
        $criteria->compare('superuser',$this->superuser);
        $criteria->compare('status',$this->status);

        return new CActiveDataProvider(get_class($this), array(
            'criteria'=>$criteria,
            'pagination'=>array(
                'pageSize'=>Yii::app()->getModule('user')->user_page_size,
            ),
        ));
    }

    public function getCreatetime() {
        return strtotime($this->create_at);
    }

    public function setCreatetime($value) {
        $this->create_at=date('Y-m-d H:i:s',$value);
    }

    public function getLastvisit() {
        return strtotime($this->lastvisit_at);
    }

    public function setLastvisit($value) {
        $this->lastvisit_at=date('Y-m-d H:i:s',$value);
    }

    public function afterSave() {
        if (get_class(Yii::app())=='CWebApplication'&&Profile::$regMode==false) {
            Yii::app()->user->updateSession();
        }
        return parent::afterSave();
    }
}
прошу, помогите пожалуйста. Использую связку yii-user+rights. готов заплатить 100 рублей :D
Аватара пользователя
sluchainiyznak
Сообщения: 617
Зарегистрирован: 2013.05.19, 17:51
Откуда: ХМАО-Югра, г. Сургут
Контактная информация:

Re: Не сохраняет в Таблицу Users новое поле

Сообщение sluchainiyznak »

Незнаю как посмотреть переменную $x,
CVarDumper::dump($x);
Аватара пользователя
Neuromance
Сообщения: 716
Зарегистрирован: 2011.09.06, 13:04

Re: Не сохраняет в Таблицу Users новое поле

Сообщение Neuromance »

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

if($user->save()){

}
else
  CVarDumper::dump($user->getErrors());
И да, второй раз сохранять не нужно) А то у вас 2 раза подряд встречается $user->save()
geniy
Сообщения: 62
Зарегистрирован: 2014.03.17, 17:02
Контактная информация:

Re: Не сохраняет в Таблицу Users новое поле

Сообщение geniy »

Ребята! Ура! Спасибо вам) запись сделана в таблице!
Изображение

правда похоже недоконца..
Только теперь выходит ошибка В строке $x=$user->save(); причём, валидация прошла.
Изображение

подробнее:
Изображение

Собственно,
1) почему в $this->insert($attributes) ,$attributes = нулю? ведь я сделал с записью username=progeniy

2) расскажите, что делает Profile::$regMode ?
Ответить