Yii2: scenarios() model method - php

There are 2 needed functions: set password when registering and change password, if user forgot it. When user signs up, password length must be at least 4 chars; when changes pass - at least 5 chars.
View is common for registration and changing pass. Obviously, also 2 actions exist, in which either scenario 'signup', either 'change' used.
Code snippet in model:
public function rules() {
return [
['password', 'string', 'min' => 4, 'on' => 'signup'],
['password', 'string', 'min' => 5, 'on' => 'change'],
];
}
But I want to do do it via scenarios(). How to do it? I'm a beginner in Yii, so did not understand, when and how to use scenarios(). Thanks.
UPD. I need to use scenarios() for ONE field with ONE rule, but DIFFERENT arguments to this one rule. how to define a scenario in Yii2? - it is NOT my case.

As documentation about scenarios() says: The default implementation of this method will return all scenarios found in the rules() declaration. So generally you do not need to override this method, because it will look for on array keys to set active attributes for current scenario an validate them properly.
So in your case 'on' => 'some scenario' for different validations of the same attribute is exactly what you need.

Related

How can I use multiple validation rules as base for multiple validation requests in Laravel

Let's say that I have 3 Types of users and they all have common fields for example:
username, email, password .... etc
And each one of them has its own fields, now I create the Add,Update functionality and create the FormRequest for each one of these function which leads me to 6 FormRequest, and they all have common rules for the common fields !
How can I use for example StoreUserRequest and put all the common rules for storing the User and put the individual rules in the right FormRequest, I hope I could explain what I'm trying to achieve clearly.
You could use traits to accomplish this, this allows multiple classes (the form requests) to inherit the specified shared rules.
Create a CommonUserRules.php in app\Http\Requests directory:
<?php
namespace App\Http\Requests;
trait CommonUserRules
{
protected function userRules()
{
return [
'name' => 'required',
'password' => 'required',
];
}
}
This will be the rules that can be shared across multiple form requests.
Then inside the Form Request you use the trait:
use CommonUserRules;
Then you can append and define your unique rules accordingly:
public function rules()
{
return array_merge($this->userRules(), [
'individual_rule' => 'required',
'another_individual_rule' => 'required',
]);
}

Yii2 - Sluggable Behavior

I have configured Sluggable behavior on my model as follows:
public function behaviors() {
return [
[
'class' => SluggableBehavior::className(),
'attribute' => 'title',
'ensureUnique' => true,
]
];
}
I need to do:
If the user fills a form field called "URL", this should be used instead of the automatic generated slug.
If user changes the title, they will mark a checkbox if they want the slug updated.
I have found that Sluggable Behaviour has an attribute "immutable" but I do not see a method to manipulate it.
Also I do not see a way to stop automatic generation if value is given.
Any ideas?
For such unusual requirements you should probably extend SluggableBehavior and overwrite getValue() and isNewSlugNeeded() methods to feat your needs.
You may also play with $value property and/or change some behavior settings in beforeValidate() of model:
public function beforeValidate() {
$this->getBahavior('my-behavior-name')->immutable = !$this->changeSlugCheckbox;
return parent::beforeValidate();
}
But custom behavior is much more clean solution.

How Can I Add a Custom Password Validation in Laravels default Forgot Password System?

I want to change the validation for passwords when using Laravels default Forgot Password System. I need to do this so I can replace the password validation rule with this validation rule:
'password' => 'required|min:6|max:15|confirmed',
Specifically, I need to add the min/max changes.
However, I don't see anywhere in the ForgotPasswordController or ResetPasswordController where I can do this....
I'm using Laravel 5.3.
You can do this in your ResetPasswordController just override the rules method.
protected function rules()
{
return [
'token' => 'required',
'email' => 'required|email',
'password' => 'required|confirmed|min:6',
];
}
Hope this helps
Since you're dealing with password data. You don't consider length of the password but also a valid format like password must not have any strange special characters or even space/blank character.
I want to share with you our basic solution yet effective that we have and been using it for many projects we built.
Create a custom Validator and register it by doing stated below.
Create a custom validator for password format, created a customClass for our customvalidator named "CustomValidator" extends the Illuminate\Validation\Validator class to your customize class.
public function validatePasswordFormat($attribute,$value,$parameters){
return preg_match(("/^(?=.)[A-Za-z\d][A-Za-z\d!##$%^&()_+]{2,25}$/"),$value);}
alphanumeric with special characters !##$%^&*()_+
2-25 range of characters only. you can change this anytime.
Boot your Custom Validator to the app service Providers.
public function boot(){
Validator::resolver(function($translator,$data,$rules,$messages){
return new CustomValidator($translator,$data,$rules,$messages);
});
}
Use is easily by doing in your request like this.
'password' => "required|password_format"
and then in your message response for error.
'password_format' => "Invalid password format. blah blah blah"
I hope this will help you.

Using ValidatesRequests trait in Laravel

Here's the code from my AuthController:
public function postRegister(Request $request)
{
$this->validate($request, [
'name' => 'required|min:3',
'email' => 'required|email|unique:users',
'password' => 'required|min:5|max:15',
]);
}
If the validation fails I'm getting redirected to the previous page. Is there a way to pass additional data along with the input and the errors (which are handled by the trait)?
Edit: Actually, the trait does exactly what I want, except the additional data I want to pass. As #CDF suggested in the answers I should modify the buildFailedValidationResponse method which is protected.
Should I create a new custom trait, which will have the same functionality as the ValidatesRequests trait (that comes with Laravel) and edit the buildFailedValidationResponse method to accept one more argument or traits can be easily modified following another approach (if any exists)?
Sure you can, check the example in the documentation:
http://laravel.com/docs/5.1/validation#other-validation-approaches1
Using the fails(); method, you can flash the errors and inputs values in the session and get them back with after redirect. To pass other datas just flash them with the with(); method.
if ($validator->fails()) {
return back()->withErrors($validator)
->withInput()
->with($foo);
}

Yii: validation rules that always apply except one scenario

I know that you can have a validation rule that applies only for one scenario:
array('username', 'exist', 'on' => 'update'),
Now i would like to know if it's possible to do the opposite: a rule that applies everytime except for a given scenrio?
The only solution that is see right now is list all the others scenario, but it's not pretty if we need to add some news scenarios later.
array('username', 'exist', 'on' => array('create', 'search', ...),//all the scenarios except update
As of Yii 1.1.11 you can use except keyword:
array('username', 'exist', 'except' => 'update'),
Take a look at this page. There is a little example there.
Doc link
Work the same way in Yii 2.0.
['username', 'required', 'except' => 'update']
Every key in the array before the name of the validator is a property for the Validator Class itself. You can see the available properties in https://www.yiiframework.com/doc/api/2.0/yii-validators-validator
I know is an old question but every time I forgot that yii2 have an except property in the validator class.
https://www.yiiframework.com/doc/guide/2.0/en/input-validation for more advanced technics

Categories