laravel-bootstrap-4-forms
laravel-bootstrap-4-forms copied to clipboard
Add field name array bracket support
I ran into a similar issue as #46 where I needed to validate forms that use nested array bracket ([]
) names.
Example form and request validator rules.
<input type="text" name="author[name]"/>
<input type="text" name="author[description]"/>
$request->validate([
'author.name' => 'required',
'author.description' => 'required',
]);
Instead of validating them correctly (or not finding the error at all), the package was throwing an exception.
This PR just adds a method that conditionally transforms the field names to a dot format ('author[name]'
=> 'author.name'
) for the purpose of finding any applicable validation messages in the session's error message bag, as well as, find any old input values. This field names are transformd to match what Laravel's validators return for nested parameters (dot notation).
You'll notice the added _transformToDotSyntax
also replaces other characters, namely .
to _
as that's how PHP converts them by default.
This would also fix #51.
@netojose When will you be able to implement this ?
Hi,
Today i was working on an array of checkboxes like. Correct me if I am doing it wrong.
@if(!$permissions->isEmpty())
<label for="permissions">{{ __('menu.permissions') }}</label>
@foreach ($permissions as $permission)
{!!Form::checkbox('permissions[]', $permission->name, $permission->id )->idPrefix('permission-'.$permission->id.'-')->disableValidation()!!}
@endforeach
<br>
@endif
But the old value was not setting, also i could not override it. I was trying to set checked by
->checked(in_array($permission->id, (old('permissions') ?? array())))
I looked in the source code to try and fix it and helping the project.
I changed the FormBuilder.php file, starting at line 262. I added the substr, is_array and in_array.
if ($this->isRadioOrCheckbox()) {
if ($this->hasOldInput()) {
if (substr($name, -2) == "[]" && is_array(old($name = rtrim($name,"[]")))) {
$isChecked = in_array($value, old($name));
} else {
$isChecked = old( $name ) === $value;
}
} else {
$isChecked = isset($formData[$name]) ? $formData[$name] === $value : $checked;
}
$attributes['checked'] = $isChecked;
}
Hello @netojose, can you combine it to main branch?
Hello @netojose, can you combine it to main branch?
@tatarysh , sorry for late response, I was traveling. I will check tonight and merge.
Tha ks @kynetiv !!!!