P
P
phpForeve2017-06-25 01:11:14
Yii
phpForeve, 2017-06-25 01:11:14

Why doesn't $model->save() work?

Have Form

<?php

namespace app\models\forms;

use Yii;
use yii\base\Model;

use app\models\User;

class SignupForm extends Model
{
    public $username;
    public $email;
    public $password;
    public $password_confirm;
    public $role;
    public $status;

    public function rules()
    {
        return [
            [['username', 'email', 'password'], 'required', 'message' => 'Поля обязательны для заполнения'],
            [['password'], 'string', 'min' => 6, 'message' => 'Длина пароля не может быть меньше 6-ти символов'],
            [['password_confirm'], 'compare', 'compareAttribute' => 'password', 'message' => 'Пароли должны совпадать'],
            [['email'], 'email', 'message' => 'Недопустимый вид почты(<b>Пример: [email protected]</b>)'],
            [['role'], 'in', 'range' => [User::ROLE_ADMIN, User::ROLE_MANAGER, User::ROLE_ROOT, User::ROLE_USER]],
            [['status'], 'in', 'range' => [User::STATUS_NEW, User::STATUS_ACTIVE, User::STATUS_BANNED, User::STATUS_DETETED]],
        ];
    }
}

Yes Model
<?php
namespace app\models;

//YII components
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
use yii\db\Exception;

/**
 * This is the model class for table "users"
 *
 * @property integer $id
 * @property string $username
 * @property string $email
 * @property string $password
 * @property string $role
 * @property string $status
 * @property string $access_token
 * @property string $recovery_token
 * @property string login_at
 * @property string created_at
 * @property string updated_at
 * @property string deleted_at
 */

class User extends ActiveRecord implements IdentityInterface {

    //STATUSES
    const STATUS_ACTIVE = 'active';
    const STATUS_NEW = 'new';
    const STATUS_BANNED = 'banned';
    const STATUS_DETETED = 'deleted';

    //ROLES
    const ROLE_USER = 'user';
    const ROLE_MANAGER = 'manager';
    const ROLE_ADMIN = 'admin';
    const ROLE_ROOT = 'root';

    public static function tableName()
    {
        return 'users';
    }

    public function rules()
    {
        return [
          [['username', 'email', 'password', 'role', 'status',
              'access_token', 'recovery_token', 'login_at', 'created_at',
              'updated_at', 'deleted_at'], 'safe'],
        ];
    }

    public function behaviors() {
        return [
            'DefaultTimestampBehaviour' => [
                'class' => TimestampBehavior::className(),
                'value' => (new \DateTime())->format('Y-m-d H:i:s')
            ]
        ];
    }

    public function getTokens() {
        return floatval($this->access_token);
    }

    public function setPassword($password) {
        return password_hash($password,PASSWORD_BCRYPT);
    }

    public function validatePassword($password) {
        return password_verify($password, $this->password);
    }

    public static function findIdentity($id)
    {
        return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
    }

    public static function findIdentityByAccessToken($token, $type = null) {
        return static::findOne(['access_token' => $token, 'status' => self::STATUS_ACTIVE]);
    }

    public function getId()
    {
        return $this->getPrimaryKey();
    }

    public function validateAuthKey($access_token)
    {
        return $this->getAuthKey() === $access_token;
    }

    public function getAuthKey()
    {
        return $this->access_token;
    }

    public function signup($attributes = []) {
        $user = new User();

        $user->username = $attributes['username'];
        $user->email = $attributes['email'];
        $user->password = User::setPassword($attributes['password']);
        $user->role = self::ROLE_USER;
        $user->status = self::STATUS_NEW;

        if (!$user->save(false)) {
            throw new Exception('Ошибка при записи модели в базу ' . $user->getErrors(), 500);
        }

        return $user;
    }

}

Have Action
public function actionSignup() {
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $data = [];

            $form = new SignupForm();
            $form->attributes = Yii::$app->request->getBodyParams();
            if (!$form->validate()) {
                throw new Exception('Невалидная форма регистрации', $form->getErrors(), 500);
            } else {
               $user =  User::signup($form->attributes);
            }

        } catch (Exception $ex) {
            $transaction->rollBack();
            throw $ex;
        }

        var_dump($user);
    }

The form validates perfectly, I pass the data to the model, I try to save - it works, but nothing appears in the database, and the auto-increment of the table increases.
Here is what is in $user at the very end (i.e. we have all the data)
"data": {
        "username": "Тест",
        "email": "[email protected]",
        "password": "$2y$10$t5OZ5okdCwnInz/RWag6LOnN7ySYrUeKaKkbbgylgJcEAQlfelVE2",
        "role": "user",
        "status": "new",
        "created_at": "2017-06-25 01:00:46",
        "updated_at": "2017-06-25 01:00:46",
        "id": "20"
    }

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
B
Boris Korobkov, 2017-06-25
@phpForeve

catchmust be added before$transaction->commit();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question