I am getting this PHP fatal error message: "Fatal error: Class PT_Fieldtype contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (EE_Fieldtype::display_field) in /.../pt_fieldtype.php on line 148"
However, when I open the file and do a search, the word "abstract" is nowhere to be found at all. Thanks for the help!
Edit: Here's the code in question. My bad for not showing it before.
<?php if (! defined('BASEPATH')) exit('No direct script access allowed');
if (! defined('PT_FIELD_PACK_VER'))
{
// get the version from config.php
require PATH_THIRD.'pt_field_pack/config.php';
define('PT_FIELD_PACK_VER', $config['version']);
}
/**
* P&T Fieldtype Base Class
*
* #package P&T Field Pack
* #author Brandon Kelly <brandon#pixelandtonic.com>
* #copyright Copyright (c) 2010 Pixel & Tonic, LLC
*/
class PT_Fieldtype extends EE_Fieldtype {
/**
* PT_Fieldtype Constructor
*/
function PT_Fieldtype()
{
parent::EE_Fieldtype();
}
// --------------------------------------------------------------------
/**
* Options Setting
*/
function options_setting($options=array(), $indent = '')
{
$r = '';
foreach($options as $name => $label)
{
if ($r !== '') $r .= "\n";
// is this just a blank option?
if (! $name && ! $label) $name = $label = ' ';
$r .= $indent . htmlentities($name);
// is this an optgroup?
if (is_array($label)) $r .= "\n".$this->options_setting($label, $indent.' ');
else if ($name != $label) $r .= ' : '.$label;
}
return $r;
}
// --------------------------------------------------------------------
/**
* Save Options Setting
*/
function save_options_setting($options = '', $total_levels = 1)
{
// prepare options
$options = preg_split('/[\r\n]+/', $options);
foreach($options as &$option)
{
$option_parts = preg_split('/\s:\s/', $option, 2);
$option = array();
$option['indent'] = preg_match('/^\s+/', $option_parts[0], $matches) ? strlen(str_replace("\t", ' ', $matches[0])) : 0;
$option['name'] = trim($option_parts[0]);
$option['value'] = isset($option_parts[1]) ? trim($option_parts[1]) : $option['name'];
}
return $this->_structure_options($options, $total_levels);
}
/**
* Structure Options
*/
private function _structure_options(&$options, $total_levels, $level = 1, $indent = -1)
{
$r = array();
while ($options)
{
if ($indent == -1 || $options[0]['indent'] > $indent)
{
$option = array_shift($options);
$children = (! $total_levels OR $level < $total_levels)
? $this->_structure_options($options, $total_levels, $level+1, $option['indent']+1)
: FALSE;
$r[(string)$option['name']] = $children ? $children : (string)$option['value'];
}
else if ($options[0]['indent'] <= $indent)
{
break;
}
}
return $r;
}
// --------------------------------------------------------------------
/**
* Prep Iterators
*/
function prep_iterators(&$tagdata)
{
// find {switch} tags
$this->_switches = array();
$tagdata = preg_replace_callback('/'.LD.'switch\s*=\s*([\'\"])([^\1]+)\1'.RD.'/sU', array(&$this, '_get_switch_options'), $tagdata);
$this->_count_tag = 'count';
$this->_iterator_count = 0;
}
/**
* Get Switch Options
*/
function _get_switch_options($match)
{
global $FNS;
$marker = LD.'SWITCH['.$FNS->random('alpha', 8).']SWITCH'.RD;
$this->_switches[] = array('marker' => $marker, 'options' => explode('|', $match[2]));
return $marker;
}
/**
* Parse Iterators
*/
function parse_iterators(&$tagdata)
{
// {switch} tags
foreach($this->_switches as $i => $switch)
{
$option = $this->_iterator_count % count($switch['options']);
$tagdata = str_replace($switch['marker'], $switch['options'][$option], $tagdata);
}
// update the count
$this->_iterator_count++;
// {count} tags
$tagdata = $this->EE->TMPL->swap_var_single($this->_count_tag, $this->_iterator_count, $tagdata);
}
}
// ====================================================================
/**
* P&T Multi Fieldtype Base Class
*
* #package P&T Field Pack
* #author Brandon Kelly <brandon#pixelandtonic.com>
* #copyright Copyright (c) 2010 Pixel & Tonic, LLC
*/
class PT_Multi_Fieldtype extends PT_Fieldtype {
var $default_field_settings = array(
'options' => array(
'Option 1' => 'Option 1',
'Option 2' => 'Option 2',
'Option 3' => 'Option 3'
)
);
var $default_cell_settings = array(
'options' => array(
'Opt 1' => 'Opt 1',
'Opt 2' => 'Opt 2'
)
);
var $default_tag_params = array(
'sort' => '',
'backspace' => '0'
);
var $total_option_levels = 1;
// --------------------------------------------------------------------
/**
* Display Field Settings
*/
function display_settings($data)
{
// load the language file
$this->EE->lang->loadfile($this->class);
$options = isset($data['options']) ? $data['options'] : array();
$input_name = $this->class.'_options';
$this->EE->table->add_row(
lang($this->class.'_options', $input_name) . '<br />'
. lang('field_list_instructions') . '<br /><br />'
. lang('option_setting_examples'),
'<textarea id="'.$input_name.'" name="'.$input_name.'" rows="6">'.$this->options_setting($options).'</textarea>'
);
}
/**
* Display Cell Settings
*/
function display_cell_settings($data)
{
// load the language file
$this->EE->lang->loadfile($this->class);
$options = isset($data['options']) ? $data['options'] : array();
return array(
array(
lang($this->class.'_options'),
'<textarea class="matrix-textarea" name="options" rows="4">'.$this->options_setting($options).'</textarea>'
)
);
}
// --------------------------------------------------------------------
/**
* Save Field Settings
*/
function save_settings($data)
{
$post = $this->EE->input->post($this->class.'_options');
// replace quotes
$post = str_replace('"', '"', $post);
return array(
'options' => $this->save_options_setting($post, $this->total_option_levels)
);
}
/**
* Save Cell Settings
*/
function save_cell_settings($settings)
{
// replace quotes
$settings['options'] = str_replace('"', '"', $settings['options']);
$settings['options'] = $this->save_options_setting($settings['options'], $this->total_option_levels);
return $settings;
}
// --------------------------------------------------------------------
/**
* Prep Field Data
*
* Ensures $field_data is an array.
*/
function prep_field_data(&$data)
{
if (! is_array($data))
{
$data = array_filter(preg_split("/[\r\n]+/", $data));
}
}
// --------------------------------------------------------------------
/**
* Display Field
*/
function display_field($data)
{
if (is_string($data)) $data = html_entity_decode($data);
return $this->_display_field($data, $this->field_name);
}
/**
* Display Cell
*/
function display_cell($data)
{
return $this->_display_field($data, $this->cell_name);
}
// --------------------------------------------------------------------
/**
* Save
*/
function save($data)
{
// replace quotes
return str_replace('"', '"', $data);
}
/**
* Save Cell
*/
function save_cell($data)
{
// replace quotes
return $this->save($data);
}
// --------------------------------------------------------------------
/**
* Find Options
*/
private function _find_option($needle, $haystack)
{
foreach ($haystack as $key => $value)
{
$r = $value;
if ($needle == $key OR (is_array($value) AND (($r = $this->_find_option($needle, $value)) !== FALSE)))
{
return $r;
}
}
return FALSE;
}
// --------------------------------------------------------------------
/**
* Replace Tag
*/
function replace_tag($data, $params = array(), $tagdata = FALSE)
{
if (! isset($this->settings['options']) || ! $this->settings['options'])
{
return $data;
}
if (! $tagdata)
{
return $this->replace_ul($data, $params);
}
$this->prep_field_data($data);
$r = '';
if ($this->settings['options'] && $data)
{
// optional sorting
if (isset($params['sort']) && $params['sort'])
{
$sort = strtolower($params['sort']);
if ($sort == 'asc')
{
sort($data);
}
else if ($sort == 'desc')
{
rsort($data);
}
}
// offset and limit
if (isset($params['offset']) || isset($params['limit']))
{
$offset = isset($params['offset']) ? $params['offset'] : 0;
$limit = isset($params['limit']) ? $params['limit'] : count($data);
$data = array_splice($data, $offset, $limit);
}
// prepare for {switch} and {count} tags
$this->prep_iterators($tagdata);
foreach($data as $option_name)
{
if (($option = $this->_find_option($option_name, $this->settings['options'])) !== FALSE)
{
// copy $tagdata
$option_tagdata = $tagdata;
// simple var swaps
$option_tagdata = $this->EE->TMPL->swap_var_single('option', $option, $option_tagdata);
$option_tagdata = $this->EE->TMPL->swap_var_single('option_name', $option_name, $option_tagdata);
// parse {switch} and {count} tags
$this->parse_iterators($option_tagdata);
$r .= $option_tagdata;
}
}
if (isset($params['backspace']) && $params['backspace'])
{
$r = substr($r, 0, -$params['backspace']);
}
}
return $r;
}
// --------------------------------------------------------------------
/**
* Unordered List
*/
function replace_ul($data, $params = array())
{
return "<ul>\n"
. $this->replace_tag($data, $params, " <li>{option}</li>\n")
. '</ul>';
}
/**
* Ordered List
*/
function replace_ol($data, $params = array())
{
return "<ol>\n"
. $this->replace_tag($data, $params, " <li>{option}</li>\n")
. '</ol>';
}
// --------------------------------------------------------------------
/**
* All Options
*/
function replace_all_options($data, $params = array(), $tagdata = FALSE, $options = FALSE, $iterator_count = 0)
{
if (! $tagdata)
{
return "<ul>\n"
. $this->replace_all_options($data, $params, " <li>{option}</li>\n")
. "</ul>";
}
PT_Multi_Fieldtype::prep_field_data($data);
$r = '';
if ($options === FALSE)
{
$options = $this->settings['options'];
}
if ($options)
{
// optional sorting
if (isset($params['sort']) && $params['sort'])
{
$sort = strtolower($params['sort']);
if ($sort == 'asc')
{
asort($options);
}
else if ($sort == 'desc')
{
arsort($options);
}
}
// prepare for {switch} and {count} tags
$this->prep_iterators($tagdata);
$this->_iterator_count += $iterator_count;
foreach($options as $option_name => $option)
{
if (is_array($option))
{
$sub_params = array_merge($params, array('backspace' => '0'));
$r .= $this->replace_all_options($data, $sub_params, $tagdata, $option, $this->_iterator_count);
}
else
{
// copy $tagdata
$option_tagdata = $tagdata;
// simple var swaps
$option_tagdata = $this->EE->TMPL->swap_var_single('option', $option, $option_tagdata);
$option_tagdata = $this->EE->TMPL->swap_var_single('option_name', $option_name, $option_tagdata);
$option_tagdata = $this->EE->TMPL->swap_var_single('selected', (in_array($option_name, $data) ? 1 : 0), $option_tagdata);
// parse {switch} and {count} tags
$this->parse_iterators($option_tagdata);
$r .= $option_tagdata;
}
}
if (isset($params['backspace']) && $params['backspace'])
{
$r = substr($r, 0, -$params['backspace']);
}
}
return $r;
}
// --------------------------------------------------------------------
/**
* Is Selected?
*/
function replace_selected($data, $params = array())
{
$this->prep_field_data($data);
return (isset($params['option']) AND in_array($params['option'], $data)) ? 1 : 0;
}
/**
* Total Selections
*/
function replace_total_selections($data, $params = array())
{
$this->prep_field_data($data);
return $field_data ? (string) count($data) : '0';
}
}
The answer of your question is on line 148 of this file...
Maybe you are using a class with abstract methods without inheriting them that is rejected, make sure you implement all of them and after show us some code. ;-)
Related
I'm getting a PHP fatal error on a cron script used for Commission Junction. It seems in the error_log it keeps updating with
PHP Fatal error: Call to undefined method Mage_Core_Helper_Data::getEscapedCSVData() in /home/lovescen/public_html/app/code/core/Mage/Dataflow/Model/Convert/Parser/Csv.php on line 269
The code on line 269 is
$escapedValue = Mage::helper("core")->getEscapedCSVData(array($value));
And here is the entire code in Csv.php.
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license#magento.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* #category Mage
* #package Mage_Dataflow
* #copyright Copyright (c) 2006-2016 X.commerce, Inc. and affiliates (http://www.magento.com)
* #license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Convert csv parser
*
* #category Mage
* #package Mage_Dataflow
* #author Magento Core Team <core#magentocommerce.com>
*/
class Mage_Dataflow_Model_Convert_Parser_Csv extends Mage_Dataflow_Model_Convert_Parser_Abstract
{
protected $_fields;
protected $_mapfields = array();
public function parse()
{
// fixed for multibyte characters
setlocale(LC_ALL, Mage::app()->getLocale()->getLocaleCode().'.UTF-8');
$fDel = $this->getVar('delimiter', ',');
$fEnc = $this->getVar('enclose', '"');
if ($fDel == '\t') {
$fDel = "\t";
}
$adapterName = $this->getVar('adapter', null);
$adapterMethod = $this->getVar('method', 'saveRow');
if (!$adapterName || !$adapterMethod) {
$message = Mage::helper('dataflow')->__('Please declare "adapter" and "method" nodes first.');
$this->addException($message, Mage_Dataflow_Model_Convert_Exception::FATAL);
return $this;
}
try {
$adapter = Mage::getModel($adapterName);
}
catch (Exception $e) {
$message = Mage::helper('dataflow')->__('Declared adapter %s was not found.', $adapterName);
$this->addException($message, Mage_Dataflow_Model_Convert_Exception::FATAL);
return $this;
}
if (!method_exists($adapter, $adapterMethod)) {
$message = Mage::helper('dataflow')->__('Method "%s" not defined in adapter %s.', $adapterMethod, $adapterName);
$this->addException($message, Mage_Dataflow_Model_Convert_Exception::FATAL);
return $this;
}
$batchModel = $this->getBatchModel();
$batchIoAdapter = $this->getBatchModel()->getIoAdapter();
if (Mage::app()->getRequest()->getParam('files')) {
$file = Mage::app()->getConfig()->getTempVarDir().'/import/'
. urldecode(Mage::app()->getRequest()->getParam('files'));
$this->_copy($file);
}
$batchIoAdapter->open(false);
$isFieldNames = $this->getVar('fieldnames', '') == 'true' ? true : false;
if (!$isFieldNames && is_array($this->getVar('map'))) {
$fieldNames = $this->getVar('map');
}
else {
$fieldNames = array();
foreach ($batchIoAdapter->read(true, $fDel, $fEnc) as $v) {
$fieldNames[$v] = $v;
}
}
$countRows = 0;
while (($csvData = $batchIoAdapter->read(true, $fDel, $fEnc)) !== false) {
if (count($csvData) == 1 && $csvData[0] === null) {
continue;
}
$itemData = array();
$countRows ++; $i = 0;
foreach ($fieldNames as $field) {
$itemData[$field] = isset($csvData[$i]) ? $csvData[$i] : null;
$i ++;
}
$batchImportModel = $this->getBatchImportModel()
->setId(null)
->setBatchId($this->getBatchModel()->getId())
->setBatchData($itemData)
->setStatus(1)
->save();
}
$this->addException(Mage::helper('dataflow')->__('Found %d rows.', $countRows));
$this->addException(Mage::helper('dataflow')->__('Starting %s :: %s', $adapterName, $adapterMethod));
$batchModel->setParams($this->getVars())
->setAdapter($adapterName)
->save();
//$adapter->$adapterMethod();
return $this;
// // fix for field mapping
// if ($mapfields = $this->getProfile()->getDataflowProfile()) {
// $this->_mapfields = array_values($mapfields['gui_data']['map'][$mapfields['entity_type']]['db']);
// } // end
//
// if (!$this->getVar('fieldnames') && !$this->_mapfields) {
// $this->addException('Please define field mapping', Mage_Dataflow_Model_Convert_Exception::FATAL);
// return;
// }
//
// if ($this->getVar('adapter') && $this->getVar('method')) {
// $adapter = Mage::getModel($this->getVar('adapter'));
// }
//
// $i = 0;
// while (($line = fgetcsv($fh, null, $fDel, $fEnc)) !== FALSE) {
// $row = $this->parseRow($i, $line);
//
// if (!$this->getVar('fieldnames') && $i == 0 && $row) {
// $i = 1;
// }
//
// if ($row) {
// $loadMethod = $this->getVar('method');
// $adapter->$loadMethod(compact('i', 'row'));
// }
// $i++;
// }
//
// return $this;
}
public function parseRow($i, $line)
{
if (sizeof($line) == 1) return false;
if (0==$i) {
if ($this->getVar('fieldnames')) {
$this->_fields = $line;
return;
} else {
foreach ($line as $j=>$f) {
$this->_fields[$j] = $this->_mapfields[$j];
}
}
}
$resultRow = array();
foreach ($this->_fields as $j=>$f) {
$resultRow[$f] = isset($line[$j]) ? $line[$j] : '';
}
return $resultRow;
}
/**
* Read data collection and write to temporary file
*
* #return Mage_Dataflow_Model_Convert_Parser_Csv
*/
public function unparse()
{
$batchExport = $this->getBatchExportModel()
->setBatchId($this->getBatchModel()->getId());
$fieldList = $this->getBatchModel()->getFieldList();
$batchExportIds = $batchExport->getIdCollection();
$io = $this->getBatchModel()->getIoAdapter();
$io->open();
if (!$batchExportIds) {
$io->write("");
$io->close();
return $this;
}
if ($this->getVar('fieldnames')) {
$csvData = $this->getCsvString($fieldList);
$io->write($csvData);
}
foreach ($batchExportIds as $batchExportId) {
$csvData = array();
$batchExport->load($batchExportId);
$row = $batchExport->getBatchData();
foreach ($fieldList as $field) {
$csvData[] = isset($row[$field]) ? $row[$field] : '';
}
$csvData = $this->getCsvString($csvData);
$io->write($csvData);
}
$io->close();
return $this;
}
public function unparseRow($args)
{
$i = $args['i'];
$row = $args['row'];
$fDel = $this->getVar('delimiter', ',');
$fEnc = $this->getVar('enclose', '"');
$fEsc = $this->getVar('escape', '\\');
$lDel = "\r\n";
if ($fDel == '\t') {
$fDel = "\t";
}
$line = array();
foreach ($this->_fields as $f) {
$v = isset($row[$f]) ? str_replace(array('"', '\\'), array($fEnc.'"', $fEsc.'\\'), $row[$f]) : '';
$line[] = $fEnc.$v.$fEnc;
}
return join($fDel, $line);
}
/**
* Retrieve csv string from array
*
* #param array $fields
* #return string
*/
public function getCsvString($fields = array()) {
$delimiter = $this->getVar('delimiter', ',');
$enclosure = $this->getVar('enclose', '');
$escapeChar = $this->getVar('escape', '\\');
if ($delimiter == '\t') {
$delimiter = "\t";
}
$str = '';
foreach ($fields as $value) {
$escapedValue = Mage::helper("core")->getEscapedCSVData(array($value));
$value = $escapedValue[0];
if (strpos($value, $delimiter) !== false ||
empty($enclosure) ||
strpos($value, $enclosure) !== false ||
strpos($value, "\n") !== false ||
strpos($value, "\r") !== false ||
strpos($value, "\t") !== false ||
strpos($value, ' ') !== false) {
$str2 = $enclosure;
$escaped = 0;
$len = strlen($value);
for ($i=0;$i<$len;$i++) {
if ($value[$i] == $escapeChar) {
$escaped = 1;
} else if (!$escaped && $value[$i] == $enclosure) {
$str2 .= $enclosure;
} else {
$escaped = 0;
}
$str2 .= $value[$i];
}
$str2 .= $enclosure;
$str .= $str2.$delimiter;
} else {
$str .= $enclosure.$value.$enclosure.$delimiter;
}
}
return substr($str, 0, -1) . "\n";
}
}
Not sure how to fix this problem. If I could get some help I'd really appreciate it.
Thanks
UPDATE
Here is the code from my app/code/core/Mage/Core/Helper/Data.php file: http://pastie.org/10815259
Does the file app/code/core/Mage/Core/Helper/Data.php have the getEscapedCSVData function in it?
It appears that this function is added by SUPEE-7405. Have you patched your store with this SUPEE?
In my case some previous programer have copy the file
from core
\app\code\core\Mage\Core\Helper\Data.php
to local
app\code\local\Mage\Core\Helper\Data.php
and then apply SUPE PATCH 7405...
it cause that all modifications made by SUPE in data.php where rewrite by the old ones in local folder...
Solution: copy the new data.php to local or made a extension of class (better solution)
I've been searching around for extensions of CodeIgniter's parser class that would add the use of conditional statements in the view files. The problem is that the location that I've found it at doesn't offer any explanation on how to use it and doesn't list anything about the file's author. Could anyone perhaps share any thoughts on this code?
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 4.3.2 or newer
*
* #package CodeIgniter
* #author ExpressionEngine Dev Team
* #copyright Copyright (c) 2008, EllisLab, Inc.
* #license http://codeigniter.com/user_guide/license.html
* #link http://codeigniter.com
* #since Version 1.0
* #filesource
*/
// ------------------------------------------------------------------------
/**
* MY Parser Class
*
* #package CodeIgniter
* #subpackage Libraries
* #category Parser
* #author Haloweb Ltd
*/
class MY_Parser extends CI_Parser {
/**
* Parse a template
*
* Parses pseudo-variables contained in the specified template,
* replacing them with the data in the second param
*
* #access public
* #param string
* #param array
* #param bool
* #return string
*/
function parse($template, $data, $return = FALSE, $include = FALSE)
{
$CI =& get_instance();
if ($template == '')
{
return FALSE;
}
if ($include === FALSE)
{
$template = $CI->load->view($template, $data, TRUE);
}
if (isset($data) && $data != '')
{
foreach ($data as $key => $val)
{
if (is_array($val))
{
$template = $this->_parse_pair($key, $val, $template);
}
else
{
$template = $this->_parse_single($key, (string)$val, $template);
}
}
}
// Check for conditional statments
$template = $this->conditionals($template, $data);
// populate form tags
preg_match_all('/{form:(.+)}/i', $template, $posts);
if ($posts)
{
foreach ($posts[1] as $post => $value)
{
if ($postValue = $CI->input->post($value))
{
$template = str_replace('{form:'.$value.'}', $postValue, $template);
}
else
{
$template = str_replace('{form:'.$value.'}', '', $template);
}
}
}
//$template = preg_replace('/{(.+)}/i', '', $template);
if ($return == FALSE)
{
$CI->output->append_output($template);
}
return $template;
}
// --------------------------------------------------------------------
/**
* Parse conditional statments
*
* #access public
* #param string
* #param bool
* #return string
*/
function conditionals($template, $data)
{
if (preg_match_all('/'.$this->l_delim.'if (.+)'.$this->r_delim.'(.+)'.$this->l_delim.'\/if'.$this->r_delim.'/siU', $template, $conditionals, PREG_SET_ORDER))
{
if (count($conditionals) > 0)
{
// filter through conditionals
foreach($conditionals as $condition)
{
// get conditional and the string inside
$code = (isset($condition[0])) ? $condition[0] : FALSE;
$condString = (isset($condition[1])) ? str_replace(' ', '', $condition[1]) : FALSE;
$insert = (isset($condition[2])) ? $condition[2] : '';
// check code is valid
if (!preg_match('/('.$this->l_delim.'|'.$this->r_delim.')/', $condString, $condProblem))
{
if (!empty($code) || $condString != FALSE || !empty($insert))
{
if (preg_match("/^!(.*)$/", $condString, $matches))
{
$condVar = (#!$data[trim($matches[1])]) ? 0 : $data[trim($matches[1])];
#$result = (!$condVar) ? TRUE : FALSE;
}
elseif (preg_match("/([a-z0-9\-_:\(\)]+)(\!=|=|==|>|<)([a-z0-9\-_\/]+)/", $condString, $matches))
{
$condVar = (#!$data[$matches[1]]) ? 0 : $data[trim($matches[1])];
if ($matches[2] == '==' || $matches[2] == '=')
{
#$result = ($condVar === $matches[3]) ? TRUE : FALSE;
}
elseif ($matches[2] == '!=')
{
#$result = ($condVar !== $matches[3]) ? TRUE : FALSE;
}
elseif ($matches[2] == '>')
{
#$result = ($condVar > $matches[3]) ? TRUE : FALSE;
}
elseif ($matches[2] == '<')
{
#$result = ($condVar < $matches[3]) ? TRUE : FALSE;
}
}
else
{
// if the variable is set
if (isset($data[$condString]) && is_array($data[$condString]))
{
$result = (count($data[$condString]) > 0) ? TRUE : FALSE;
}
else
{
$result = (isset($data[$condString]) && $data[$condString] != '') ? TRUE : FALSE;
}
}
// filter for else
$insert = preg_split('/'.$this->l_delim.'else'.$this->r_delim.'/siU', $insert);
if ($result == TRUE)
{
// show the string inside
$template = str_replace($code, $insert[0], $template);
}
else
{
if (is_array($insert))
{
$insert = (isset($insert[1])) ? $insert[1] : '';
$template = str_replace($code, $insert, $template);
}
else
{
$template = str_replace($code, '', $template);
}
}
}
}
else
{
// remove any conditionals we cant process
$template = str_replace($code, '', $template);
}
}
}
//print_r($conditionals);
}
return $template;
}
// --------------------------------------------------------------------
/**
* Matches a variable pair
*
* #access private
* #param string
* #param string
* #return mixed
*/
function _match_pair($string, $variable)
{
$variable = str_replace('(', '\(', $variable);
$variable = str_replace(')', '\)', $variable);
if ( ! preg_match("|".$this->l_delim . $variable . $this->r_delim."(.+?)".$this->l_delim . '/' . $variable . $this->r_delim."|s", $string, $match))
{
return FALSE;
}
return $match;
}
}
In my-theme/template/catalog/navigation/left.phtml here is code for listing of all categories and its respective sub-categories and its working correctly. Here is code of left.phtml file
<?php $_menu = $this->renderCategoriesMenuHtml(0,'level-top') ?>
<?php if($_menu): ?>
<ul ><?php echo $_menu ?>
<ul>
<?php endif ?>
I found renderCategoriesMenuHtml() function in app / code / core / Mage / Catalog / Block/navigation.php here is code of navigation.php file
class Mage_Catalog_Block_Navigation extends Mage_Core_Block_Template
{
protected $_categoryInstance = null;
/**
* Current category key
*
* #var string
*/
protected $_currentCategoryKey;
/**
* Array of level position counters
*
* #var array
*/
protected $_itemLevelPositions = array();
protected function _construct()
{
$this->addData(array(
'cache_lifetime' => false,
'cache_tags' => array(Mage_Catalog_Model_Category::CACHE_TAG, Mage_Core_Model_Store_Group::CACHE_TAG),
));
}
/**
* Get Key pieces for caching block content
*
* #return array
*/
public function getCacheKeyInfo()
{
$shortCacheId = array(
'CATALOG_NAVIGATION',
Mage::app()->getStore()->getId(),
Mage::getDesign()->getPackageName(),
Mage::getDesign()->getTheme('template'),
Mage::getSingleton('customer/session')->getCustomerGroupId(),
'template' => $this->getTemplate(),
'name' => $this->getNameInLayout(),
$this->getCurrenCategoryKey()
);
$cacheId = $shortCacheId;
$shortCacheId = array_values($shortCacheId);
$shortCacheId = implode('|', $shortCacheId);
$shortCacheId = md5($shortCacheId);
$cacheId['category_path'] = $this->getCurrenCategoryKey();
$cacheId['short_cache_id'] = $shortCacheId;
return $cacheId;
}
/**
* Get current category key
*
* #return mixed
*/
public function getCurrenCategoryKey()
{
if (!$this->_currentCategoryKey) {
$category = Mage::registry('current_category');
if ($category) {
$this->_currentCategoryKey = $category->getPath();
} else {
$this->_currentCategoryKey = Mage::app()->getStore()->getRootCategoryId();
}
}
return $this->_currentCategoryKey;
}
/**
* Get catagories of current store
*
* #return Varien_Data_Tree_Node_Collection
*/
public function getStoreCategories()
{
$helper = Mage::helper('catalog/category');
return $helper->getStoreCategories();
}
/**
* Retrieve child categories of current category
*
* #return Varien_Data_Tree_Node_Collection
*/
public function getCurrentChildCategories()
{
$layer = Mage::getSingleton('catalog/layer');
$category = $layer->getCurrentCategory();
/* #var $category Mage_Catalog_Model_Category */
$categories = $category->getChildrenCategories();
$productCollection = Mage::getResourceModel('catalog/product_collection');
$layer->prepareProductCollection($productCollection);
$productCollection->addCountToCategories($categories);
return $categories;
}
/**
* Checkin activity of category
*
* #param Varien_Object $category
* #return bool
*/
public function isCategoryActive($category)
{
if ($this->getCurrentCategory()) {
return in_array($category->getId(), $this->getCurrentCategory()->getPathIds());
}
return false;
}
protected function _getCategoryInstance()
{
if (is_null($this->_categoryInstance)) {
$this->_categoryInstance = Mage::getModel('catalog/category');
}
return $this->_categoryInstance;
}
/**
* Get url for category data
*
* #param Mage_Catalog_Model_Category $category
* #return string
*/
public function getCategoryUrl($category)
{
if ($category instanceof Mage_Catalog_Model_Category) {
$url = $category->getUrl();
} else {
$url = $this->_getCategoryInstance()
->setData($category->getData())
->getUrl();
}
return $url;
}
/**
* Return item position representation in menu tree
*
* #param int $level
* #return string
*/
protected function _getItemPosition($level)
{
if ($level == 0) {
$zeroLevelPosition = isset($this->_itemLevelPositions[$level]) ? $this->_itemLevelPositions[$level] + 1 : 1;
$this->_itemLevelPositions = array();
$this->_itemLevelPositions[$level] = $zeroLevelPosition;
} elseif (isset($this->_itemLevelPositions[$level])) {
$this->_itemLevelPositions[$level]++;
} else {
$this->_itemLevelPositions[$level] = 1;
}
$position = array();
for($i = 0; $i <= $level; $i++) {
if (isset($this->_itemLevelPositions[$i])) {
$position[] = $this->_itemLevelPositions[$i];
}
}
return implode('-', $position);
}
/**
* Render category to html
*
* #param Mage_Catalog_Model_Category $category
* #param int Nesting level number
* #param boolean Whether ot not this item is last, affects list item class
* #param boolean Whether ot not this item is first, affects list item class
* #param boolean Whether ot not this item is outermost, affects list item class
* #param string Extra class of outermost list items
* #param string If specified wraps children list in div with this class
* #param boolean Whether ot not to add on* attributes to list item
* #return string
*/
protected function _renderCategoryMenuItemHtml($category, $level = 0, $isLast = false, $isFirst = false,
$isOutermost = false, $outermostItemClass = '', $childrenWrapClass = '', $noEventAttributes = false)
{
if (!$category->getIsActive()) {
return '';
}
$html = array();
// get all children
if (Mage::helper('catalog/category_flat')->isEnabled()) {
$children = (array)$category->getChildrenNodes();
$childrenCount = count($children);
} else {
$children = $category->getChildren();
$childrenCount = $children->count();
}
$hasChildren = ($children && $childrenCount);
// select active children
$activeChildren = array();
foreach ($children as $child) {
if ($child->getIsActive()) {
$activeChildren[] = $child;
}
}
$activeChildrenCount = count($activeChildren);
$hasActiveChildren = ($activeChildrenCount > 0);
// prepare list item html classes
$classes = array();
$classes[] = 'level' . $level;
$classes[] = 'nav-' . $this->_getItemPosition($level);
if ($this->isCategoryActive($category)) {
$classes[] = 'active';
}
$linkClass = '';
if ($isOutermost && $outermostItemClass) {
$classes[] = $outermostItemClass;
$linkClass = ' class="'.$outermostItemClass.'"';
}
if ($isFirst) {
$classes[] = 'first';
}
if ($isLast) {
$classes[] = 'last';
}
if ($hasActiveChildren) {
$classes[] = 'parent';
}
// prepare list item attributes
$attributes = array();
if (count($classes) > 0) {
$attributes['class'] = implode(' ', $classes);
}
if ($hasActiveChildren && !$noEventAttributes) {
$attributes['onmouseover'] = 'toggleMenu(this,1)';
$attributes['onmouseout'] = 'toggleMenu(this,0)';
}
// assemble list item with attributes
$htmlLi = '<li';
foreach ($attributes as $attrName => $attrValue) {
$htmlLi .= ' ' . $attrName . '="' . str_replace('"', '\"', $attrValue) . '"';
}
$htmlLi .= '>';
$html[] = $htmlLi;
$html[] = '<a href="'.$this->getCategoryUrl($category).'"'.$linkClass.'>';
$html[] = '<span>' . $this->escapeHtml($category->getName()) . '</span>';
$html[] = '</a>';
// render children
$htmlChildren = '';
$j = 0;
foreach ($activeChildren as $child) {
$htmlChildren .= $this->_renderCategoryMenuItemHtml(
$child,
($level + 1),
($j == $activeChildrenCount - 1),
($j == 0),
false,
$outermostItemClass,
$childrenWrapClass,
$noEventAttributes
);
$j++;
}
if (!empty($htmlChildren)) {
if ($childrenWrapClass) {
$html[] = '<div class="' . $childrenWrapClass . '">';
}
$html[] = '<ul class="level' . $level . '">';
$html[] = $htmlChildren;
$html[] = '</ul>';
if ($childrenWrapClass) {
$html[] = '</div>';
}
}
$html[] = '</li>';
$html = implode("\n", $html);
return $html;
}
/**
* Render category to html
*
* #deprecated deprecated after 1.4
* #param Mage_Catalog_Model_Category $category
* #param int Nesting level number
* #param boolean Whether ot not this item is last, affects list item class
* #return string
*/
public function drawItem($category, $level = 0, $last = false)
{
return $this->_renderCategoryMenuItemHtml($category, $level, $last);
}
/**
* Enter description here...
*
* #return Mage_Catalog_Model_Category
*/
public function getCurrentCategory()
{
if (Mage::getSingleton('catalog/layer')) {
return Mage::getSingleton('catalog/layer')->getCurrentCategory();
}
return false;
}
/**
* Enter description here...
*
* #return string
*/
public function getCurrentCategoryPath()
{
if ($this->getCurrentCategory()) {
return explode(',', $this->getCurrentCategory()->getPathInStore());
}
return array();
}
/**
* Enter description here...
*
* #param Mage_Catalog_Model_Category $category
* #return string
*/
public function drawOpenCategoryItem($category) {
$html = '';
if (!$category->getIsActive()) {
return $html;
}
$html.= '<li';
if ($this->isCategoryActive($category)) {
$html.= ' class="active"';
}
$html.= '>'."\n";
$html.= '<span>'.$this->htmlEscape($category->getName()).'</span>'."\n";
if (in_array($category->getId(), $this->getCurrentCategoryPath())){
$children = $category->getChildren();
$hasChildren = $children && $children->count();
if ($hasChildren) {
$htmlChildren = '';
foreach ($children as $child) {
$htmlChildren.= $this->drawOpenCategoryItem($child);
}
if (!empty($htmlChildren)) {
$html.= '<ul>'."\n"
.$htmlChildren
.'</ul>';
}
}
}
$html.= '</li>'."\n";
return $html;
}
/**
* Render categories menu in HTML
*
* #param int Level number for list item class to start from
* #param string Extra class of outermost list items
* #param string If specified wraps children list in div with this class
* #return string
*/
public function renderCategoriesMenuHtml($level = 0, $outermostItemClass = '', $childrenWrapClass = '')
{
$activeCategories = array();
foreach ($this->getStoreCategories() as $child) {
if ($child->getIsActive()) {
$activeCategories[] = $child;
}
}
$activeCategoriesCount = count($activeCategories);
$hasActiveCategoriesCount = ($activeCategoriesCount > 0);
if (!$hasActiveCategoriesCount) {
return '';
}
$html = '';
$j = 0;
foreach ($activeCategories as $category) {
$html .= $this->_renderCategoryMenuItemHtml(
$category,
$level,
($j == $activeCategoriesCount - 1),
($j == 0),
true,
$outermostItemClass,
$childrenWrapClass,
true
);
$j++;
}
return $html;
}
}
Now. I have created a new file template to list all categories and its subcategories at location my-theme/template/catalog/navigation/all_cat.phtml and I pasted the code of left.phtml file into all_cat.phtml file.
But when I'm executing this file on fronted I could not see any such categories and subcategories in all_cat.phtml file. I dont know what I'm missing and How to correct it. So please someone help me to find it out !
Please try this
{{block type="catalog/navigation" name="catalog.nav" template="catalog/navigation/all_cat.phtml"}}
I am having trouble find the problem in figuring out the problem using merchant-sdk-php I found on github. For some reason its throwing this error. I tried looking at the code but I dont under stand it or see the problem.
Fatal error: Call to undefined method stdClass::toXMLString() in /home/content/08/10639508/html/wp-content/plugins/donation-manager/library/vendor/paypal/paypal-sdk-core-php-bc7822a/lib/PPXmlMessage.php on line 89
<?php
/**
* #author
*/
abstract class PPXmlMessage
{
/**
* #return string
*/
public function toSOAP()
{
return $this->toXMLString();
}
/**
* #return string
*/
public function toXMLString()
{
if (count($properties = get_object_vars($this)) >= 2 && array_key_exists('value', $properties)) {
$attributes = array();
foreach (array_keys($properties) as $property) {
if ($property === 'value') continue;
if (($annots = PPUtils::propertyAnnotations($this, $property)) && isset($annots['attribute'])) {
if (($propertyValue = $this->{$property}) === NULL || $propertyValue == NULL) {
$attributes[] = NULL;
continue;
}
$attributes[] = $property . '="' . PPUtils::escapeInvalidXmlCharsRegex($propertyValue) . '"';
}
}
if (count($attributes)) {
return implode(' ', $attributes) . '>' . PPUtils::escapeInvalidXmlCharsRegex($this->value);
}
}
$xml = array();
foreach ($properties as $property => $defaultValue) {
if (($propertyValue = $this->{$property}) === NULL || $propertyValue == NULL) {
continue;
}
if (is_array($defaultValue) || is_array($propertyValue)) {
foreach ($propertyValue as $item) {
if (!is_object($item)) {
$xml[] = $this->buildProperty($property, $item);
}else{
$xml[] = $this->buildProperty($property, $item);
}
}
} else {
$xml[] = $this->buildProperty($property, $propertyValue);
}
}
return implode($xml);
}
/**
* #param string $property
* #param PPXmlMessage|string $value
* #param string $namespace
* #return string
*/
private function buildProperty($property, $value, $namespace = 'ebl')
{
$annotations = PPUtils::propertyAnnotations($this, $property);
if (!empty($annotations['namespace'])) {
$namespace = $annotations['namespace'];
}
if (!empty($annotations['name'])) {
$property = $annotations['name'];
}
$el = '<' . $namespace . ':' . $property;
if (!is_object($value)) {
$el .= '>' . PPUtils::escapeInvalidXmlCharsRegex($value);
} else {
if (substr($value = $value->toXMLString(), 0, 1) === '<' || $value=='') {
$el .= '>' . $value;
} else {
$el .= ' ' . $value;
}
}
return $el . '</' . $namespace . ':' . $property . '>';
}
/**
* #param array $map
* #param string $prefix
*/
public function init(array $map = array(), $prefix = '')
{
if (empty($map)) {
return;
}
if (($first = reset($map)) && !is_array($first) && !is_numeric(key($map))) {
parent::init($map, $prefix);
return;
}
$propertiesMap = PPUtils::objectProperties($this);
$arrayCtr = array();
foreach ($map as $element) {
if (empty($element) || empty($element['name'])) {
continue;
} elseif (!array_key_exists($property = strtolower($element['name']), $propertiesMap)) {
if (!preg_match('~^(.+)[\[\(](\d+)[\]\)]$~', $property, $m)) {
continue;
}
$element['name'] = $m[1];
$element['num'] = $m[2];
}
$element['name'] = $propertiesMap[strtolower($element['name'])];
if(PPUtils::isPropertyArray($this, $element['name'])) {
$arrayCtr[$element['name']] = isset($arrayCtr[$element['name']]) ? ($arrayCtr[$element['name']]+1) : 0;
$element['num'] = $arrayCtr[$element['name']];
}
if (!empty($element["attributes"]) && is_array($element["attributes"])) {
foreach ($element["attributes"] as $key => $val) {
$element["children"][] = array(
'name' => $key,
'text' => $val,
);
}
if (isset($element['text'])) {
$element["children"][] = array(
'name' => 'value',
'text' => $element['text'],
);
}
$this->fillRelation($element['name'], $element);
} elseif (!empty($element['text'])) {
$this->{$element['name']} = $element['text'];
} elseif (!empty($element["children"]) && is_array($element["children"])) {
$this->fillRelation($element['name'], $element);
}
}
}
/**
* #param string $property
* #param array $element
*/
private function fillRelation($property, array $element)
{
if (!class_exists($type = PPUtils::propertyType($this, $property))) {
trigger_error("Class $type not found.", E_USER_NOTICE);
return; // just ignore
}
if (isset($element['num'])) { // array of objects
$this->{$property}[$element['num']] = $item = new $type();
$item->init($element['children']);
} else {
$this->{$property} = new $type();
$this->{$property}->init($element["children"]);
}
}
}
I had this exact same error (with my live application - it worked fine in my test code). I eventually realized that, when I copied over my test code into the live environment and changed my credentials and URLs from the sandbox ones to the live ones ... I somehow deleted a line of code initializing a PaymentDetailsType object before calling SetExpressCheckout. So this error seemed pretty unrelated, but it was just a problem with setting up the objects before making the call to PayPal.
Perchance are you using json_encode/decode on your PaymentDetail record? It seems that PayPal is very particular about the component classes; stdClass (which json_decode generates) won't cut it. Serialize works, but there are warnings about using it.
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);
}