I’m pretty new to using Yii and I have been building a form to submit and I understand you setup your validation rules such as:
My Model:
namespace app\models;
use yii\base\model;
class CompanySignupForm extends Model {
public $company_name;
public $first_name;
public $last_name;
public $email;
public $username;
public $password;
public $password2;
public function rules() {
return [
[['company_name', 'first_name'], 'required'],
[
'company_name', 'match', 'not' => true, 'pattern' => '/[^a-zA-Z0-9 ]/',
'message' => 'Company name must consist of letters, numbers and spaces only', 'on' => 'company'
],
];
}
}
But how do you pass the scenario?
This is the method it submits to in my controller:
public function actionCompanySignup() {
$signup = new CompanySignupForm();
if ($signup->load(Yii::$app->request->post()) and $signup->validate()) {
if (Yii::$app->request->isAjax) {
}
} else {
}
}
As I understand it you should pass the scenario such as:
$signup = new CompanySignupForm('company');
But how does that work? Will I need to add a constructor to my model to handle that or how is this done?
Unless you’re configuring your model so that it can handle multiple different scenarios, you don’t need to worry about the scenario at all. Specifically, your rules will be configured to apply to all scenarios, and the default implementation of scenarios() will make those attributes with rules active automatically.
Assuming that you don’t want to manage different scenarios, there’s no reason to specify scenario information anywhere in your model or action.