October CMS datetime picker has a max date of 2020 - laravel

I am trying to add an event using proevent in October CMS and the date-picker has a default range from 2010 to 2020 and I cannot change this option. When I inspect the HTML I see the below code:
<div id="Multidate-formMultidate-multidate" class="multidate" data-control="datepicker" data-show-time="false" data-min-date="2000-01-01" data-max-date="2020-12-31" data-disposable="">
Here is an image of the date-picker:
Below is the back-end builder which somehow is displaying that the widget is unknown by saying Unknown control type:multi-date:
When I edit that to see what will happen nothing changes. I also tried setting the maxDate and minDate dates by modifying the Datepicker class in the formwidgets to set the min and max dates but nothing is happening as well. Below is the datepicker class:
<?php namespace Backend\FormWidgets;
use Carbon\Carbon;
use Backend\Classes\FormField;
use Backend\Classes\FormWidgetBase;
use System\Helpers\DateTime as DateTimeHelper;
/**
* Date picker
* Renders a date picker field.
*
* #package october\backend
* #author Alexey Bobkov, Samuel Georges
*/
class DatePicker extends FormWidgetBase
{
//
// Configurable properties
//
/**
* #var bool Display mode: datetime, date, time.
*/
public $mode = 'datetime';
/**
* #var string Provide an explicit date display format.
*/
public $format = null;
/**
* #var string the minimum/earliest date that can be selected.
* eg: 2000-01-01
*/
public $minDate = null;
/**
* #var string the maximum/latest date that can be selected.
* eg: 2020-12-31
*/
public $maxDate = null;
/**
* #var string number of years either side or array of upper/lower range
* eg: 10 or [1900,1999]
*/
public $yearRange = 50;
/**
* #var int first day of the week
* eg: 0 (Sunday), 1 (Monday), 2 (Tuesday), etc.
*/
public $firstDay = 0;
/**
* #var bool show week numbers at head of row
*/
public $showWeekNumber = false;
/**
* #var bool change datetime exactly as is in database
*/
public $ignoreTimezone = false;
//
// Object properties
//
/**
* #inheritDoc
*/
protected $defaultAlias = 'datepicker';
/**
* #inheritDoc
*/
public function init()
{
$this->fillFromConfig([
'format',
'mode',
'minDate',
'maxDate',
'yearRange',
'firstDay',
'showWeekNumber',
'ignoreTimezone',
]);
$this->mode = strtolower($this->mode);
if ($this->minDate !== null) {
$this->minDate = is_integer($this->minDate)
? Carbon::createFromTimestamp($this->minDate)
: Carbon::parse($this->minDate);
}
if ($this->maxDate !== null) {
$this->maxDate = is_integer($this->maxDate)
? Carbon::createFromTimestamp($this->maxDate)
: Carbon::parse($this->maxDate);
}
}
/**
* #inheritDoc
*/
public function render()
{
$this->prepareVars();
return $this->makePartial('datepicker');
}
/**
* Prepares the list data
*/
public function prepareVars()
{
if ($value = $this->getLoadValue()) {
$value = DateTimeHelper::makeCarbon($value, false);
$value = $value instanceof Carbon ? $value->toDateTimeString() : $value;
}
$this->vars['name'] = $this->getFieldName();
$this->vars['value'] = $value ?: '';
$this->vars['field'] = $this->formField;
$this->vars['mode'] = $this->mode;
$this->vars['minDate'] = $this->minDate;
$this->vars['maxDate'] = $this->maxDate;
$this->vars['yearRange'] = $this->yearRange;
$this->vars['firstDay'] = $this->firstDay;
$this->vars['showWeekNumber'] = $this->showWeekNumber;
$this->vars['ignoreTimezone'] = $this->ignoreTimezone;
$this->vars['format'] = $this->format;
$this->vars['formatMoment'] = $this->getDateFormatMoment();
$this->vars['formatAlias'] = $this->getDateFormatAlias();
}
/**
* #inheritDoc
*/
public function getSaveValue($value)
{
if ($this->formField->disabled || $this->formField->hidden) {
return FormField::NO_SAVE_DATA;
}
if (!strlen($value)) {
return null;
}
return $value;
}
/**
* Convert PHP format to JS format
*/
protected function getDateFormatMoment()
{
if ($this->format) {
return DateTimeHelper::momentFormat($this->format);
}
}
/*
* Display alias, used by preview mode
*/
protected function getDateFormatAlias()
{
if ($this->format) {
return null;
}
if ($this->mode == 'time') {
return 'time';
}
elseif ($this->mode == 'date') {
return 'dateLong';
}
else {
return 'dateTimeLong';
}
}
}
Below is my datepicker html page:
<?php if ($this->previewMode): ?>
<div class="form-control"><?= Backend::dateTime($value, [
'format' => $format,
'formatAlias' => $formatAlias,
'defaultValue' => $value
]) ?></div>
<div
id="<?= $this->getId() ?>"
class="field-datepicker"
data-control="datepicker"
<?php if ($formatMoment): ?>data-format="<?= $formatMoment ?>"<?php endif ?>
<?php if ($minDate): ?>data-min-date="<?= $minDate ?>"<?php endif ?>
<?php if ($maxDate): ?>data-max-date="<?= $maxDate ?>"<?php endif ?>
<?php if ($yearRange): ?>data-year-range="<?= $yearRange ?>"<?php endif ?>
<?php if ($firstDay): ?>data-first-day="<?= $firstDay ?>"<?php endif ?>
data-show-week-number="<?= $showWeekNumber ?>"
<?php if ($ignoreTimezone): ?>data-ignore-timezone<?php endif ?>
>
<?php if ($mode == 'date'): ?>
<?= $this->makePartial('picker_date') ?>
<?php elseif ($mode == 'datetime'): ?>
<div class="row">
<div class="col-md-6">
<?= $this->makePartial('picker_date') ?>
</div>
<div class="col-md-6">
<?= $this->makePartial('picker_time') ?>
</div>
</div>
<?php elseif ($mode == 'time'): ?>
<?= $this->makePartial('picker_time') ?>
<?php endif ?>
<!-- Data locker -->
<input
type="hidden"
name="<?= $field->getName() ?>"
id="<?= $field->getId() ?>"
value="<?= e($value) ?>"
data-datetime-value
/>
</div>
Is there anything I am doing wrong or i can change to fix this issue? I have been handed this project and the previous developer did not document this well.

I directly edited the view by going inside the plugin itself and removed the maxdate php code and set it to blank. The directory was plugins/radiantweb/proevents/modules/backend/formwidgets/multidate/partils/_multidate.htm. That fixed the problem and now date has no Max and I can also set directly the Max and Min dates accordingly. The view looks like below:
<div
id="<?= $this->getId() ?>"
class="multidate"
data-control="datepicker"
data-show-time="<?= $showTime ? 'true' : 'false' ?>"
data-min-date="<?= $minDate ?>"
data-max-date=""
>
<input
type="text"
class="multidate-picker form-control align-left input-small"
autocomplete="off"
data-datepicker
/>
<input
type="hidden"
id="<?= $this->getId('input') ?>"
name="<?= $name ?>[date][]"
value="<?= $value['date'][0] ?>"
data-datetime-value
/>
<?php if ($this->mode != 'date'): ?>
<input
type="text"
id="<?= $this->getId('input') ?>-sttime"
name="<?= $name ?>[sttime][]"
value="<?= $value['sttime'][0] ?>"
class="form-control align-left timepicker"
/>
<input
type="text"
id="<?= $this->getId('input') ?>-entime"
name="<?= $name ?>[entime][]"
value="<?= $value['entime'][0] ?>"
class="form-control align-left timepicker"
/>
<?php endif ?>
<i class="icon-trash-o"></i>
</div>

Related

Redirect customer to product page from where customer logged in to website Magento 2

In Magento 2, I have a custom login form in Header.
If a customer is on the product page for eg :
http://www.testwebsite.com/catalog/product/view/id/10
and login from header form then customer should redirect to the same product page instead of Customer Dashboard.
I have tried plugin code from this link.
Below is my custom header form code -
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->get('Magento\Customer\Model\Session');
$urlInterface = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Framework\UrlInterface');
$currenturl = $urlInterface->getCurrentUrl();
if(!$customerSession->isLoggedIn()) {?>
<div class="header-login-main">
<form action="<?php echo $this->getUrl('customer/account/loginPost');?>" method="post" id="login-form" novalidate="novalidate">
<input name="form_key" value="" type="hidden">
<div class="header-login" style="">
<span>Email</span>
<input name="login[username]" id="email" class="input-text" title="Email" data-validate="{required:true, 'validate-email':true}" aria-required="true" type="email">
</div>
<div class="header-login">
<span>Password</span>
<input name="login[password]" id="pass" class="input-text" title="Password" data-validate="{required:true}" aria-required="true" type="password">
</div>
<div class="header-login1">
<button type="submit" class="action login primary" name="send" id="send2"><span>Login</span>
</div>
</form>
Reset Your Password?
</div>
<?php } ?>
Plugin Code -
<?php
namespace Vendor\Module\Plugin;
class LoginPostPlugin
{
/**
* Change redirect after login to home instead of dashboard.
*
* #param \Magento\Customer\Controller\Account\LoginPost $subject
* #param \Magento\Framework\Controller\Result\Redirect $result
*/
public function afterExecute(
\Magento\Customer\Controller\Account\LoginPost $subject,
$result)
{
$result->setPath('/'); // Change this to what you want
return $result;
}
}
I want to redirect the customer to $currenturl. Link tutorial can be able to redirect to the home page. Please suggest what needs to be done to achieve to redirect the customer to the current page.
Try the below:
Header Login Form :-
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->get('Magento\Customer\Model\Session');
$urlInterface = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Framework\UrlInterface');
$currenturl = $urlInterface->getCurrentUrl();
if(!$customerSession->isLoggedIn()) {?>
<div class="header-login-main">
<form action="<?php echo $this->getUrl('customer/account/loginPost');?>" method="post" id="login-form" novalidate="novalidate">
<input name="form_key" value="" type="hidden">
<input type="hidden" name='referer' value="<?php echo $currenturl ?>">
<div class="header-login" style="">
<span>Email</span>
<input name="login[username]" id="email" class="input-text" title="Email" data-validate="{required:true, 'validate-email':true}" aria-required="true" type="email">
</div>
<div class="header-login">
<span>Password</span>
<input name="login[password]" id="pass" class="input-text" title="Password" data-validate="{required:true}" aria-required="true" type="password">
</div>
<div class="header-login1">
<button type="submit" class="action login primary" name="send" id="send2"><span>Login</span>
</div>
</form>
Reset Your Password?
</div>
<?php } ?>
Plugin Code : -
<?php
namespace Vendor\Module\Plugin;
class LoginPostPlugin
{
protected $request;
public function __construct(
\Magento\Framework\App\RequestInterface $request
) {
$this->request = $request;
}
public function getPostReferer()
{
return $this->request->getPostValue('referer');
}
/**
* Change redirect after login to home instead of dashboard.
*
* #param \Magento\Customer\Controller\Account\LoginPost $subject
* #param \Magento\Framework\Controller\Result\Redirect $result
*/
public function afterExecute(
\Magento\Customer\Controller\Account\LoginPost $subject,
$result)
{
$result->setPath($this->getPostReferer());
return $result;
}
}
Please try with the following code I have set the current url to the instant of $resultRedirect like this : $resultRedirect->setUrl($currenturl);
<?php
namespace Vendor\Module\Controller\Account;
use Magento\Customer\Model\Account\Redirect as AccountRedirect;
use Magento\Framework\App\Action\Context;
use Magento\Customer\Model\Session;
use Magento\Customer\Api\AccountManagementInterface;
use Magento\Customer\Model\Url as CustomerUrl;
use Magento\Framework\Exception\EmailNotConfirmedException;
use Magento\Framework\Exception\AuthenticationException;
use Magento\Framework\Data\Form\FormKey\Validator;
use Magento\Catalog\Api\ProductRepositoryInterface;
class LoginPost extends \Magento\Customer\Controller\Account\LoginPost {
public function execute() {
$urlInterface = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Framework\UrlInterface');
$sku = '24-MB01'; //Edit as per your product sku
$_product = $this->productRepository->get($sku);
$currenturl = $_product->getProductUrl();
if ($this->session->isLoggedIn() || !$this->formKeyValidator->validate($this->getRequest())) {
/** #var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultRedirectFactory->create();
//$resultRedirect->setPath('home');
$resultRedirect->setUrl($currenturl);
return $resultRedirect;
}
if ($this->getRequest()->isPost()) {
$login = $this->getRequest()->getPost('login');
if (!empty($login['username']) && !empty($login['password'])) {
try {
$customer = $this->customerAccountManagement->authenticate($login['username'], $login['password']);
$this->session->setCustomerDataAsLoggedIn($customer);
$this->session->regenerateId();
} catch (EmailNotConfirmedException $e) {
$value = $this->customerUrl->getEmailConfirmationUrl($login['username']);
$message = __(
'This account is not confirmed.' .
' Click here to resend confirmation email.', $value
);
$this->messageManager->addError($message);
$this->session->setUsername($login['username']);
} catch (AuthenticationException $e) {
$message = __('Invalid login or password.');
$this->messageManager->addError($message);
$this->session->setUsername($login['username']);
} catch (\Exception $e) {
$this->messageManager->addError(__('Invalid login or password.'));
}
} else {
$this->messageManager->addError(__('A login and a password are required.'));
}
}
$resultRedirect = $this->resultRedirectFactory->create();
//$resultRedirect->setPath('home');
$resultRedirect->setUrl($currenturl);
return $resultRedirect;
}
}
If you have a plugin that receives the Magento\Customer\Controller\Account\LoginPost object you could get the referer URL like : $subject->_redirect->getRefererUrl(). Then return this URL
$productURL = $subject->_url->getUrl($subject->_redirect->getRefererUrl());
return $subject->_redirect($productURL);
I'm not 100% sure if this URL will actually be the URL you want but worth a try.

Export .xslx data using Laravel Excel with parameter

I want to export data from the database to .xlsx using Laravel-Excel.
I want to pass three parameters to query the data and download into excel file.
I already search and read a few examples but still failed to make the excel file to download.
This is my blade file.
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-3"></div>
<div class="col-md-6">
<div class="card">
<div class="card-header">Download Report</div>
<div class="card-body">
<div class="col-md-12" style="margin-bottom:15px">
<select class="form-control" name="plant" id="plant">
<option selected value="All">Please Select Plant</option>
#foreach($plants as $plant)
<option value="{{ $plant->id }}">{{ $plant->name }}</option>
#endforeach
</select>
</div>
<div class="col-md-12" style="">
<div class="input-group input-daterange" align="center">
<input type="text" name="from_date" id="from_date" readonly class="form-control" value="<?php echo date("Y-m-d");?>" />
<div class="input-group-addon" >To</div>
<input type="text" name="to_date" id="to_date" readonly class="form-control" value="<?php echo date("Y-m-d");?>"/>
</div>
</div>
<br>
<div class="col-md-12" align="center">
<button type="button" name="search" id="search" class="btn btn-info btn-block">Download</button>
</div>
</div>
</div>
</div>
<div class="col-md-3"></div>
</div>
</div>
<script type="text/javascript">
$(function() {
var date = new Date();
$('.input-daterange').datepicker({
todayBtn: 'linked',
format: 'yyyy-mm-dd',
autoclose: true
});
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#search').click(function(e){
e.preventDefault();
var from_date = $('#from_date').val();
var to_date = $('#to_date').val();
var plant = $('#plant').val();
if(plant != 'All')
{
$.ajax({
url:"{{ route('export') }}",
data:{from_date:from_date, to_date:to_date, plant:plant},
dataType:"json",
})
}
else
{
alert('Please Select Plant');
}
});
});
</script>
#endsection
This is my function at the controller
public function export(Request $request)
{
return (new DetailReportDownload($request->plant,$request->from_date,$request->to_date))->download('Report Details.xlsx');
}
and This is my Export file
class DetailReportDownload implements FromQuery, WithHeadings
{
use Exportable;
protected $plant,$from,$to;
public function __construct(String $from,String $to,String $plant)
{
$this->plant = $plant;
$this->from = $from;
$this->to = $to;
}
public function headings(): array
{
return [
'plandate',
'workcentre',
'partno',
'prodduration',
'totaldowntime',
'planout',
'cumout',
];
}
public function query()
{
return DB::table('plannings')
->select(DB::raw('plandate, workcentre, partno, prodduration, coalesce(sum(downduration),0) as totaldowntime, planout, cumout'))
->join('prodstatuses', 'plannings.id', '=', 'prodstatuses.id')
->leftJoin('downtimes', 'plannings.id', '=', 'downtimes.plan_id')
->whereBetween('plandate', array($this->from, $this->to))
->where('plant_id',$this->plant)
->where('status','Finished')
->groupBy('plannings.id')
->orderBy('plannings.id');
}
}
I wanted to download excel file from parameter given in blade file.
Thanks in advance for any help
create a provider to add below code & register to app.php file
Sheet::macro('styleCells', function (Sheet $sheet, string $cellRange, array $style) {
$sheet->getDelegate()->getStyle($cellRange)->applyFromArray($style);
});
And create class to download data using parameters,
<?php
namespace App\Modules\User\Http\Exports;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\FromView;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\AfterSheet;
/**
* Class ExportUsers
* #package App\Exports
*/
class ExportUsers implements FromView, ShouldAutoSize, WithEvents
{
protected $plannings;
/**
* ExportUsers constructor.
* #param Collection $plannings
*/
public function __construct(Collection $plannings) {
$this->plannings = $plannings;
}
/**
* #return View
*/
public function view() : View {
return view('plannings_list', [
'plannings' => $this->plannings,
]);
}
/**
* #return array
*/
public function registerEvents() : array {
return [
AfterSheet::class => function (AfterSheet $event) {
$this->createStyle($event, 'A1:N1', 9);
$event->sheet->styleCells(
'A1:N1',
[
'font' => [
'bold' => true,
]
]
);
},
];
}
/**
* #param $event
* #param $cell
* #param $size
* #throws \PhpOffice\PhpSpreadsheet\Exception
*/
private function createStyle($event, $cell, $size) {
/** #var AfterSheet $event */
$event->sheet->getDelegate()->getStyle($cell)->getFont()->setSize($size);
}
}
add this code to controller
private function downloadCsv($exportCsvList) {
return Excel::download(new ExportUsers($exportCsvList),
'students.xlsx');
}

Magento - How to validate my radio button?

in my custom module, I have a form which has radio buttons.
When I click the submit button it does not validate the radio button.
<?php
$question = Mage::getModel('emme_question/question')->getCollection()->getLastItem();
$answers = $question->getSelectedAnswersCollection();
?>
<h4><?php echo $this->escapeHtml($question->getValue()); ?></h4>
<ul>
<?php foreach ($answers as $answer): ?>
<li>
<label><?php echo $this->escapeHtml($answer->getValue()) ?></label>
<input class="required required-field" type="radio" name="my_custom_answer" value="<?php echo $answer->getId() ?>" required>
</li>
<?php endforeach ?>
and
<?php
// app/code/local/Envato/Custompaymentmethod/Model/Paymentmethod.php
class Envato_Custompaymentmethod_Model_Paymentmethod extends Mage_Payment_Model_Method_Abstract {
protected $_code = 'custompaymentmethod';
public function validateRadioIsSelected()
{
$var options = $$('input.Classname');
for( i in options ) {
if( options[i].checked == true ) {
return true;
}
}
return false;
}
public function getOrderPlaceRedirectUrl()
{
return Mage::getUrl('custompaymentmethod/payment/redirect', array('_secure' => false));
}
}
Parse error: syntax error, unexpected 'options' (T_STRING) in /home/mmstore9/public_html/demo/app/code/local/Envato/Custompaymentmethod/Model/Paymentmethod.php on line 27
use this magetno default validation class to validate the radio button
validate-one-required-by-name
OR
validate-one-required
I solved
public function validate()
{
foreach (Mage::getModel('emme_question/question')->load(1)->getSelectedAnswersCollection() as $answer)
{
if ($answer->getIsCorrect())
{
if ($answer->getId() == $_POST['my_custom_answer'])
{
Mage::getSingleton('core/session')->addSuccess('Risposta esatta');
} else
{
Mage::throwException('Risposta sbagliata!');
}
}
}
}

how make to form search in CodeIgniter using two fields

I want to make a search form in Codeigniter using two fields.
But I'm confused about making the controller and model.
View:
echo form_open("home/pencarian","class='form-inline navbar-search'");
<input id="srchFld" class="srchTxt" name="keyword" type="text" value=" echo $this->session->userdata("keyword");" />
<select class="srchTxt" name="kategori">
<option>All</option>
foreach ($kat as $kategori){
$id = $kategori['id'];
$nama_kategori = $kategori['nama_kategori'];
$created_at = $kategori['created_at'];
<option value=" echo $id; ?>"><?php echo $nama_kategori; </option>
}
</select>
echo form_submit('action', 'Cari', "class='btn btn-primary'");
echo form_close();
How do I make the controller and model?
Model example_model.php
public function search($search_txt, $search_category) {
$this->load->database();
$sql = "select * from search_table where search_field = ? and search_category = ?;";
$query = $this->db->query($sql, array($search_txt, $search_category));
return $query->result();
}
Controller home
public function pencarian() {
$this->load->model('example_model', 'm');
$search_txt = $this->input->post('srchFld');
$search_category = $this->input->post('kategori');
$data['search_result'] = $this->m->search($search_txt, $search_category);
$this->load->view('example_view', $data);
}
View example_view
<?php foreach($search_result as $r): ?>
<div><?php echo $r->field1 . ' ' . $r->field2; ?></div>
<?php endforeach; ?>

How to get Recently View Product For Guest User In Magento

I am Facing one problem when i want to display recent products for guest user, is there any ways to show recently view product for guest user,
Magento support Recently View Product For Registered User But for Guest User How to show Recently view products by that particular Guest...
I am waiting for your kind response,
Hope i get some reply on this.
Thanks in advance.
here is phtml
<?php if ($_products = $this->getRecentlyViewedProducts()):
$ids = '';
foreach ($_products as $_item) {
$ids .= $_item->getId() . ';';
}
?>
<div class="lftHeading">
<span
style="text-transform:capitalize;background:url(<?php echo $this->getSkinUrl('css/images/clo_left_heading_bullet2.gif') ?>) top left no-repeat;"
>recently viewed</span>
</div>
<div class="innerRgtMenu recently_viewed_block">
<table id="recently-viewed-items">
<?php $i = 0; foreach ($_products as $_item): if ($i == 3) {
continue;
} ?>
<?php $product = $_item ?>
<tr>
<td><a style="border:1px solid #DDDDDD;float:left;margin:5px;padding:5px;"
href="<?php echo $this->getProductUrl($_item, array('_nosid' => true)) ?>" class="product-image"><img
src="<?php echo $this->helper('catalog/image')->init($product, 'thumbnail')->resize(50) ?>"
width="50" alt="<?php echo $this->escapeHtml($_item->getName()) ?>"/></a></td>
<td><a style="position:relative;top:3px;font-size:11px;"
href="<?php echo $this->getProductUrl($_item, array('_nosid' => true)) ?>"><?php echo $this->escapeHtml($_item->getName()) ?></a>
</td>
</tr>
<?php $i++;
endforeach; ?>
</table>
<div style="margin: 5px 0px 5px 2px; text-align: center; width: 140px;">
<input type="button" class="button recently_viewed_btn" value="<?php echo $this->__('Email These To Me') ?> "
onClick="email_recently('<?php echo $ids; ?>')"/>
</div>
<div style="margin:5px;">
<?php echo $this->__('See All Recently Viewed') ?>
</div>
<script type="text/javascript">decorateList('recently-viewed-items');</script>
and php file
class Mage_Reports_Block_Product_Viewed extends Mage_Reports_Block_Product_Abstract
{
const XML_PATH_RECENTLY_VIEWED_COUNT = 'catalog/recently_products/viewed_count';
/**
* Viewed Product Index model name
*
* #var string
*/
protected $_indexName = 'reports/product_index_viewed';
/**
* Retrieve page size (count)
*
* #return int
*/
public function getPageSize()
{
if ($this->hasData('page_size')) {
return $this->getData('page_size');
}
return Mage::getStoreConfig(self::XML_PATH_RECENTLY_VIEWED_COUNT);
}
/**
* Added predefined ids support
*/
public function getCount()
{
$ids = $this->getProductIds();
if (!empty($ids)) {
return count($ids);
}
return parent::getCount();
}
/**
* Prepare to html
* check has viewed products
*
* #return string
*/
protected function _toHtml()
{
if (!$this->getCount()) {
return '';
}
$this->setRecentlyViewedProducts($this->getItemsCollection());
return parent::_toHtml();
}
}
if it will not work for guests - try to change last function in php file to
protected function _toHtml()
{
/* if ($this->_hasViewedProductsBefore() === false) {
return '';
} */
$this->setDisplayMinimalPrice('1');
$collection = $this->_getRecentProductsCollection();
$hasProducts = (bool)count($collection);
// if (is_null($this->_hasViewedProductsBefore())) {
// Mage::getSingleton('reports/session')->setData('viewed_products', $hasProducts);
// }
if ($hasProducts) {
$this->setRecentlyViewedProducts($collection);
}
return parent::_toHtml();
}
Block Recently Viewed Products works fine without any code modification in magento 1.6-1.9.2.2
If block is not shown you need check:
Block is properly added to page in visible container (by default block added to right sidebar)
Log is Enabled. Check System->Configuration->System->Log Option "Enable Log" = Yes
Rebuild index "Category Product" (catalog_category_product)
as far as I know - it should work fine for guests. at least it works on my site
here is how I put that on a page:
<block type="reports/product_viewed" name="reports.product.recently.viewed" template="reports/recently_viewed.phtml" />

Resources