result ammount not showing correct - php

On my pagination results it is not showing correct for example it should show Showing 1 to 5 of 5 (1 Pages) on view but for some reason it is showing Showing -19 to 0 of 5 (1 Pages)
I am not sure why it is showing -19 should show 1 $the $data['results'] not working correct how can I fix it.
<?php
class Users_group extends MX_Controller {
public function index() {
$this->load->library('paginations');
$this->load->model('admin/user/model_user_group');
$data['title'] = "Users Group";
// Sort
if (null !==($this->uri->segment(3))) {
$sort = $this->uri->segment(3);
} else {
$sort = 'name';
}
// Order
if (null !==($this->uri->segment(4))) {
$order = $this->uri->segment(4);
} else {
$order = 'asc';
}
// Page
if (null !==($this->uri->segment(3))) {
$page = $this->uri->segment(3);
} else {
$page = 1;
}
$url = '';
// Sort
if (null !==($this->uri->segment(3))) {
$url .= $this->uri->segment(3);
}
// Order
if (null !==($this->uri->segment(4))) {
$url .= $this->uri->segment(4);
}
// Page Number
if (null !==($this->uri->segment(3))) {
$url .= $this->uri->segment(3);
}
$admin_limit = "20";
$filter_data = array(
'sort' => $sort,
'order' => $order,
'start' => ($page - 1) * $admin_limit,
'limit' => $admin_limit
);
$user_group_total = $this->model_user_group->getTotalUserGroups();
$results = $this->model_user_group->getUserGroups($filter_data);
foreach ($results as $result) {
$data['user_groups'][] = array(
'user_group_id' => $result['user_group_id'],
'name' => $result['name'],
'edit' => site_url('admin/users_group/edit' .'/'. $result['user_group_id'] . $url)
);
}
$url = '';
if ($order == 'asc') {
$url .= 'desc';
} else {
$url .= 'asc';
}
$data['sort_name'] = site_url('admin/users_group' .'/'. 'name' .'/'. $url);
$url = '';
$paginations = new Paginations();
$paginations->total = $user_group_total;
$paginations->page = $page;
$paginations->limit = $admin_limit;
$paginations->url = site_url('admin/users_group' .'/'. $url . '{page}');
$data['pagination'] = $paginations->render();
$paginations_lang = "Showing %d to %d of %d (%d Pages)";
$data['results'] = sprintf($paginations_lang, ($user_group_total) ? (($page - 1) * $admin_limit) + 1 : 0, ((($page - 1) * $admin_limit) > ($user_group_total - $admin_limit)) ? $user_group_total : ((($page - 1) * $admin_limit) + $admin_limit), $user_group_total, ceil($user_group_total / $admin_limit));
$data['sort'] = $sort;
$data['order'] = $order;
$this->load->view('template/user/users_group_list.tpl', $data);
}
public function getForm() {
$data['title'] = "Users Group";
$this->load->view('template/user/users_group_form.tpl', $data);
}
}

Related

filtering and sorting with pagination in laravel

Hi I'm using Laravel and I have a sorting and filtering system it works via url like this
http://localhost:8000/halehule/category/103?type=all&minprice=+10+&maxprice=+10000000000+&color=&sortBy%5Bfield%5D=price&sortBy%5BorderBy%5D=desc
so when I use pagination it does not work and refresh to original page like this :
http://localhost:8000/halehule/category/103?page=2
How can I use pagination with sorting and filtering like this
here is my method
public function brandProduct($shop, $id, Request $request) {
$colors = Color::all();
$shop = Shop::where('english_name', $shop)->first();
$shopTags = $shop->tags;
$shopCategories = $shop->ProductCategories()->get();
$categories = Shop::where('english_name', $shop->english_name)->first()->ProductCategories()->get()->where('parent_id', null);
$brand = Brand::where('id', $id)->get()->first();
$brands = $shop->brands;
$shopProducts = $shop->products;
$minPriceProduct = $shopProducts->min('price');
$maxPriceProduct = $shopProducts->max('price');
//color product and category product merging
if($request->color == null){
$colorAndBrandProducts = $brand->products->sortByDesc('created_at');
}
else{
$colorProducts = Color::where('code', $request->color)->get()->first()->products;
$brandProducts = $brand->products;
$colorAndBrandProducts = collect();
foreach($colorProducts->toBase()->merge($brandProducts)->groupBy('id') as $allProducts){
if($allProducts->count() > 1){
$colorAndBrandProducts[] = $allProducts;
}
}
$colorAndBrandProducts = $colorAndBrandProducts->first();
}
if ($request->has('type') and $request->has('sortBy') and $request->has('minprice') and $request->has('maxprice') and $request->has('color')) {
if($colorAndBrandProducts != null){
$minPrice = $request->minprice;
$maxPrice = $request->maxprice;
$filterBy = $request->type;
$sortBy = $request->sortBy['field'];
$perPage = 16;
if($shop->template->folderName == 2){
$sortBy_array = explode('|', $request->sortBy['field']);
$sortBy = $sortBy_array[0];
$orderBy = $sortBy_array[1];
}
else{
$orderBy = $request->sortBy['orderBy'];
}
if ($request->type == 'all') {
if ($orderBy == 'desc') {
$products = $colorAndBrandProducts->whereBetween('price', [$minPrice, $maxPrice])->sortByDesc($sortBy)->unique('id');
} else {
$products = $colorAndBrandProducts->whereBetween('price', [$minPrice, $maxPrice])->sortBy($sortBy)->unique('id');
}
} else {
if ($orderBy == 'desc') {
$products = $colorAndBrandProducts->where('type', $filterBy)->whereBetween('price', [$minPrice, $maxPrice])->sortByDesc($sortBy)->unique('id');
} else {
$products = $colorAndBrandProducts->where('type', $filterBy)->whereBetween('price', [$minPrice, $maxPrice])->sortBy($sortBy)->unique('id');
}
}
}
else{
$products = collect();
}
}
else {
$products = $colorAndBrandProducts;
}
$total = $products->count();
$perPage = 16; // How many items do you want to display.
$currentPage = request()->page; // The index page.
$productsPaginate = new LengthAwarePaginator($products->forPage($currentPage, $perPage), $total, $perPage, $currentPage);
$template_folderName = $shop->template->folderName;
SEOTools::setTitle($shop->name . ' | ' . $brand->name);
SEOTools::setDescription($shop->description);
SEOTools::opengraph()->addProperty('type', 'website');
return view("app.shop.$template_folderName.layouts.partials.products", compact('products','minPriceProduct', 'maxPriceProduct', 'shopCategories', 'brand', 'shop', 'categories', 'productsPaginate', 'brands', 'shopTags','colors'));
}
I use this method for sorting and filtering and use pagination works great but without sorting and filtering
just apply ->append($_GET) to your pagination

show post of category in index controller codeigniter

i completely new in ci and i build a project that have index page and show posts in this page with pagination, i have menu sidebar that contain categories , i want when i click each them show posts of that category. how can change my code to that?
home_controller
class Home extends Ci_controller {
function __construct() {
parent:: __construct();
$this->load->model('home_model');
$this->load->model('category_model');
$this->load->library('pagination');
}
function index() {
$category = $this->category_model->allCategory();
$config['base_url'] = base_url() . 'index.php/home/index/page/';
$config['total_rows'] = $this->home_model->countall();
$config['per_page'] = 5;
$config['uri_segment'] = 4;
$page = ($this->uri->segment(4)) ? $this->uri->segment(4) : 0;
$this->pagination->initialize($config);
$posts = $this->home_model->all($config['per_page'], $page);
$setting = $this->home_model->setting('about');
$pagination = $this->pagination->create_links();
$this->template->load('home', array('posts' => $posts, 'pagination' => $pagination, 'category' => $category, 'setting' => unserialize($setting['value'])));
}
}
home_model
class Home_model extends CI_Model {
function __construct() {
parent::__construct();
}
function allPost() {
$all = $this->db->get('posts')->result_array();
$data_send = array();
foreach ($all as $key => $value) {
$data = array();
$category = $this->db->get_where('catpost', array('post_id' => $value['post_id']))->result_array();
$data['id'] = $value['post_id'];
$data['title'] = $value['title'];
$data['create_time'] = $value['create_time'];
$data['content'] = $value['content'];
$data['username'] = $value['username'];
$data['category'] = $category;
$data_send[] = $data;
}
return $data_send;
}
function all($limit, $start) {
$lastpost = $this->db->select('post_id')->order_by('create_time DESC')->limit($limit, $start)->get('post')->result_array();
$idarr = array();
foreach ($lastpost as $key => $value) {
$idarr[] = "'{$value['post_id']}'";
}
$ids = implode(',', $idarr);
$sql = "select tbl_post.post_id, tbl_category.name, tbl_post.title, tbl_post.content, tbl_post.create_time, tbl_post.author_id, tbl_user.username from `tbl_category` join `tbl_post_category` on `tbl_post_category`.`category_id`=`tbl_category`.`category_id` join `tbl_post` on `tbl_post`.`post_id`=`tbl_post_category`.`post_id` join tbl_user on tbl_user.user_id=tbl_post.author_id where tbl_post.post_id in($ids) ORDER BY tbl_post.post_id DESC";
$allpost = $this->db->query($sql)->result_array();
$posts = array();
foreach ($allpost as $key => $value) {
$postid = $value['post_id'];
if (array_key_exists($postid, $posts)) {
$posts[$postid]['category'] .= ",{$value['name']}";
} else {
$posts[$postid] = array(
'post_id' => $postid,
'title' => $value['title'],
'content' => $value['content'],
'create_time' => $value['create_time'],
'username' => $value['username'],
'category' => $value['name']);
}
}
return $posts;
}
function setting($name = NULL) {
$ret = NULL;
if ($name != NULL) {
$this->db->where('name', $name);
$ret = $this->db->get('setting')->result_array()[0];
} else {
$ret = $this->db->get('setting')->result_array();
}
return $ret;
}
function countall() {
Return $this->db->count_all('posts');
}
}
view part of category
<?php
foreach($category as $key => $value){
$name='category['.$value['name'].']';
echo '<li><a href='.$value['name'].'>'.$value['name'].'</a></li>';
}
?>

Pagination can not back to prev number

I have pagination, and my pagination is working fine if I click next number.
View :
1 2 >
if I am clicking on 2 it goes on second page and shows proper result.but if I want to come back on 1 than its not redirect to page 1. here is my controller code:
public function index($date_start = 'all', $date_end = 'all', $title = 'all', $cid = 0, $skpd = 'all', $offset = NULL)
{
if($_POST)
{
$filter = array(
($this->input->post('filter_date_start') == '') ? 'all' : $this->input->post('filter_date_start'),
($this->input->post('filter_date_end') == '') ? 'all' : $this->input->post('filter_date_end'),
($this->input->post('filter_title') == '') ? 'all' : $this->input->post('filter_title'),
($this->input->post('filter_kategori') == 0) ? 0 : $this->input->post('filter_kategori'),
($this->input->post('filter_skpd') == '') ? 'all' : $this->input->post('filter_skpd')
);
$url = implode('/', $filter);
redirect('document/index'.$url);
}
//echo urldecode($title);
$this->load->model('News_model');
$this->load->library('pagination');
$data['title'] = 'Informasi Publik';
$param_document = array('status' => 1);
if(!empty($tid)) $param_document['tid'] = $tid;
if($date_start != 'all') $param_document['date_start'] = $date_start;
if($date_end != 'all') $param_document['date_end'] = $date_end;
if(!empty($cid)) $param_document['cid'] = $cid;
if($title != 'all') $param_document['title'] = urldecode($title);
if($skpd != 'all') $param_document['skpd'] = $skpd;
$params_total = $param_document;
$param_document_berkala = $param_document;
$param_document_serta_merta = $param_document;
$param_document_setiap_saat = $param_document;
$param_document_dikecualikan = $param_document;
$param_document['limit'] = 10;
$param_document['offset'] = $offset;
$data['document'] = $this->Document_model->get($param_document);
//dimodif cara urang
$data['bijilkategori'] = $this->Document_model->tampil();
// get document download count
foreach($data['document'] as $i => $row)
{
$document_transaction = $this->Document_model->get_transaction(array('did' => $row['document_id']));
$data['document'][$i]['download_count'] = empty($document_transaction) ? 0 : $document_transaction[0]['count'];
}
/*
$config['base_url'] = site_url('document/index/'.
(empty($tid) ? 0 : $tid).'/'.$date_start.'/'.$date_end.'/'.
$title.'/'.(empty($cid) ? 0 : $cid).'/'.$skpd
);
*/
$config['base_url'] = site_url('document/index/'.
$date_start.'/'.$date_end.'/'.
$title.'/'.(empty($cid) ? 0 : $cid).'/'.$skpd
);
$config['total_rows'] = count($this->Document_model->get($params_total));
$config['uri_segment'] = 9;
$this->pagination->initialize($config);
$data['main'] = 'document/document_indeks';
$data['kategori'] = $this->get_category();
$data['type'] = $this->get_type(TRUE);
$data['filter_kategori'] = $cid;
//dihidden ku urang
//$data['filter_type'] = $tid;
$data['filter_date_start'] = ($date_start == 'all') ? '' : $date_start;
$data['filter_date_end'] = ($date_end == 'all') ? '' : $date_end;
$data['filter_title'] = ($title == 'all') ? '' : $title;
$data['filter_author'] = ($skpd == 'all') ? '' : $skpd;
$param_document_berkala['tid'] = 1;
$param_document_serta_merta['tid'] = 2;
$param_document_setiap_saat['tid'] = 3;
$param_document_dikecualikan['tid'] = 4;
$data['total_record'] = count($this->Document_model->get($params_total));
$data['total_record_berkala'] = count($this->Document_model->get($param_document_berkala));
$data['total_record_serta_merta'] = count($this->Document_model->get($param_document_serta_merta));
$data['total_record_setiap_saat'] = count($this->Document_model->get($param_document_setiap_saat));
$data['total_record_dikecualikan'] = count($this->Document_model->get($param_document_dikecualikan));
$this->load->view('layout', $data);
}
Model:
public function get($params = array())
{
if(isset($params['fields']))
{
$this->db->select($params['fields']);
}
else
{
$this->db->select('*');
}
if(isset($params['id']))
{
$this->db->where('document.document_id', $params['id']);
}
elseif(isset($params['code']))
{
$this->db->where('document_code', $params['code']);
}
elseif(isset($params['date_start']) AND isset($params['date_end']))
{
$this->db->where('document_date >=', $params['date_start'].' 00:00:00');
$this->db->where('document_date <=', $params['date_end'].' 23:59:59');
}
elseif(isset($params['tid']))
{
$this->db->where('type_id', $params['tid']);
}
elseif(isset($params['cid']))
{
$this->db->where('document.category_id', $params['cid']);
}
elseif(isset($params['uid']))
{
$this->db->where('user_id', $params['uid']);
}
elseif(isset($params['sid']))
{
$this->db->where('document.skpd_id', $params['sid']);
}
if(isset($params['title']))
{
$this->db->like('document_title', $params['title']);
}
if(isset($params['author']))
{
$this->db->like('document_author', $params['author']);
}
elseif(isset($params['date']))
{
$this->db->where('document_date', $params['date']);
}
if(isset($params['dsid']))
{
$this->db->where('document_skpd_id', $params['dsid']);
}
if(isset($params['status']))
{
$this->db->where('document_is_published', $params['status']);
}
if(isset($params['document_sync']))
{
$this->db->where('document_sync', $params['document_sync']);
}
if(isset($params['sync']))
{
$this->db->reset_query();
$this->db->select('document.*');
$this->db->where('document_sync', $params['sync']);
}
if(isset($params['limit']))
{
if(!isset($params['offset']))
{
$params['offset'] = NULL;
}
$this->db->limit($params['limit'], $params['offset']);
}
if(isset($params['order_by']))
{
$this->db->order_by($params['order_by'], 'desc');
}
else
{
$this->db->order_by('document_date', 'desc');
}
$this->db->select('document.document_id');
$this->db->join('user_desktop', 'user_desktop.user_desktop_id = document.operator_id');
$this->db->join('(SELECT document_id, MAX(document_file_id) AS document_file_max_id FROM document_file GROUP BY document_id) AS document_file_max', 'document.document_id = document_file_max.document_id', 'left', FALSE);
$this->db->join('document_file', 'document_file.document_file_id = document_file_max.document_file_max_id', 'left');
$this->db->join('document_type', 'document_type.document_type_id = document.type_id');
$this->db->join('document_form', 'document_form.document_form_id = document.form_id');
$this->db->join('document_category', 'document_category.category_id = document.category_id');
$this->db->join('skpd', 'skpd.skpd_id = document.skpd_id');
$res = $this->db->get('document');
if(isset($params['id']))
{
return $res->row_array();
}
else
{
return $res->result_array();
}
}
Please master how to fix it ? whst is problem on my pagination
Please try this :
$config['base_url'] = site_url('document/index/'.
$date_start.'/'.$date_end.'/'.
$title.'/'.(empty($cid) ? 0 : $cid).'/'.$skpd.'/'
);
$config['uri_segment'] = 8;
in your base_url you missed out / at the end and codeigniter places offset for pagination. Hence, uri_segment would be 8.

Laravel : search or filter the collection

I have this issue while filtering or searching through a collection
http://laravel.io/bin/vj115 check the url for code.
What i am trying to do is filter a collection by get method (from url ofcourse)
But only it only works when Input::get('category') has value else nothing works.
Could you please check the code and let me know what need to be fixed?
Thanks.
===== Real Code just incase the link is broken in future (edited)=============
public function anyIndex() {
$id = Input::get('id');
$brand = Brand::firstOrNew(array('id' => $id));
$paginate = Misc::getSettings('admin-pagination');
$page_no = isset($_GET['page']) ? $_GET['page'] : 1;
$i = ($paginate * $page_no) - ($paginate - 1);
$appends = false;
$newBrands = new Brand;
if (Input::get('category')) {
$brandCat = BrandCategory::find(Input::get('category'));
$newBrands = $brandCat->brands();
$appends['category'] = Input::get('category');
}
if (Input::get('status')) {
$status = Input::get('status') == 'published' ? 1 : 0;
$newBrands->where('is_active', '=', $status);
$appends['status'] = Input::get('status');
}
if (Input::get('order_by') || Input::get('order')) {
if (Input::get('order_by')) {
$order_by = Input::get('order_by');
$appends['order_by'] = Input::get('order_by');
} else {
$order_by = 'name';
}
if (Input::get('order')) {
$order = Input::get('order');
$appends['order'] = Input::get('order');
} else {
$order = 'asc';
}
$order = Input::get('order') ? Input::get('order') : 'asc';
$newBrands->orderBy($order_by, $order);
}
$brands = $newBrands->paginate($paginate);
$brand_categories_list = new BrandCategory;
$selected_cats = array();
if ($id != "") {
$selected_cats = $brand->categories->lists('id');
}
return View::make('admin.brands.index')
->with(array(
'selected_cats' => $selected_cats,
'brand' => $brand,
'brands' => $brands,
'brand_categories_list' => $brand_categories_list->lists('name', 'id'),
'appends' => $appends,
'i' => $i
));
}
Thanks to Dave.. I solved it as :
public function anyIndex() {
$id = Input::get('id');
$brand = Brand::firstOrNew(array('id' => $id));
$paginate = Misc::getSettings('admin-pagination');
$page_no = isset($_GET['page']) ? $_GET['page'] : 1;
$i = ($paginate * $page_no) - ($paginate - 1);
$appends = false;
if (Input::has('category')) {
$brandCat = BrandCategory::find(Input::get('category'));
$newBrands = $brandCat->brands();
$appends['category'] = Input::get('category');
} else {
$newBrands = Brand::limit(-1);
}
if (Input::has('status')) {
$status = Input::get('status') == 'published' ? 1 : 0;
$newBrands->where('is_active', '=', $status);
$appends['status'] = Input::get('status');
}
if (Input::has('order_by') || Input::has('order')) {
if (Input::has('order_by')) {
$order_by = Input::get('order_by');
$appends['order_by'] = Input::get('order_by');
} else {
$order_by = 'name';
}
if (Input::has('order')) {
$order = Input::get('order');
$appends['order'] = Input::get('order');
} else {
$order = 'asc';
}
$order = Input::get('order') ? Input::get('order') : 'asc';
$newBrands->orderBy($order_by, $order);
}else{
$newBrands->orderBy('name', 'asc');
}
$brands = $newBrands->paginate($paginate);
/* $queries = DB::getQueryLog();
$last_query = end($queries);
dd($last_query); */
$brand_categories_list = new BrandCategory;
$selected_cats = array();
if ($id != "") {
$selected_cats = $brand->categories->lists('id');
}
return View::make('admin.brands.index')
->with(
array(
'selected_cats' => $selected_cats,
'brand' => $brand,
'brands' => $brands,
'brand_categories_list' => $brand_categories_list->lists('name', 'id'),
'appends' => $appends,
'i' => $i)
);
}
I suspect it has to do with how you are using Eloquent. You can't simply apply methods to the object if it was created using the "new" keyword.
$newBrands = new Brand;
// This won't work
$newBrands->where('is_active', '=', $status);
// This will work
$newBrands = $newBrands->where('is_active', '=', $status);
It will work if you create it statically along with a method.
$newBrands = Brand::limit(100);
// This will work
$newBrands->where('is_active', '=', $status);
Fluent (DB) works the same way.
$newBrands = DB::table('brands');
// This wil work
$newBrands->where('is_active', '=', $status);
here I am searching the username(s) based on the displayname or fullname or email. therefore, the $request->filled('name of your input') is the solution.
$usernames = (new User())->newQuery(); //where User is the model
if($request->filled('email')){
$usernames->orWhere('email',$request->email);
}
if($request->filled('full_name')){
$usernames->orWhere('full_name',$request->full_name);
} if($request->filled('display_name')){
$usernames->orWhere('display_name',$request->display_name);
}
$usernames = $usernames->pluck('username')->toArray();

Want to remove (((price_table_price.value)*1) < from the product collection

I am very new to Magento. (Indeed this is my first task). I would be very glad if you can help me on this.
I am using magento sample database and theMagento version is 1.3.2.
Local PC URL : http://magento.local/electronics/cell-phones.html?price=4,100
Class : Mage_Catalog_Block_Product_List
protected function _getProductCollection()
{
if (is_null($this->_productCollection)) {
$layer = Mage::getSingleton('catalog/layer');
/* #var $layer Mage_Catalog_Model_Layer */
if ($this->getShowRootCategory()) {
$this->setCategoryId(Mage::app()->getStore()->getRootCategoryId());
}
// if this is a product view page
if (Mage::registry('product')) {
// get collection of categories this product is associated with
$categories = Mage::registry('product')->getCategoryCollection()
->setPage(1, 1)
->load();
// if the product is associated with any category
if ($categories->count()) {
// show products from this category
$this->setCategoryId(current($categories->getIterator()));
}
}
$origCategory = null;
if ($this->getCategoryId()) {
$category = Mage::getModel('catalog/category')->load($this->getCategoryId());
if ($category->getId()) {
$origCategory = $layer->getCurrentCategory();
$layer->setCurrentCategory($category);
}
}
$this->_productCollection = $layer->getProductCollection();
$this->prepareSortableFieldsByCategory($layer->getCurrentCategory());
if ($origCategory) {
$layer->setCurrentCategory($origCategory);
}
}
return $this->_productCollection;
}
I need to remove (((price_table_price.value)*1) < 400) from the $this->_productCollection.
Can’t figure out how and when this added to the product collection. Please HELP!!!
Thanks!!!!
Since No one helped me, I figured out answer by myself.
Firstly I'll state what my task was.
Lets say that I have a products 10 in 100-200 price range, 12 in 500-600 and 1 product in 10000-20000 of X category. With the default price range of magento it display as two ranges which are 0-10000 and 10000-200000 which is not much useful for the customer.
I had to made the ranges as 100-200,500-600 and 1000<
I'll post all my code here.
When I follow other post for customizing ranges most of them have only consider display of the layered navigation. But here I have made my consideration on displaying the products when click on the final range (i.e. 1000<)
Please note that LMage is local->LMage folder and also I am a new bee for the Magento ;).
Please post here if you find a better way to do this.
class LMage_CatalogIndex_Model_Mysql4_Price extends Mage_CatalogIndex_Model_Mysql4_Price {
public function getCount($range, $attribute, $entitySelect) {
$select = clone $entitySelect;
$select->reset(Zend_Db_Select::COLUMNS);
$select->reset(Zend_Db_Select::ORDER);
$select->reset(Zend_Db_Select::LIMIT_COUNT);
$select->reset(Zend_Db_Select::LIMIT_OFFSET);
$select->join(array('price_table' => $this->getMainTable()), 'price_table.entity_id=e.entity_id', array());
$response = new Varien_Object();
$response->setAdditionalCalculations(array());
if ($attribute->getAttributeCode() == 'price') {
$select->where('price_table.customer_group_id = ?', $this->getCustomerGroupId());
$args = array(
'select' => $select,
'table' => 'price_table',
'store_id' => $this->getStoreId(),
'response_object' => $response,
);
Mage::dispatchEvent('catalogindex_prepare_price_select', $args);
}
$fields = array('count' => 'COUNT(DISTINCT price_table.entity_id)', 'range' => "FLOOR(((price_table.value" . implode('', $response->getAdditionalCalculations()) . ")*{$this->getRate()})/{$range})+1");
$select->from('', $fields)
->group('range')
->where('price_table.website_id = ?', $this->getWebsiteId())
->where('price_table.attribute_id = ?', $attribute->getId());
$result = $this->_getReadAdapter()->fetchAll($select);
$counts = array();
foreach ($result as $row) {
if ($row['range'] >= 11) {
$counts[11] = isset($counts[11])?$row['count']+$counts[11]:$row['count'];
} else {
$counts[$row['range']] = $row['count'];
}
}
return $counts;
}
public function applyFilterToCollection($collection, $attribute, $range, $index, $tableName = 'price_table') {
/**
* Distinct required for removing duplicates in case when we have grouped products
* which contain multiple rows for one product id
*/
$collection->getSelect()->distinct(true);
$tableName = $tableName . '_' . $attribute->getAttributeCode();
$collection->getSelect()->joinLeft(
array($tableName => $this->getMainTable()), $tableName . '.entity_id=e.entity_id', array()
);
$response = new Varien_Object();
$response->setAdditionalCalculations(array());
$collection->getSelect()
->where($tableName . '.website_id = ?', $this->getWebsiteId())
->where($tableName . '.attribute_id = ?', $attribute->getId());
if ($attribute->getAttributeCode() == 'price') {
$collection->getSelect()->where($tableName . '.customer_group_id = ?', $this->getCustomerGroupId());
$args = array(
'select' => $collection->getSelect(),
'table' => $tableName,
'store_id' => $this->getStoreId(),
'response_object' => $response,
);
Mage::dispatchEvent('catalogindex_prepare_price_select', $args);
}
$collection->getSelect()->where("(({$tableName}.value" . implode('', $response->getAdditionalCalculations()) . ")*{$this->getRate()}) >= ?", ($index - 1) * $range);
if($index<=10){
$collection->getSelect()->where("(({$tableName}.value" . implode('', $response->getAdditionalCalculations()) . ")*{$this->getRate()}) < ?", $index * $range);
}
return $this;
}
public function getCategoryProductPrices($attribute = null, $entitySelect) {
$select = clone $entitySelect;
$select->reset(Zend_Db_Select::COLUMNS);
$select->reset(Zend_Db_Select::ORDER);
$select->reset(Zend_Db_Select::LIMIT_COUNT);
$select->reset(Zend_Db_Select::LIMIT_OFFSET);
$response = new Varien_Object();
$response->setAdditionalCalculations(array());
$select->join(array('price_table' => $this->getMainTable()), 'price_table.entity_id=e.entity_id', array());
if ($attribute->getAttributeCode() == 'price') {
$select->where('price_table.customer_group_id = ?', $this->getCustomerGroupId());
$args = array(
'select' => $select,
'table' => 'price_table',
'store_id' => $this->getStoreId(),
'response_object' => $response,
);
Mage::dispatchEvent('catalogindex_prepare_price_select', $args);
}
$select
->from('', "(price_table.value" . implode('', $response->getAdditionalCalculations()) . ")")
->where('price_table.website_id = ?', $this->getWebsiteId())
->where('price_table.attribute_id = ?', $attribute->getId());
return $this->_getReadAdapter()->fetchAll($select);
}
}
class LMage_CatalogIndex_Model_Price extends Mage_CatalogIndex_Model_Price{
public function getCategoryProductPrices($attribute, $entityIdsFilter){
return $this->_getResource()->getCategoryProductPrices($attribute, $entityIdsFilter);
}
}
class LMage_Catalog_Model_Layer_Filter_Price extends Mage_Catalog_Model_Layer_Filter_Price {
public function getPriceRange() {
$range = $this->getData('price_range');
if (is_null($range)) {
$productsprice = $this->getCategoryProductPricesArr();
$maxPrice = $this->getMaxPriceInt();
$maxPrice = $this->getMaxPriceOfMaxOccurenceRange($productsprice, $maxPrice);
$index = 1;
do {
$range = pow(10, (strlen(floor($maxPrice)) - $index));
$items = $this->getRangeItemCounts($range);
$index++;
} while ($range > self::MIN_RANGE_POWER && count($items) < 1);
$this->setData('price_range', $range);
}
return $range;
}
public function getMaxPriceOfMaxOccurenceRange($productsprice, $maxPrice) {
$rangeArr = array();
$i = 1;
$val = 0;
do {
$val = self::MIN_RANGE_POWER * $i - 1;
$rangeArr[$val] = 0;
$i *= 10;
} while ($maxPrice > $val);
foreach ($productsprice as $value) {
$rangeArr[pow(10, strlen(floor($value['value']))) - 1]+=1;
}
return array_search(max($rangeArr), $rangeArr);
}
public function getCategoryProductPricesArr() {
$productsprice = $this->getData('products_price_arr');
if (is_null($productsprice)) {
$productsprice = Mage::getSingleton('catalogindex/price')->getCategoryProductPrices(
$this->getAttributeModel(), $this->_getBaseCollectionSql()
);
$this->setData('products_price_arr', $productsprice);
}
return $productsprice;
}
/**
* Prepare text of item label
*
* #param int $range
* #param float $value
* #return string
*/
protected function _renderItemLabel($range, $value) {
$store = Mage::app()->getStore();
if ($value > 10) {
$fromPrice = $store->formatPrice(($value - 1) * $range);
//$toPrice = $store->formatPrice($value * $range);
return Mage::helper('catalog')->__('%s < ', $fromPrice);
}
$fromPrice = $store->formatPrice(($value - 1) * $range);
$toPrice = $store->formatPrice($value * $range);
return Mage::helper('catalog')->__('%s - %s', $fromPrice, $toPrice);
}

Categories