katie hudson
katie hudson

Reputation: 2893

Laravel 5 - Old Data on multiple checkboxes

I have a lot of checkboxes which take the following form in my template

<div class="col-md-6 checkbox checkbox-danger">
    {!! Form::checkbox('testingOptions[]', 'Checkbox A', null, ['class' => 'styled', 'id' => 'checkbox1']) !!}
    <label for="checkbox1">
        Checkbox A
    </label>
</div>
<div class="col-md-6 checkbox checkbox-danger">
    {!! Form::checkbox('testingOptions[]', 'Checkbox B', null, ['class' => 'styled', 'id' => 'checkbox2']) !!}
    <label for="checkbox2">
        Checkbox B
    </label>
</div>

So selected options are saved to testingOptions[].

In my controller, I get the input, and then basically implode all of the choices into a single string

$testingOptions = Input::get('testingOptions');
$testingOptions = implode('&&&', $testingOptions);

In my database, I end up with something like this

Checkbox A&&&Checkbox B

This is all fine. For my edit controller, I am doing the following

$selectedOptions = $project->something->testing;
if($selectedOptions != "") {
    $selectedOptions = explode('&&&', $selectedOptions);
    return View::make('something.edit', compact('project', 'selectedOptions'));
}

With that done, in my edit template, if I output selectedOptions I have something like this

array:2 [▼
  0 => "Checkbox A"
  1 => "Checkbox B"
]

So knowing that on my edit page i have

<div class="col-md-6 checkbox checkbox-danger">
    {!! Form::checkbox('testingOptions[]', 'Checkbox A', null, ['class' => 'styled', 'id' => 'checkbox1']) !!}
    <label for="checkbox1">
        Checkbox A
    </label>
</div>
<div class="col-md-6 checkbox checkbox-danger">
    {!! Form::checkbox('testingOptions[]', 'Checkbox B', null, ['class' => 'styled', 'id' => 'checkbox2']) !!}
    <label for="checkbox2">
        Checkbox B
    </label>
</div>

Is there any way to use the variable array of previously selected options to pre-select their matches within my form?

Thanks

Upvotes: 0

Views: 785

Answers (2)

katie hudson
katie hudson

Reputation: 2893

I managed to solve this by doing

{!! Form::checkbox('testingOptions[]', 'Checkbox A', in_array('Checkbox A', $testingOptions), ['class' => 'styled', 'id' => 'checkbox1']) !!}
{!! Form::checkbox('testingOptions[]', 'Checkbox B', in_array('Checkbox B', $testingOptions), ['class' => 'styled', 'id' => 'checkbox1']) !!}

Upvotes: 2

Derek Pollard
Derek Pollard

Reputation: 7165

To achieve this, I'd use laravel's built in old() function:

{{ old('username') }}

Upvotes: 1

Related Questions