Setting model as template data (attribute) for child block - magento

In my product view template i'm loading child template, and transfering product instance to be available in this child template:
<?php
echo $this->getLayout()
->createBlock('core/template')
->setTemplate('catalog/product/view/addedToCartDialog.phtml')
->setAttribute('product', $_product)
->toHtml();
?>
Then in my catalog/product/view/addedToCartDialog.phtml i'm trying to use this product instance:
<?php $product = $this->getData('product'); ?>
<?php echo"<pre>";print_r($product->getId());echo"</pre>"; ?>
However it seems to be not loaded: Fatal error: Call to a member function getId() on a non-object in /home/ryba/workspace/polcode/Greenlights/app/design/frontend/default/greenlights/template/catalog/product/view/addedToCartDialog.phtml on line 2
But when i check variable $product with print_r:
<?php echo"<pre>";print_r($product);echo"</pre>"; ?>
It is displayed that this variable is correct Mage_Catalog_Model_Product Object, also checked if attributes is correct (like sku, name etc) - everything is correct.
What is wrong with this ?

I'm going to give you several answers. The first is the direct answer to your question. The rest are alternatives, but better ways to do what you're trying. The last answer is, in my opinion, the best.
Direct Answer:
Instead of using setAttribute, just use the magic setter/getter methods:
<?php
// In catalog/product/view.phtml
echo $this->getLayout()
->createBlock('core/template')
->setTemplate('catalog/product/view/addedToCartDialog.phtml')
->setProduct($_product)
->toHtml();
?>
<?php
// In addedToCartDialog.phtml
$_product = $this->getProduct();
echo $_product->getId();
?>
Better:
And, if you know you are in a template loaded by the catalog/product controller, you can get the product this way.
<?php
// In catalog/product/view.phtml
echo $this->getLayout()
->createBlock('core/template')
->setTemplate('catalog/product/view/addedToCartDialog.phtml')
->toHtml();
?>
<?php
// In addedToCartDialog.phtml
$_product = Mage::registry('product');
echo $_product->getId();
?>
Even Better
The best way would be to use a different block type which has the methods already loaded (again, if you know you are in a template loaded by the catalog/product controller)
<?php
// In catalog/product/view.phtml
echo $this->getLayout()
->createBlock('catalog/product_view')
->setTemplate('catalog/product/view/addedToCartDialog.phtml')
->toHtml();
?>
<?php
// In addedToCartDialog.phtml
$_product = $this->getProduct();
echo $_product->getId();
?>
And Finally, the Best
One last item of business. The better way to add extra blocks to your templates is to add the block in your local.xml file.
<!-- Local.xml -->
<catalog_product_view translate="label">
<reference name="content">
<block type="catalog/product_view" name="addedToCartDialog" as="addedToCartDialog" template="catalog/product/view/addedToCartDialog.phtml" />
</reference>
</catalog_product_view>
Now, set up your phtml file
<?php
// In addedToCartDialog.phtml
$_product = $this->getProduct();
echo $_product->getId();
?>
Then call the block from your phtml file
// In catalog/product/view.phtml
<?php echo $this->getChildHtml('addedToCartDialog'); ?>

Related

Magento - how to filter categories in phtml

I have been working on the maga menu. I got the collection in phtml like:
<?php $_helper = Mage::helper('catalog/category') ?>
<?php $_categories = $_helper->getStoreCategories() ?>
<?php $currentCategory = Mage::registry('current_category') ?>
Now I have to add the filter to show specific categories. Like I have an array(1,2,3,4) of categories that i want to show. so how can I apply filter to this Helper.
Any one have any suggestion please answer.
Thanks.
The first answer is correct but it's not efficient as it consumes unnecessary database round trips. #Karan's code issues a query to the database for every id. Just imagine if the number of category ids to be filtered were 50 or above.
My example would be this:
<?php
$catIds = array(1,2,3,4);
$catCollection = Mage::getModel('catalog/category')->getCollection()->addAttributeToFilter('id', $catIds)->addAttributeToFilter('is_active',1);
foreach($catCollection as $category){
echo $category->getName()." ";
}
This will reduce the database roundtrip to just one.
use this code
<?php $catids[]=array(1,2,3,4);
foreach($catids as $id):
$_category = Mage::getModel('catalog/category')->load($id);
if($_category->getIsActive()):
echo $_category->getName();
endif;
endforeach;
?>
and don't forget to link my answer if it was helpful

Magento - Unable to display custom options

I'm using a module for displaying grouped configurable products and all options are showing except custom options. They are displaying on the configurable product page but that's it. I'm trying to use the code in app\design\frontend\blank\blank\template\catalog\product\view\options.phtml in my custom configurable.phtml but $_options is showing up null. Here is the code used to retrieve $_options
<?php $_options = Mage::helper('core')->decorateArray($this->getOptions()) ?>
<?php if (count($_options)):?>
and after the javascript
<?php foreach($_options as $_option): ?>
<?php echo $this->getOptionHtml($_option) ?>
<?php endforeach; ?>
</dl>
<?php else: echo dlkghflghf;?>
<?php endif; ?>
The dlkghflghf is displaying so i know $_options is not showing up. Any suggestions?
Your custom configurable.phtml is a template of what block? You can use a block that extends Mage_Catalog_Block_Product_View_Options or you can set your own method for options like the method from Mage_Catalog_Block_Product_View_Options, you also need to have a method getProduct():
public function getOptions()
{
return $this->getProduct()->getOptions();
}

Magento: Display Category Image by ID in CMS page

Is there a way to display a category image by it's category id in a CMS page?
You can display a category link by id with:
{{widget type="catalog/category_widget_link" anchor_text="Displayed Text" title="Title attribute text" template="catalog/category/widget/link/link_block.phtml" id_path="category/22"}}
Or display category products by it's id.
{{block type="catalog/product_list" category_id="14" template="catalog/product/list.phtml"}}
But I can't figure out hwo to display a specific categories image in a CMS page just by calling it's id.
Any idea?
In stock magento you cant.
There are essentially 3 ways of achieving this, in order of preference (good to bad imo):
Create and use a widget
Embed directly in cms page and use a custom block type for initialising the category
Embed directly in a cms page, use core/template block type and initialise category inside the template directly
1. Use a widget
I have previously answered a similar question and provided a complete example on how to build such a widget specific to a category:
magento - category name and image in static block?
2. Custom module
You nned to create a module with a block to support this. You can then just include the block in cms pages using the following syntax:
{{block type="yourmodule/category_image" category_id="14" template="yourmodule/category/image.phtml"}}
Your block class is going to look like this:
<?php
class Yourcompany_Yourmodule_Block_Category_Image extends Mage_Core_Block_Template
{
public function getCategory()
{
if (! $this->hasData('category')) {
$category = Mage::getModel('catalog/category')->load($this->getData('category_id'));
$this->setData('category', $category);
}
return $this->getData('category');
}
}
and your template class is going to look like this:
<?php
$_helper = $this->helper('catalog/output');
$_category = $this->getCategory();
$_imgHtml = '';
if ($_imgUrl = $_category->getImageUrl()) {
$_imgHtml = '<p class="category-image"><img src="'.$_imgUrl.'" alt="'.$this->htmlEscape($_category->getName()).'" title="'.$this->htmlEscape($_category->getName()).'" /></p>';
$_imgHtml = $_helper->categoryAttribute($_category, $_imgHtml, 'image');
}
?>
<?php if($_imgUrl): ?>
<?php echo $_imgHtml ?>
<?php endif; ?>
3. Use core/template block type
Include on the cms page like so..
{{block type="core/template" category_id="14" template="category/image.phtml"}}
Create your template - catalog/category/image.phtml
<?php
$_helper = $this->helper('catalog/output');
$category = Mage::getModel('catalog/category')->load($this->getData('category_id'));
$_imgHtml = '';
if ($_imgUrl = $_category->getImageUrl()) {
$_imgHtml = '<p class="category-image"><img src="'.$_imgUrl.'" alt="'.$this->htmlEscape($_category->getName()).'" title="'.$this->htmlEscape($_category->getName()).'" /></p>';
$_imgHtml = $_helper->categoryAttribute($_category, $_imgHtml, 'image');
}
?>
<?php if($_imgUrl): ?>
<?php echo $_imgHtml ?>
<?php endif; ?>
I don't think you'll be able to just call the image because it is not a block. In /design/base/default/template/category/view.phtml, it's just calling the image url as an attribute of the block and then building the output HTML right in the template file. There isn't any specific element in the block that renders it to call with magento's shortcode.
Best best would be to build a new widget. There's plenty of guides, and they're pretty awesome once you get to know them better.

Magento - Filter Category list by category attribute

I have a list of store categories, and everything is working well except for one thing. I would like the list of categories to omit any that are set as 'Include in Navivation Menu = No'.
I can tell at this point that this attribute is not being loaded, but I'm having a difficult time figuring out where to place the filter. Currently, I am getting my category list via:
<?php $_helper = Mage::helper('catalog/category') ?>
<?php $_categories = $_helper->getStoreCategories() ?>
Followed by:
<?php foreach ($_categories as $_category) : ?>
<?php $_category = Mage::getModel('catalog/category')->load($_category->getId()) ?>
...
...
At this point, I have my category objects how I want them. But if I run a debug on these objects, the 'include_in_menu' attribute is not listed.
So for some reason:
<?php $_subCategory->getIncludeInMenu() ?>
Was not working for me after I ran:
<?php foreach($_parentCategory->getChildrenCategories() as $_subCategory) : ?>
The object was still the same model, but ['include_in_menu'] was no longer part of the object. I don't like this solution, but I just reconverted the object back:
<?php $_subCategory = Mage::getModel('catalog/category')->load($_subCategory->getId()) ?>
And then it worked fine. Not sure why getting the children would strip down the object, but it does.

Display categories on home page in Magento

I am a newbie in Magento and wanted to display all categories on the Magento home page rather than a top nav menu.
I read a lot of articles on it, but nothing has helped. Please point me to the right direction.
Thanks in advance.
The code below does a couple of things, first it will get all the store’s categories - it then checks to see if they are active before continuing.
Code Courtesy : magentocommerce forum
<?php
/* Get the categories that are active for the store */
$_main_categories=$this->getStoreCategories();
/* Get the current category the user is in */
$_current_category=$this->getCurrentCategory();
/* Get the current category path */
$_categorypath = $this->getCurrentCategoryPath();
?>
<ul>
<?php
if ($_main_categories):
/* This bit cycles through the categories - setting the next one to current */
foreach ($_main_categories as $_main_category):
if($_main_category->getIsActive()):
$cur_category=Mage::getModel('catalog/category')->load($_main_category->getId());
$layer = Mage::getSingleton('catalog/layer');
$layer->setCurrentCategory($cur_category);
/* Write the main categories */
?>
<li><?php echo $this->getCurrentCategory()->getName();?></li>
<?php
/* Check the category variable loop against the current category path if it is - print sub categories */
if (in_array($this->getCurrentCategory()->getId(), $_categorypath)): ?>
<?php $_maincategorylisting=$this->getCurrentCategory()?>
<?php $_categories=$this->getCurrentChildCategories()?>
<?php if($_categories->count()):?>
<ul>
<? foreach ($_categories as $_category):?>
<? if($_category->getIsActive()):
$cur_subcategory=Mage::getModel('catalog/category')->load($_category->getId());
$layer = Mage::getSingleton('catalog/layer');
$layer->setCurrentCategory($cur_subcategory);
?>
<li> <?php echo $_category->getName()?></li>
<? endif;?>
<?endforeach?>
</ul>
<?php /* This resets the category back to the original pages category
**** If this is not done, subsequent calls on the same page will use the last category
**** in the foreach loop
*/ ?>
<?php $layer->setCurrentCategory($_current_category); ?>
<?endif;?>
<?endif;?>
<?php
endif;
endforeach;
else:
?>
<p>$_main_categories array was empty.</p>
<p>This might be because you are referencing this phtml file with a wrong type attribute. You should use <block type="catalog/navigation" ... /> !</p>
<?php endif; ?>
I got where the problem was.
The solution is at this link http://samsami2u.wordpress.com/2009/09/15/add-categories-with-images-on-homepage-magento/ and I was trying to add this line
{{block type="catalog/navigation" name="catalog.category" template="catalog/category/list.phtml"}} to home page from back end in layout update xml under design tab but the correct way was to place it in content tab.

Resources