Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug: rules() "required" is generated before "*_default" #22

Open
siggi-k opened this issue Aug 9, 2024 · 3 comments · May be fixed by #24
Open

Bug: rules() "required" is generated before "*_default" #22

siggi-k opened this issue Aug 9, 2024 · 3 comments · May be fixed by #24
Assignees

Comments

@siggi-k
Copy link

siggi-k commented Aug 9, 2024

The automatic generation of rules() first generates 'required' and then 'default' values.
Consequently, default values are not considered when checking 'required'.
The 'required' rules should therefore be generated after 'default'.

Example

schema.yaml

...

      required:
        - verified
      properties:
         verified:
            type: boolean
            default: false
...

This means that "verified" must be set. If it is not passed in a form, it must be saved as false.

The succession of generic "rules".

ACTUAL STATE

'trim' => [...],
'required' => [...],
...
'verified_default' => [['verified'], 'default', 'value' => false],
...

TARGET STATE

'trim' => [...],
'verified_default' => [['verified'], 'default', 'value' => false],
// all defaults
'required' => [...],
...
@SOHELAHMED7
Copy link
Member

Though I have already implemented the solution for this issue, I think required validation is not required for boolean with default values.

It can be achieved as

$model = new Post;
$model->loadDefaultValues();
if ($model->load($_POST) && $model->validate()) {
}

@cebe
Copy link
Member

cebe commented Nov 12, 2024

This does not really make sense, default applies if empty, using required means it can not be empty.

@SOHELAHMED7
Copy link
Member

@siggi-k

I would like to know your use case can be achieved by any below options?

Option 1: set default value false in database table. And Yii model validation rules, remove required rule

Option 2: can you please check if yii\validators\RequiredValidator::$skipOnEmpty and/or yii\validators\RequiredValidator::$requiredValue fixes your use case

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants