I'm dealing with an "old" issue and wondering if there's something I'm doing wrong. When we have an array in FormData
, the name of that array usually goes like field[]
, where the []
indicates an array and can then be processed by PHP (in my case, Laravel) when the data is sent to the server. But in Angular reactive forms, the array name is mere field
and Laravel complains that's not an array.
This is the code I have in Angular:
public form = this.fb.group({
array_field: this.fb.array([]),
normal_field: [null],
});
And then in HTML:
<form [formGroup]="form" (ngSubmit)="submit)">
<mat-form-field>
<mat-label>Type</mat-label>
<mat-select multiple="true" [formControl]="form.controls.array_field">
<mat-option [value]="'reports'">Reports</mat-option>
<mat-option [value]="'companies'">Companies</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field>
<mat-label>Normal</mat-label>
<mat-select [formControl]="form.controls.normal_field">
<mat-option [value]="'reports'">Reports</mat-option>
<mat-option [value]="'companies'">Companies</mat-option>
</mat-select>
</mat-form-field>
</form>
The request (FormData) that gets sent to the server looks like:
array_field: reports
array_field: companies
normal_field: null
while it should be:
array_field[]: reports
array_field[]: companies
normal_field: null
And this is what Laravel sees ($request->all())
:
array:2 [
"array_field" => reports,
"normal_field" => null
]
Notice that there's only one of array_fields while the second one is discharged.
Usually I resort into using alternative code that does not use [formGroup]
and [formControl]
, where I can set the name as I want, but I would prefer to use reactive all the way.