Using multidimensional array input names with Lara

2019-06-08 03:23发布

问题:

I'm having an issue in Laravel 4.2 with the Form facade when using input names that represent multidimensional arrays. The form will load, display, and post data correctly unless there are values set in Input::old() (because of failed validation, etc.).

Here is a simple example that shows the problem:

routes.php:

Route::get('input-test', function() {
  return View::make('input_test.index');
});

Route::post('input-test', function() {
  return Redirect::back()->withInput(Input::all());
});

input_test/index.blade.php:

<!doctype html>
<html>
  <head>
    <title>Input Array Test</title>
  </head>

  <body>
    {{ Form::open(array('url' => 'input-test')) }}
      {{ Form::label('customer[some_customer_field][]', 'Customer Field:') }} <br>
      {{ Form::text('customer[some_customer_field][]', null) }}
      {{ Form::submit('Submit') }}
    {{ Form::close() }}
  </body>
</html>

Submitting this form will throw an error:

htmlentities() expects parameter 1 to be string, array given 

Is there a way to get inputs with these types of names to work on postback?

回答1:

That way is not the proper one.

Following one is it

{{ Form::label('customer[0][field_1], 'Customer Field:') }} <br>
{{ Form::text('customer[0][field_2]', null) }}

After that, if you want to duplicate it, you must use

{{ Form::label('customer[1][field_1], 'Customer Field:') }} <br>
{{ Form::text('customer[1][field_2]', null) }}

But if you want just get a simple array, you must use

{{ Form::label('customer[field_1], 'Customer Field:') }} <br>
{{ Form::text('customer[field_2]', null) }}