kate_hudson February 2016

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, [        

Answers


Oliver Queen February 2016

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

{{ old('username') }}


kate_hudson February 2016

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']) !!}

Post Status

Asked in February 2016
Viewed 2,487 times
Voted 11
Answered 2 times

Search




Leave an answer