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

required_if rule doesn't work for child forms #247

Open
rudiedirkx opened this issue Jul 27, 2016 · 2 comments
Open

required_if rule doesn't work for child forms #247

rudiedirkx opened this issue Jul 27, 2016 · 2 comments

Comments

@rudiedirkx
Copy link
Collaborator

I have a child form EducationalInstitutionForm with a field customer_since, with a rule required_if:participation_type,gold,silver,bronze. participation_type is a 'choice' field in the same form. If I load the form on its own, that validation works. If I load the form as a child form inside another form, it doesn't work.

After debugging: Validator::validateRequiredIf() receives the correct attribute: educational_institution.customer_since, and has the correct $this->data, but it doesn't know the referenced field participation_type, because of the nested form. It should be educational_institution.participation_type in this case.

Since it doesn't know the field, the value is empty, and the other field isn't required.

Is there a way to make the validation work in both scenario's?: child form and form on its own

@kristijanhusak
Copy link
Owner

I would need to customize Laravels Validator for this. You could do something like this maybe:

$participationType = 'participation_type';
i ($this->getName() !== '') {
$participationType = $this->getName() . '.participation_type';
}

$this->add('customer_since', 'text', [
  'rules' => sprintf('required_if:%s,gold,silver,bronze', $participationType)
]);

It's ugly, but it should work.

@rudiedirkx
Copy link
Collaborator Author

What I did this time was:

'rules' => [
  'required_if:participation_type,gold,silver,bronze',
  'required_if:educational_institution.participation_type,gold,silver,bronze', // @todo Fix bug kristijanhusak/laravel-form-builder#247
  'date_format:Y-m-d',
],

which works only because it's a required_IF validation, not a required_UNLESS (the opposite). It ignores the one that doesn't exist.

I think the form builder could do this by defining a list of rules that require another element. Maybe Laravel's Validator already has that...

$this->getName() might not be enough, because the form might be doubly nested. (Or does getName() include parents?)

I'll take a crack at it some time.

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

No branches or pull requests

2 participants