Enrique Moreno Tent
Enrique Moreno Tent

Reputation: 25267

Laravel 4 - Sending the input back on a failed submission

I have this form

@extends('index')

@section('main')
    <h1>Create a new poll</h1>
    {{ Form::model(new Poll, ['route' => 'polls.store', 'class' => 'create-poll']) }}
        <div class="gray-box">
            {{ Form::label("topic", "Write your poll question") }}
            {{ Form::text('topic', '', ['placeholder' => 'Example: What is the best number?', 'id' => 'topic']) }}
        </div>

        <div class="gray-box">
            {{ Form::label(null, "Write the possible answers") }}
            {{ Form::text('option[]', null, ['class' => 'option', 'placeholder' => 'Test option']) }}

            <input type="button" class="more-options" value="Add another option">
            {{-- This will create another option[] input element --}}

        </div>

        {{ Form::submit() }}
    {{ Form::close() }}
@stop

There is more to it, but that is the important part. Basically it is a poll name. It has a topic and at least one option. Clicking on a button, you can add more options.

This is the controller:

public function store() {
    $data = Input::all();

    // Validate input
    $validator = Validator::make($data, Poll::$rules);
    if ($validator->fails())
        return Redirect::back()->withErrors($validator)->withInput();

    ...

The problem here is that the WithInput() throws an error:

ErrorException

htmlentities() expects parameter 1 to be string, array given (View: /home/dbugger/laravelproject/app/views/polls/create.blade.php)

I suspect is because I am using an Array Form Element, but im not sure why or how, since at the time being I am not even trying to re-fill the form with the (failed) submitted data...

Upvotes: 1

Views: 470

Answers (2)

Daniel Gasser
Daniel Gasser

Reputation: 5133

For grouped inputs like Form::text('option[]')... or Form::checkbox('options[]')... you need to rearrange the posted Array in your controller:

Something like:

$optionsInput = Input::get('option');

if(is_array($optionsInput)) {
   // process your options, eg like this
   foreach($optionsInput as $key => $input) {
        $proceededOptionsArray[$key] = $input;
   }
}

The same rule for array inputs is applicable for the validator, then:

// return it with other `Input`

return Redirect::back()
    ->withErrors($proceededValidatorArray + $validator)
    ->withInput($proceededOptionsArray + Input::all());

Upvotes: 1

Hassan Gilak
Hassan Gilak

Reputation: 699

{{ Form::text('option[]', null, ['class' => 'option', 'placeholder' => 'Test option']) }} its in the way you named the text field option[] ...

Upvotes: 0

Related Questions