【问题标题】:CakePHP Input form search for product id and show result on the same pageCakePHP 输入表单搜索产品 id 并在同一页面上显示结果
【发布时间】:2014-02-23 10:27:08
【问题描述】:

正如标题所说,我需要使用输入表单从我的数据库中搜索数据并将查询返回到同一页面。

我尝试过 Google 和此处提供的许多不同类型的解决方案。到目前为止,他们都没有和我一起工作过。而且我对 CakePHP 很陌生,所以很明显我错过了一些东西..

我的数据的表名是“posts”。

所以我想要这个搜索的视图是(search.ctp),我有这样的表格:

<?php
  echo $this->Form->create('Search');
  echo $this->Form->input('search', array('label' => 'Search with ID'));
  echo $this->Form->end('Search');
?>

根据我的发现,我很困惑是否应该使用我的 PostsController.php 作为搜索功能,或者为此将新的 Controller 设置为 SearchController.php,模型也是如此。

此时我正在使用 SearchController.php 进行尝试,代码如下:

class SearchController extends AppController {


    public function search(){

        $keyword=$this->params->query['keyword']; 

        $cond=array('OR'=>array("Post.id LIKE '%$keyword%'","Post.title LIKE %$keyword%'")  );

        $list = $this->Post->find('all',array('conditions')=>$cond);

    }
}

我试图在页面 search.ctp 代码上显示我的查询结果的部分如下:

<?php
      foreach($list as $post): ?>

   <tr>
     <td> <?php echo $post ["Search"]["id"]; ?> </td>
     <td>   
         <?php echo $this->Html->link($post["Search"]["title"], array("controller" => "posts", "action" => "search", $post["Search"]["id"])); ?>
    </td>

    <td><?php echo $post["Search"]["created"]; ?></td>
   </tr>
<?php endforeach; ?>
<?php unset ($post); ?>

我敢打赌,代码有点迟钝,我为此尝试了很多不同的解决方案,所以现在代码完全搞砸了,我怀疑..

无论如何,如果有人愿意帮助有需要的人,请提前感谢您!

【问题讨论】:

    标签: php forms cakephp input


    【解决方案1】:

    在搜索操作中,您必须验证帖子已发送。 所以 如果($_POST) { $keyword=$this->params->query['keyword'];

        $cond=array('OR'=>array("Post.id LIKE '%$keyword%'","Post.title LIKE %$keyword%'")  );
    
        $list = $this->Post->find('all',array('conditions')=>$cond);
        $this->set("list",$MyData);
    

    }

    【讨论】:

      【解决方案2】:

      这完全是错误的,您尝试通过 POST (Post.search) 进行搜索,但使用 URL 中的查询参数 (/posts/index/?keyword=something)。你认为它应该如何到达那里?顺便问一下,你为什么还要搜索 id?

      没有必要创建搜索控制器,我不明白为什么人们喜欢这样做,但绝对没有必要这样做。您可以在与搜索相同的页面上列出您的帖子,甚至分页:

      public function index() {
          if ($this->request->is('post') && !empty($this->request->data['Post']['search'])) {
              $searchTerm = '%' . $this->request->data['Post']['search'] . '%';
              $this->Paginator->settings['conditions']['OR'] = array(
                  'Post.id LIKE' => $searchTerm,
                  'Post.title LIKE' => $searchTerm,
              );
          }
          $this->set('posts', $this->Paginate->paginate());
      }
      

      如果您尝试在 URL 中获取搜索词,则此处使用的正确模式是 the PRG pattern。 CakePHP 的CakeDC search plugin 很好地实现了这一点,并且很容易实现。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-06-25
        • 2013-12-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多