D
D
Denis2018-03-16 23:20:20
Yii
Denis, 2018-03-16 23:20:20

Using scripts in Yii2?

I read the documentation several times, looked through dozens of articles, but did not fully understand the indication of the rules for scripts.
There is an AR User, we define the script there

<?php
namespace common\models;

use yii\db\ActiveRecord;
use yii\web\IdentityInterface;

class User extends ActiveRecord implements IdentityInterface
{
    const SCENARIO_REGISTRATION = 'registration';

    public function scenarios()
    {
        $scenarios = parent::scenarios();
        $scenarios[self::SCENARIO_REGISTRATION] = ['nickname', 'email', 'password'];
        return $scenarios;
    }

There is a Model layer RegistrationForm
<?php

namespace frontend\modules\account\models\forms;

use Yii;
use yii\base\Model;
use common\models\User;
use frontend\modules\account\models\Token;

class RegistrationForm extends Model
{
    public $nickname; // nickname user

    public $email; // email user

    public $password; //password user

     //....

    /**
     * Registration function
     * @return bool
     * @throws \Exception
     * @throws \yii\db\Exception
     */
    public function registration()
    {
        if (!$this->validate()) {
            return false;
        }

        $transaction = Yii::$app->db->beginTransaction();

        try {
            $user = new User();
            $user->scenario = User::SCENARIO_REGISTRATION;
            $user->attributes = $this->attributes;
            $user->email_confirm = User::EMAIL_NO_CONFIRM;
            $user->generatePassword($this->password);

           //.....
    }
}

In it, we install the script and assign attributes in bulk.
Where should we write rules in this case , in AR or Model (RegistrationForm). In the documentation, as I understand it, this is done in AR, however, in some extensions, rules are present both there and there, while being identical, which accordingly led to a dead end. What for? Why? How and where to prescribe validation rules?
Help me get to the point.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Lumore, 2018-03-16
@valetu

The form is inherited from RegistrationForm, therefore the rules will be inherited from this model and validated in the view based on these rules. When you call the save() method in the controller, the User model is saved, and validation occurs through the rules of this model.
You can only write rules in the RegistrationForm, but then you won't be able to use the User model directly elsewhere, because validation inside is not registered.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question