Cakephp - 索引搜索

问题描述 投票:0回答:2

我有一个关于我如何搜索的问题,例如,在INDEX视图中按名称或姓氏搜索。是否有任何插件或易于使用的组件不会过多加载应用程序?

目前,我在index.ctp中有一个小表单,其中有一个输入字段,我在其中输入我想要搜索的内容,并且在控制器中有一个if($ this-> request-> is('post'))之后$ this-> Model-> find添加条件WHERE。但我承认这不是一个好方法,它也重新加载页面。

这是控制器:

public function index()
{
    if ($this->request->is('post')) {
        $s = '%'.$this->request->getData('Search').'%';
        $students = $this->Students->find('all')->where(['OR' => ['name LIKE' => $s, 'lastname LIKE' => $s]]);
        $this->set('students', $this->paginate($students));
    } else {
        $students = $this->paginate($this->Students);
        $this->set(compact('students'));
    }
}

这是index.ctp:

<div class="input-group mb-3">
    <?= $this->Form->button(__('<i class="fas fa-search"></i>'), ['escape' => false, 'class' => 'btn btn-primary']) ?>
    <?= $this->Form->input('Search', ['type' => 'text', 'class' => 'form-control', 'label' => false]); ?>
    <?= $this->Form->end() ?>
</div>
php cakephp search plugins cakephp-3.x
2个回答
0
投票

从我可以看到你要么是一个更好的解决方案来处理搜索和/或一种不重新加载页面来显示你的搜索结果。如果这不是您的意思,那么请澄清您的问题,以便更好地概述您希望解决方案的样子。

您应该将搜索功能与索引功能分开,因为这只是为了显示该页面上的内容。添加像你这样的条件将最终导致你有一个非常长的索引函数,根据请求中的差异运行你的整个应用程序,这不是很好。

将搜索分成一个单独的功能,然后创建一个新页面供您显示结果。

public function index()
{
    $students = $this->paginate($this->Students);
    $this->set(compact('students'));
}

public function search()
{
    $s = '%' . $this->request->getData('Search') . '%';
    $students = $this->Students->find('all')->where(['OR' => ['name LIKE' => $s, 'lastname LIKE' => $s]]);
    $this->set('students', $this->paginate($students));
}

这在CakePHP文档的教程中有详细描述 - CMS Tutorial - Creating the Articles Controller,可以与您的应用程序相关,因为您的索引包含一个表单,用于将搜索条件传递给您的应用程序,然后搜索功能/页面将获取结果并显示它们您。

不要忘记然后更改您的表单,将其指向/search页面。 - Setting a URL for the Form

您需要在src / Template / ExampleController文件夹中创建一个search.ctp文件。将您的html代码放在那里以在表格中显示结果,或者您想要显示搜索结果。

最后,您需要在routes.php中添加一个路径,以允许应用程序中的/search路径。

$routes->connect('/search', ['controller' => 'Example', 'action' => 'search']);

现在,如果您不希望在使用表单时重新加载页面,则必须使用Ajax和JS / JQuery向搜索方法发出请求,并在页面上动态显示搜索功能的结果。在stackoverflow和web上已经有很多很好的例子,可以使用ajax和jquery来构建搜索表,所以我不打算在这里发布它们。

如果您需要插件/库解决方案,请查看本教程,了解如何使用DataTables在表中显示搜索结果。 - Search Using Datatables


0
投票

安装插件https://github.com/FriendsOfCake/search

然后在搜索配置中

$this->searchManager()
     // Here we will alias the 'q' query param to search the `Students.name`
     // field and the `Students.lastname` field, using a LIKE match, with `%`
            // both before and after.
            ->add('q', 'Search.Like', [
                'before' => true,
                'after' => true,
                'fieldMode' => 'OR',
                'comparison' => 'LIKE',
                'wildcardAny' => '*',
                'wildcardOne' => '?',
                'field' => ['name', 'lastname']
            ]);
© www.soinside.com 2019 - 2024. All rights reserved.