yii2
yii2 copied to clipboard
RequiredValidator with typed properties
Q | A |
---|---|
Yii version | 2.0.49 |
PHP version | 7.4 |
Is bugfix | Yes |
Breaks BC? | No (not sure) |
What steps will reproduce the problem?
$model = SomeModelWithTypedProperties();
$model->setAttributes([]);
$model->validate();
What is the expected result?
Validation error, Prop1 cannot be blank.
What do you get instead?
Typed property prop1 must not be accessed before initialization
Solution
Change RequiredValidator. See @DplusG/yii2-required-validator
I'm not sure if we should get back to this old thing already mentioned in https://github.com/yiisoft/yii2/issues/17954 What exactly is your use-case? I mean, how does your SomeModelWithTypedProperties look like?
class SomeModelWithTypedProperties extends Model
{
public string $prop1;
public ?string $optionalProp2 = null;
public function rules(): array
{
return [
[['prop1'], 'required'],
];
}
}
// I don't know current data like in https://github.com/yiisoft/yii2/issues/17954
// and I want to see which properties are really required at the language level
// (not like: public ?string $prop1 = null)
$model->setAttributes($post);
Thank you, I see in https://github.com/yiisoft/yii2/issues/17954 'prefer not handing it' from samdark
In this issue I suggest to change the programm error to the validation error.
I can suggest an internal validator initialized
, But it's no so clear.
return [
[['prop1'], 'initialized'],
[['prop1'], 'required'],
];
Validation error is what we received in php <=7.3. I show it in my repo
Fixing typed properties in validation seems like a lost cause to me, due to how Yii handles validation in models: it first assigns value to property, and then validates it. So if you type property as string and someone pass array as value for it, it will throw fatal error before even validation begins.
Yes, likely that isn't fixable in Yii2.
Ok, thanks! In my case, I did not try to solve typecasting. Only initialization.
Can I add packages from Yii3 to solve this problem? Validator, hydrator, form-model?
True, but this is another case here. Yii is checking the attribute first before assigning it hence the error for not initializing. DplusG has a model with invalid state for $prop1 here. The thing with incompatible types and this problem both are developer issues.
DplusG - for your case this is simple, you must initialize the property.