laravel-bootstrap-4-forms icon indicating copy to clipboard operation
laravel-bootstrap-4-forms copied to clipboard

Add field name array bracket support

Open kynetiv opened this issue 5 years ago • 5 comments

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.

kynetiv avatar Apr 06 '19 19:04 kynetiv

This would also fix #51.

kynetiv avatar Apr 10 '19 16:04 kynetiv

@netojose When will you be able to implement this ?

PaulusMenheere avatar May 13 '19 12:05 PaulusMenheere

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;
}

ricklambrechts avatar Aug 07 '19 10:08 ricklambrechts

Hello @netojose, can you combine it to main branch?

tatarysh avatar Nov 06 '19 19:11 tatarysh

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 !!!!

netojose avatar Mar 02 '20 14:03 netojose