We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

How to search in phalcon using criteria query



10.3k
Accepted
answer
 /**
     * Execute the "search" based on the criteria sent from the "index"
     * Returning a paginator for the results
     */
    public function searchAction()
    {
        $numberPage = 1;
        if ($this->request->isPost()) {//create the query conditions
            $query = Criteria::fromInput($this->di, "Products", $_POST);
            $this->persistent->searchParams = $query->getParams();
        } else {//paginate using the existing conditions
            $numberPage = $this->request->getQuery("page", "int");
            if ($numberPage <= 0) {
                $numberPage = 1;
            }
        }

        $parameters = array();
        if ($this->persistent->searchParams) {
            $parameters = $this->persistent->searchParams;
        }

        $products = Products::find($parameters);
        if (count($products) == 0) {
            $this->flash->notice("The search did not find any products");
            return $this->forward("products/index");
        }

        $paginator = new Phalcon\Paginator\Adapter\Model(array(
            "data" => $products,
            "limit" => 5,
            "page" => $numberPage
        ));
        $page = $paginator->getPaginate();

        $this->view->setVar("page", $page);
    }

https://github.com/phalcon/invo/blob/master/app/controllers/ProductsController.php