Answer the question
In order to leave comments, you need to log in
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;
}
<?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);
//.....
}
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question