Paging issue on custom collection in magento - magento

I have created custom block to retrieve product from multiple categories. I have extended this block to core product List block. Pager is not working on custom collection, have any idea why paging is not working?
I am using this function in collection.php
public function addCategoriesFilter($categories)
{
$alias = 'cat_index';
$categoryCondition = $this->getConnection()->quoteInto(
$alias.'.product_id=e.entity_id AND '.$alias.'.store_id=? AND ',
$this->getStoreId()
);
$categoryCondition.= $alias.'.category_id IN ('.$categories.')';
$this->getSelect()->group('e.entity_id');
$this->getSelect()->joinInner(
array($alias => $this->getTable('catalog/category_product_index')),
$categoryCondition,
array('position'=>'position')
);
$this->_categoryIndexJoined = true;
$this->_joinFields['position'] = array('table'=>$alias, 'field'=>'position' );
return $this;
}

After exploring many hours and reading almost all forums for paging on custom collection I have found a way to show paging for custom collection page.
I have a requirement to show toolbar for my page that will show products which are having diabetic value as yes (diabetic is the custom attribute).
Firstly we need to filter the collection on phtml file:
$_productCollection = Mage::getModel('catalog/product')->setStoreId($storeId)getCollection()->addAttributeToFilter("diabetic",1);
/* populate toolbar collection with your collection */
$toolbar = Mage::getBlockSingleton('catalog/product_list')->getToolbarBlock();
$toolbar->setCollection($_productCollection);
echo $toolbar->toHtml();

<block type="catalog/product_list_toolbar" name="product_list_toolbar" template="catalog/product/list/toolbar.phtml">
<block type="page/html_pager" name="product_list_toolbar_pager" />
This needs to be added to the xml block where you are attempting to load product so that it gets the toolbar and the pager.
See this link as reference.
Products with Pagination

Related

Magento: Load products from specific category to product page

I have a custom made menu, that contains products from specific category (category id=3). In my menu there is a block:
{{block type="catalog/product_list" name="product_list" mode="grid" template="catalog/product/category_list_1.phtml"}}
I can normally see the products on main site and inside the category, but on product page the getBlockTemplateProcessor() doesn't return any data.
The code inside file is the same as for list.phtml, i just made some html modifications, located in:
\catalog\product\list.phtml
Why exactly is my code not rendering? Is it a problem that the files can't be located from product site?
Why all is good inside a category site and on product site not?
I suggest you use your own block extending the product list block, so that you can properly set the product collection, something like:
class YourNamespace_YourModule_Block_List extends Mage_Catalog_Block_Product_List
{
protected function _getProductCollection()
{
if (is_null($this->_productCollection)) {
$collection = Mage::getResourceModel('catalog/product_collection');
Mage::getModel('catalog/layer')->prepareProductCollection($collection);
$prodIdArray = array(1,2,3,4,5);
$collection->addAttributeToFilter('entity_id', $prodIdArray);
$collection->addStoreFilter();
$this->_productCollection = $collection;
}
return $this->_productCollection;
}
}
You can filter to add or remove any products that you want from the listing.

How to add Manufacturer attribute to Filter results in magento layered navigation

I'm working with Magento Enterprise edition, here by default I'm getting Category's and Price ranges in left navigation bar while displaying products list by Category.
But, I need to add other product attributes like Manufacturer, Transfer type... to the filter results in layered navigation.
I'm able to display that list of Manufacturers under that Manufacturer Attribute but with option 'Filter with no results' with 0 count.
Whenever I changed that option in Admin side for Manufacturer Attribute as 'Filter with results' under Catalogue/Attributes/Manage Attributes I'm unable to see that attribute in front end left navigation bar.
Even though there is assigned lot of products with Manufacturer's. Do i need to make any changes in Code, please help me out I'm new to this magento platform.
Thanks
Sorry if sound a stupid question but you changed see the category configuration to be anchor in YES?
I'll keeping you posted after the answer
Best,
Alejandro
add this function in your:
magento/app/code/core/Mage/Catalog/Block/Navigation.php
public function getAllManu()
{
$product = Mage::getModel('catalog/product');
$attributes = Mage::getResourceModel('eav/entity_attribute_collection')
->setEntityTypeFilter($product->getResource()->getTypeId())
->addFieldToFilter('attribute_code', 'manufacturer'); //can be changed to any attribute
$attribute = $attributes->getFirstItem()->setEntity($product->getResource());
$manufacturers = $attribute->getSource()->getAllOptions(false);
return $manufacturers;
}
Now add phtml file at location:
magento/app/design/frontend/mytheme/default/template/catalog/navigation/left_nav.phtml
<?php foreach ($this->getAllManu() as $manufacturer): ?>
<li>
<?php echo $manufacturer['label'] ?>
</li>
<?php endforeach;?>
And simply call block:magento/app/design/frontend/mytheme/default/layout/catalog.xml
<reference name="left">
<block type="catalog/navigation" name="catalog.leftnavigation" template="catalog/navigation/left_nav.phtml"/>
</reference>

Create magento pagination in custom product collection inside phtml file

First of all, i didn't create custom module to handle this product collection, so, i just put model inside phtml file, i know it's bad implementation, i'm new in magento and i have to do small customization in loading product collection to the extension that bought by client.
This product collection is only showing up in specific category, so inside custom design tab in category management, i put this code :
<reference name="product_list">
<action method="setTemplate"><template>catalog/product/list_all.phtml</template></action>
And here is my query to load product collection, this query is inside list_all.phtml file :
$collection = Mage::getResourceModel('catalog/product_collection')
->addAttributeToSelect('*')
->addStoreFilter()
->addUrlRewrite()
->addAttributeToFilter('groupdeal_status', Devinc_Groupdeals_Model_Source_Status::STATUS_RUNNING)
->joinField('groupdeals_id','groupdeals/groupdeals','groupdeals_id','product_id=entity_id',null,'left');
$collection->getSelect()->limit(2);
i've used this code to generate the pagination :
$toolbar = Mage::getBlockSingleton('catalog/product_list')->getToolbarBlock();
$toolbar->setCollection($collection);
echo $toolbar->toHtml();
the code above only showing the products count and show per-page options, not 1,2,3..., links, i've also tried to use the code below :
<?php
$toolbar = Mage::getBlockSingleton('catalog/product_list')->getToolbarBlock();
$toolbar->setCollection($collection);
echo $toolbar->getCollection()->getSize().'------'.var_dump($toolbar->getPages());
?>
but, the var_dump returning NULL values. Should i create custom module to do this? or is there any ways to do this way, without creating custom module??
Try adding setCurPage() to your collection filters, then update it based on URL parameters via $_GET when needed:
$collection = Mage::getResourceModel('catalog/product_collection')
->addAttributeToSelect('*')
->addStoreFilter()
->addUrlRewrite()
->addAttributeToFilter('groupdeal_status', Devinc_Groupdeals_Model_Source_Status::STATUS_RUNNING)
-> joinField('groupdeals_id','groupdeals/groupdeals','groupdeals_id','product_id=entity_id',null,'left');
$collection->getSelect()->limit(2)->setCurPage(1);
if ($_GET["p"] <= $_productCollection->getLastPageNumber()){
$_productCollection->setCurPage($_GET["p"]);
}

Images in Magento widgets

I am developing a site for a fashion client in Magento Community version 1.4.2 and as part of this project I need to have some customized home page promotion blocks to feature specific products or categories of products. For this I thought I would write my own widget and have made pretty good progress in this with the exception of how to deal with images. I need to include an image as part of the promotion. In my widget definition file I included the following parameter
<image>
<label>Image</label>
<description>Promotion image</description>
<visible>1</visible>
<type>image</type>
</image>
This seemed at first to work fine and when creating/editing a widget in the admin back end a file upload field is included in the widget options however on saving the form the image does not appear to be uploaded, or its details retained in the database. Does anyone else have experience of using images in widgets and what I may be doing wrong?
There are a couple reason why it doesn't save/upload the image:
The form enctype needs to be "multipart/form-data" for a file upload to work
Even if you change the form enctype to "multipart/form-data" you will notice if you monitor the requests that it gets POST'ed as "application/x-www-form-urlencoded" this is because it is done through ajax and ajax by itself can't process a file upload, you need to process them separately.
I have successfully implemented a "Insert Image" button which initialises the Media Library dialogue where you can browse your server for images and/or upload images.
Once the user clicks "Insert File" it inserts the full image url into a textbox in the widget so it's passed along like a normal field to your template.
This is how I achieved it:
In your widget.xml specify a new node:
<image translate="label">
<label>Image</label>
<visible>1</visible>
<required>1</required>
<type>label</type>
<helper_block>
<type>widgets/cms_wysiwyg_images_chooser</type>
<data>
<button translate="open">
<open>Insert Image...</open>
</button>
</data>
</helper_block>
</image>
The helper block type <type>widgets/cms_wysiwyg_images_chooser</type> is a custom class, so you can change it to anything you want as long as you create the class/files correctly.
<?php
class Stackoverflow_Widgets_Block_Cms_Wysiwyg_Images_Chooser extends Mage_Adminhtml_Block_Template
{
public function prepareElementHtml(Varien_Data_Form_Element_Abstract $element)
{
$config = $this->getConfig();
$chooseButton = $this->getLayout()->createBlock('adminhtml/widget_button')
->setType('button')
->setClass('scalable btn-chooser')
->setLabel($config['button']['open'])
->setOnclick('MediabrowserUtility.openDialog(\''.$this->getUrl('*/cms_wysiwyg_images/index', array('target_element_id' => $element->getName())).'\')')
->setDisabled($element->getReadonly());
$text = new Varien_Data_Form_Element_Text();
$text->setForm($element->getForm())
->setId($element->getName())
->setName($element->getName())
->setClass('widget-option input-text');
if ($element->getRequired()) {
$text->addClass('required-entry');
}
if ($element->getValue()) {
$text->setValue($element->getValue());
}
$element->setData('after_element_html', $text->getElementHtml().$chooseButton->toHtml());
return $element;
}
}
?>
And that is it! You should now have a new field in your widget options called "Image" with a textbox and a button in which you can insert the url to an image on your server and display it from your template.
A quick explanation of how it works:
A button is created that has an onclick function that calls the Media Library dialogue by calling MediabrowserUtility.openDialog() which along is passed the parameter target_element_id which tells media library what element to set the value in once they user clicks "Insert File" so we simply pass along the id of our textbox in the widget for it to receive the url of the image that the user selected.
Hope this helps someone as I couldn't find any resources out there that explained how to do it so I spent quite a while digging through Magento to work it all out :)
What I would like to do in the future is have it so it displays the image after you select it in the widget, and it stores the url in a hidden field, but having an onchange bind is not fired when the value is set to the element from js/mage/adminhtml/browser.js in the insert function, so without changing the core files it is a lot harder to do. I thought about playing around with when the form gets focus again after the Media Library closes or a timer (pretty dodgey but would work), but I have other things to move on to and may come back to it later!
UPDATE:
The URL's that the Media Library generates are like so:
http://www.yourwebsite.com/index.php/admin/cms_wysiwyg/directive/___directive/e3ttZWRpYSB1cmw9Ind5c2l3eWcvd2lkZ2V0cy9iYW5uZXIvaG9tZXBhZ2UvZm9yZWdyb3VuZC9maXNoLXRhbmsucG5nIn19/key/e8167e3884e40b97d8985e7b84e7cbc7875f134e5f7e5946c9c2a482d0279762/
Which are a cached image, and only work if the user is an admin. Stupid? Yes. If you insert the same image in to a CMS page when the html is generated for output it converts it to the original url on the server accessible via /media/wysiwyg/path/to/file/photo.jpg. We need the original url to show to the user, so what we can do is hook into the function that generates the widget html (when you click "Insert Widget") and look for /admin/cms_wysiwyg/directive/___directive/ and replace it with the original URL to the image as the CMS page does.
In your config.xml for your custom widgets:
<global>
<models>
<widget>
<rewrite>
<widget>Stackoverflow_Widgets_Model_Widget</widget>
</rewrite>
</widget>
</models>
</global>
Then create the model Widget code\local\Stackoverflow\Widgets\Model\Widget.php:
<?php
class Stackoverflow_Widgets_Model_Widget extends Mage_Widget_Model_Widget
{
public function getWidgetDeclaration($type, $params = array(), $asIs = true)
{
foreach($params as $k => $v){
if(strpos($v,'/admin/cms_wysiwyg/directive/___directive/') !== false){
$parts = explode('/',parse_url($v, PHP_URL_PATH));
$key = array_search('___directive', $parts);
if($key !== false){
$directive = $parts[$key+1];
$src = Mage::getModel('core/email_template_filter')->filter(Mage::helper('core')->urlDecode($directive));
if(!empty($src)){
$params[$k] = parse_url($src, PHP_URL_PATH);
}
}
}
}
return parent::getWidgetDeclaration($type, $params, $asIs);
}
}
Which overrides the getWidgetDeclaration function which is called every time a the widget output is produced for a textarea/wysiwyg and looks through all the parameters and if it finds an image that is linked to the admin cache it will find out the original image and overwrite the variable in the array and call the original function with the parameters.
If the cached image is not found the function will work as normal.
UPDATE: 13/09/2012
As Jonathan Day pointed out you have to overwrite Mage_Widget_Model_Widget_Instance also if you want it to work in a Widget Instance.
I haven't had the need to add an image to a widget through a Widget Instance until now and was confused why my function didn't work, until I investigated and realised the "popup" widget instances use Mage_Widget_Model_Widget and the widget instances that are used on a Widget options tab (no popup) are Mage_Widget_Model_Widget_Instance and do not extend Mage_Widget_Model_Widget so do not inherit the functionality.
To add the functionality to Mage_Widget_Model_Widget_Instance simply add the line <widget_instance>Petbarn_Widgets_Model_Widget_Instance</widget_instance> to your config.xml so it will look like:
<global>
<models>
<widget>
<rewrite>
<widget>Stackoverflow_Widgets_Model_Widget</widget>
<widget_instance>Stackoverflow_Widgets_Model_Widget_Instance</widget_instance>
</rewrite>
</widget>
</models>
</global>
Then create the model Instance code\local\Stackoverflow\Widgets\Model\Widget\Instance.php:
<?php
class Petbarn_Widgets_Model_Widget_Instance extends Mage_Widget_Model_Widget_Instance
{
protected function _beforeSave()
{
if (is_array($this->getData('widget_parameters'))) {
$params = $this->getData('widget_parameters');
foreach($params as $k => $v){
if(strpos($v,'/cms_wysiwyg/directive/___directive/') !== false){
$parts = explode('/',parse_url($v, PHP_URL_PATH));
$key = array_search('___directive', $parts);
if($key !== false){
$directive = $parts[$key+1];
$src = Mage::getModel('core/email_template_filter')->filter(Mage::helper('core')->urlDecode($directive));
if(!empty($src)){
$params[$k] = parse_url($src, PHP_URL_PATH);
}
}
}
}
$this->setData('widget_parameters', $params);
}
return parent::_beforeSave();
}
}
This time we are modifying the widget_parameters data at the start of the _beforeSave() function so it fixes up the url before it saves it.
You also have to ensure the /js/mage/adminhtml/browser.js javascript file is included (in my case it wasn't) to get the MediabrowserUtility functionality.
To ensure it is included, the easiest way is to include it for all of admin (didn't spend much time targeting it better).
Create a local.xml for adminhtml layouts (if you don't already have one): app\design\adminhtml\default\default\layout\local.xml
<?xml version="1.0"?>
<layout version="0.1.0">
<default>
<reference name="head">
<action method="addJs"><script>mage/adminhtml/browser.js</script></action>
</reference>
</default>
</layout>
This will make Magento include js/mage/adminhtml/browser.js on every page of admin so MediabrowserUtility will always be available.
NOTE: I'm using Magento Enterprise 1.11.2.0 so I'm not sure how it behaves on other versions.
I solved this use case by creating a custom field type for widgets:
<image>
<label>Image</label>
<description>Promotion image</description>
<visible>1</visible>
<type>widgetimagechooser/chooser</type>
</image>
I implemented a block Aijko_WidgetImageChooser_Block_Chooser that triggers the standard Magento image chooser element.
To solve the problem with the non clear url to the image file I implemented a custom controller Aijko_WidgetImageChooser_Adminhtml_Cms_Wysiwyg_Images_ChooserController that handles the return value from the Magento standard image chooser.
The value is added to a textbox in the widget. This relative url to the image then can be used to show the image in the frontend.
Feel free to try the extension available on Github or install directly using Magento Connect.
Thx krus for you answer! I've found a nicer way to solve the problem with the cached image URLs. I even had to do this, because your solution overwriting the Widget Model didn't work with Magento 1.7.0.2.
So what I have done is adding a new GET parameter use_file_url to the URL used for the Chooser Block:
$url = $this->getUrl(
'*/cms_wysiwyg_images/index',
array(
'target_element_id' => $element->getName(),
'use_file_url' => 1
)
);
This passes the GET parameter to the media browser. The next step is to pass this parameter to the onInsertAction of the Mage_Adminhtml_Cms_Wysiwyg_ImagesController. Do do this, you have to override the getOnInsertUrl() function of the Mage_Adminhtml_Block_Cms_Wysiwyg_Images_Content Block:
public function getOnInsertUrl()
{
$useFileUrl = (int)$this->getRequest()->getParam('use_file_url', 0);
return $this->getUrl('*/*/onInsert', array('use_file_url' => $useFileUrl));
}
Then you need to handle the new parameter in the Mage_Adminhtml_Cms_Wysiwyg_ImagesController controller:
public function onInsertAction()
{
$useFileUrl = (int)$this->getRequest()->getParam('use_file_url', 0) == 1 ? true : false;
$helper = Mage::helper('cms/wysiwyg_images');
$storeId = $this->getRequest()->getParam('store');
$filename = $this->getRequest()->getParam('filename');
$filename = $helper->idDecode($filename);
$asIs = $this->getRequest()->getParam('as_is');
Mage::helper('catalog')->setStoreId($storeId);
$helper->setStoreId($storeId);
if ($useFileUrl == false) {
$image = $helper->getImageHtmlDeclaration($filename, $asIs);
} else {
$image = $helper->getImageMediaUrl($filename);
}
$this->getResponse()->setBody($image);
}
The last step is to override the Mage_Cms_Helper_Wysiwyg_Images helper and add the getImageMediaUrl() function:
public function getImageMediaUrl($filename)
{
return $this->getCurrentUrl() . $filename;
}
I think this is a quite pretty approach, even though you have to ovverride 4 classes. But passing a GET parameter seems to be more future safe than parsing the cached URL.
There is no file uploads for widgets. To solve that problem you may use magento media browser and select image like for wysiwyg editor, but there is other issue, media browser do not return clear url of image.
As of Magento version 1.9.2.0 you will also need to add the following to your adminhtml layout file:
lib/flex.js
lib/FABridge.js
mage/adminhtml/flexuploader.js
Magento's Image custom attributes normally does not come to extension tab and you will have to go to Catalog>Product> Images to assign this attribute. But with some custom coding you can achieve this.

Magento - Display Same Block Multiple Times on CMS Page

I'm using the method described here to display an individual product on a cms page:
http://www.molotovbliss.com/magento-commerce/magento-display-a-product-image-within-static-pages-and-blocks/
The problem is that if I try to display 2 products using this method both blocks show the same product even if I specify a different id in each block ie:
{{block type="catalog/product_new" product_id="1" template="catalog/product/view/your_new_page.phtml"}}
{{block type="catalog/product_new" product_id="2" template="catalog/product/view/your_new_page.phtml"}}
Adding the above code to my cms page results in product 1 being displayed twice.
Here is the solution change product_new to product_view
like this:
type="catalog/product_view"
have fun :)
Without knowing exactly what version of Magento you are running, I chose to look at 1.3.2.4 for you.
Oddly, I'm suprised you get any good result using 'catalog/product_new'. It has no provision for passing in the product id as a block arg. 'catalog/product_view' will allow you to pass in the product id as an arg, but only once. If you notice below, it's sets the product as a registry object the first time and will not use the passed in product id after that.
public function getProduct()
{
if (!Mage::registry('product') && $this->getProductId()) {
$product = Mage::getModel('catalog/product')->load($this->getProductId());
Mage::register('product', $product);
}
return Mage::registry('product');
}
My 2 cents (not beeing sure though...) : did you try to set a name to each block ?
Like :
{{block type="catalog/product_new" product_id="1" name="first.product" template="catalog/product/view/your_new_page.phtml"}}
{{block type="catalog/product_new" product_id="2" name="second.product" template="catalog/product/view/your_new_page.phtml"}}

Resources