如何在Laravel中跨分页请求持久化检查项



我有一个表单,其中显示了一些项目,这些项目可以由用户选择。有1000多个项目,所以我使用分页。

当用户转到下一页时,保持选中项目的最佳方式是什么?

将所有这些项目存储在隐藏字段中是不可行的,因为它们相当多。

我的观点:

@foreach($articles['uncommitted'] as $article)
    <tr>
        <td><input type="checkbox" name="articles[]"></td>
        <td>{{{$article->articlename}}}</td>
        <td>{{{$article->category->catname}}}</td>
        <td>{{{strftime('%d.%m.%Y %H:%M', strtotime($article->created_at))}}
        <td>{{{$article->rrp}}}</td>>created_at))}}}</td>
    </tr>
@endforeach
{{$links}}

此表单将被分页。

据我所知,您面临两个问题:在分页请求中持久化已检查项,以及将已检查项检索回视图。

为了在分页请求中保持选中的项目,我会将选中的项目闪存到会话中。控制器方法看起来如下。

public function fill_form()
{
    $items = Item::paginate(25);
    // Retrieve checked items in session.
    $checked_items = []
    if (Session::has('checked_items'))
        $checked_items = Session::get('checked_items');
    // Persist new checked items.
    $checked_items = array_merge($checked_items, Input::get('item'));
    Session::flash('checked_items', $checked_items);
    return View::make('form')
        ->with('items', $items);
}

正如您所看到的,选中的项目将在分页请求中的会话中可用。

现在,为了将选中的项目显示回视图,我将在会话中通过旧输入将选中的项目发送到视图。也就是说,返回值将更改如下。

public function fill_form()
{
    # code intentionally omitted #
    return View::make('form')
        ->with('items', $items)
        ->withInput($checked_items);
}

然后,在您的视图中,选中的项目将保持其选中的值。显然,您应该使用Laravel来生成您的复选框。


如何在提交时获取所有项目(选中或未选中)

也许,如果您使用复选框渲染项目,您需要知道哪些复选框在分页时被选中,哪些没有被选中。一个简单的解决方案是为每个带有默认值的复选框添加一个额外的输入隐藏字段,它将如下所示:

{{ Form::hidden('item1', 'off') }}
{{ Form::checkbox('item1', 'on') }}
{{ Form::hidden('item2', 'off') }}
{{ Form::checkbox('item2', 'on') }}
{{ Form::hidden('item3', 'off') }}
{{ Form::checkbox('item3', 'on') }}

提交表单后,进行分页时,对于选中的项目,您将收到预期值,对于未选中的项目将收到隐藏值。

注意1,重要的是将隐藏输入放在每个复选框之前注意2,每个隐藏的输入都应该与复选框具有相同的名称。

除非我误解了你的问题,否则我认为你想要的是缓存:http://four.laravel.com/docs/cache

以下是文档摘录:


数据库缓存

使用数据库缓存驱动程序时,需要设置一个表来包含缓存项。下面是表的Schema声明示例:

Schema::create('cache', function($table)
{
    $table->string('key')->unique();
    $table->text('value');
    $table->integer('expiration');
});

如果你想跨请求存储表单数据,那么你需要使用Session-从文档中摘录(http://four.laravel.com/docs/session):

数据库会话

使用数据库会话驱动程序时,需要设置一个表来包含会话项。下面是表的Schema声明示例:

Schema::create('sessions', function($table)
{
    $table->string('id')->unique();
    $table->text('payload');
    $table->integer('last_activity');
});

最新更新