Thursday, March 17, 2022

[FIXED] CakePHP implementing search inside a view

Issue

I have a index view which shows all products and works fine, I would like to have a search bar on the top where users could search by keyword. My controller looks like this:

    class ProductsController extends AppController{
        public function search(){
            $this->loadModel('Item');
            $this->view('index');
            $keyword = $this->request->data['Item']['keywords'];
            $this->Product->recursive = 0;
            $this->paginate = array(
                'conditions' => array('Item.is_deleted' => false, 'Item.name LIKE' => "%$keyword", 'Item.item_type_id' => 15)
            );
            $this->set('products', $this->Paginator->paginate());
            $this->redirect(array('action' => 'index'));
        }
    }

Items show up because product is an item and I have two tables but it should not be a problem I just want to filter by keyword.

This is the index view:

    <div class="products index">
        <h2><?php echo __('Products'); ?></h2>
        <?php echo $this->Form->create('Product', array('url' => 'search')) ?>
            <fieldset>
                <legend><?php echo __('Search Products') ?></legend>
                <?php
                    echo $this->Form->input('Item.keywords');
                ?>
            </fieldset>
        <?php echo $this->Form->end(__('Submit')) ?>
        //other stuff for index view

But even though I made this view to be rendered in the search controller when I submit the form I get "The requested address '/WarehouseManagementApp/products/search' was not found on this server." So maybe I am missing something, or maybe I should implement this differently.


Solution

So actually it was dumb to have a separate function for this, all I did was put it all in the index function and check whether search button is called or not (post or not):

public function index() {
        if ($this->request->is(array('post', 'put'))) {
            $keyword = $this->request->data['Item']['keywords'];
            $this->Product->recursive = 0;
            $this->paginate = array(
                'conditions' => array('Item.is_deleted' => false, 'Item.name LIKE' => '%' . $keyword . '%')
            );
            $this->set('products', $this->Paginator->paginate());
        }else{
            $this->Product->recursive = 0;
            $this->paginate = array(
                'conditions' => array('Item.is_deleted' => false)
            );
            $this->set('products', $this->Paginator->paginate());
        }
    }


Answered By - Младен Карић

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.