elfeffe's avatar

Persist form checkboxes (select and others) on pagination

I have a form where I select some options for my query, I'm adding pagination and all works good. Except that I lose the form data when I press "page 2" I'm using Laravel 5.2 Is to keep data on session the only way to keep form state?

0 likes
7 replies
Swaz's avatar

You can use the appends method. No need to store data in session.

{{ $users->appends(['sort' => 'votes'])->links() }}
elfeffe's avatar

What I want is to keep the "name" on the form (on the input) with the name that the used searched for. And to keep results for that name, but in page 2.

It is not what appends does, no?

Swaz's avatar
Swaz
Best Answer
Level 20

It can still work for that. Appends is meant for when your variables are set as url parameters.

mysite.com?name=John&page=3

Here is an example usage:

// users/index.blade.php
<form method="GET">
    <input type="text" name="name" value="{{ Input::get('name') }}">
    <button type="submit">Filter</button>
</form>

<ul>
    @foreach($users as $user)
        <li>{{ $user->name }}</li>
    @endforeach
</ul>

{{ $users->appends([
    'name' => Input::get('name')
])->links() }}

And then the controller could be something like this:

// UsersController.php
public function index(Request $request)
{
    $name = request('name');

    $users = User::when($name, function ($query) use ($name) {
        return $query->where('name', $name);
    })->paginate(12);

    return view('users.index', compact('users'));
}
1 like
elfeffe's avatar

Thank you for the info. It works good. Just a last question, any idea about how to mark "checked" for a checkbox, or "selected" for a dropdown?

elfeffe's avatar

Ok, just using

if (Input::get('checkbox_name') == 'true') { 
    echo 'checked';
}
Swaz's avatar

@elfeffe Yea that is one option. You could maybe inline it to clean things up.

<input type="checkbox" name="mycheckbox" value="1" {{ Input::get('mycheckbox') == 1 ? 'checked' : '' }}>
<input type="checkbox" name="mycheckbox" value="2" {{ Input::get('mycheckbox') == 2 ? 'checked' : '' }}>

Or wrap that logic in a helper function.

<input type="checkbox" name="mycheckbox" value="1" {{ isChecked('mycheckbox', 1) }}>
<input type="checkbox" name="mycheckbox" value="2" {{ isChecked('mycheckbox', 2) }}>

//helpers.php
function isChecked($name, $value) {
    return Input::get($name) == $value ? 'checked' : '';
}

I personally prefer using the Laravel Collective form helpers.

{{ Form::checkbox('name', 'value') }} // not selected
{{ Form::checkbox('name', 'value', true) }} // selected

{{ Form::checkbox('mycheckbox', 1, Input::get('mycheckbox') == 1) }}
{{ Form::checkbox('mycheckbox', 2, Input::get('mycheckbox') == 2) }}

And dropdowns work the same way.

{{ Form::select('myselect', [
    '1' => 'Value 1',
    '2' => 'Value 2'
], Input::get('myselect'), ['placeholder' => 'Pick one...']) }}
1 like

Please or to participate in this conversation.