Magento - Get product items attribute in view.phtml - magento

I am trying to load a custom category in the catalog/category/view.phtml to archive this I use:
<?php
$_category = Mage::getModel('catalog/category')->load(47);
$_productCollection = $_category->getProductCollection();
if($_productCollection->count()) {
foreach( $_productCollection as $_product ):
echo $_product->getProductUrl();
echo $this->getPriceHtml($_product, true);
echo $this->htmlEscape($_product->getName());
endforeach;
}
?>
I can load the URL for example, now I want to load a custom attribute for example color:
$_product->getResource()->getAttribute('color')->getFrontend()->getValue($_product)
This code does not work, I am 100% sure the color attribute is set to show in the category listing and also that the items in this category have this fields fill. I know this because this code works on list.html.
What I am doing wrong? I am working with 1.7.0.2.
The expected result is to show all COLOR attibutes from a custom cateogory in
catalog/category/view.phtml

I can't believe I just found the answer. Because we are not in a regular category listing we need to add the custom attributes to the collection.
Here is the code:
$_productCollection = $_category->getProductCollection()
->addAttributeToSelect('color');

If "color" is in the flat table you should be able to
$_product->getColor();
If this attribute is not in the collection, you can either add it to the flat table by making the attribute filterable, add it in the PHP collection call
$_productCollection = $_category->getProductCollection()
->addAttributeToSelect('color');
Or load the product model to get all of the attributes
$_product = Mage::getModel('catalog/product')->load($_product->getId());
echo $_product->getColor();

Make this attribute visible in listing/frontend
Run Reindexing
foreach( $_productCollection as $_product ):
echo $_product->getProductUrl();
in this code var_dump $_product->getData(); check if this var_dump results in that specific attribute value getting displayed.
Note:
$_product->getResource()->getAttribute('color')->getFrontend()->getValue($_product)
is not a very efficient way of calling.

Related

Magento (newbie query): how can I display product specification attributes?

I want to extract the Brand and other attributes within the "Specification" under "Product Information" (Catalog -> Manage Products - then select a product).
I can get the product name by doing the following:
<?php echo $_helper->productAttribute($_product, $_product->getName(), 'name') ?>
I need something similar to display a Specification attribute on the front end.
How do I do this?
Thank you
This worked for me :
$_product = $this->getProduct();
$guarantee = Mage::getResourceModel('catalog/product')->getAttributeRawValue($_product->getId(), 'spec_guarantee', 1); // 1 is the store id
echo $guarantee;
// outputs:
// 2 Years Manufacturers Guarantee
In magento 1.9 I used the following code to display a custom attribute.
<?php $_product->getData('takealotlink'); ?>
However to make sure it displays in the front-end you also have to set the correct property from manage attributes.
The property to set in Front-end properties is "Used in product listing". See arrow below.

Fetching current category in magento

Im trying to get the current category from catalog/product/view.phtml
<?php
$_helper = $this->helper('catalog/output');
$item = $this->getProduct();
$curCat = Mage::registry('current_category');
if($curCat && $curCat->getId() == Mage::helper('function')->NEWS_CAT_ID) {
// do stuff
}
?>
The major problem with this method is; Im getting the parrent category_ID(2) instead of the child category_ID(10). How do i fix this problem?
SinisterGlitch, you was goes to this page from catalog search page....registry have save it current category default category ,whose ids is 2.That means the product call from category is save as current category
check your root category form admin panel you probably add this product to root category also.

Magento How to display/list all categories from catalog category flat table

I have enabled "Use Flat Catalog Category" & "Use Flat Catalog Product" to "yes" for getting better performance. But after enabling this options one of my previous cms page on which I was getting a list of all subcategories is not working anymore.
The code using which I was getting sub-categories before enabling flat data is:
$_category = Mage::getModel('catalog/category')->load(CATEGORY-ID);
$_categories = $_category->getCollection()->addAttributeToSelect(array('url_key','name','image','all_children','is_anchor','description'))
->addAttributeToFilter('is_active', 1)
->addIdFilter($_category->getChildren())
->setOrder('position', 'ASC')
->joinUrlRewrite();
Note: I have checked that, both of my flat data tables have been successfully populated. This code still works if I change the "Use Flat Catalog Category" option to "No".
Now, what should be the code to get a list of category along with its subcategories where as it may pull data from "catalog_category_flat_store_*" table?
Here I got this code working
$_category = Mage::getModel('catalog/category')->load(CATEGORY-ID);
$_categories = $_category
->getCollection()
->addAttributeToSelect(array('name', 'image', 'description'))
->addIdFilter($_category->getChildren());
foreach ($_categories as $_category):
echo $_category->getName();
endforeach;
Just remove filters and check.
->addAttributeToFilter('is_active', 1)
->addIdFilter($_category->getChildren())
also do a getselect and check what sql query is generated.
Above two will provide further hints.Post those here for further commenting.

How to add Rating of a product in products listing?

I am displaying products of a particular category to the homepage content section.
I have made a separate .phtml file to display my homepage.
Now I want to show the ratings of a product (products are already rated). How do I show it?
If you look at the category listing template it's pretty easy to work out how category pages render out the review summary to show the rating block.
First load the product in question:
$product = Mage::getModel('catalog/product')->load($id);
Then create a product listing block to give access to the correct methods:
$block = Mage::app()->getLayout()->createBlock('catalog/product_list');
Finally run the getReviewsSummaryHtml() method and pass it the product to get the summary HTML.
$html = $block->getReviewsSummaryHtml($product, 'short');
You can do this.
$_product = Mage::getModel('catalog/product')->load($id);
if ($_product->getRatingSummary() && $rating = $this->getReviewsSummaryHtml($_product, 'short')) :
echo $rating;
else:
echo "<a href='$_product->getProductUrl()'>" . $this->__('Be the first to review this') . "</a>";
endif;

Magento: How to retrieve the minimal price of (i.e.) grouped products?

I am trying to display a grouped product's price on the product view page in Magento 1.7.0.2, just as it is being displayed in the category product listing ("Starting at: xx.xx"). I thought I could just use
$this->getPriceHtml($_product, true);
to do so because it works the same way in the category product listing, but as everything I tried to do in Magento, it is not that easy because that method doesnt return anything on the product view page.
I looked a little deeper into Magento's code and figured out that the cause of this problem is the product's minimal price data not being set on the product view page ($_product->getMinimalPrice() returns null).
Therefore I did some research on how to load a product's minimal price which brought up ideas like
$_product->getPriceModel()->getMinimalPrice($_product);
which doesnt work because apparently that method was deprecated and removed in one of the last updates or
$priceModel = Mage::getResourceModel('catalogindex/price');
$priceModel->setStoreId(Mage::app()->getStore()->getId());
$priceModel->setCustomerGroupId(Mage::getSingleton('customer/session')->getCustomerGroupId());
$minimalPrices = $priceModel->getMinimalPrices(array($_product->getId()));
$minimalPrice = $minimalPrices[0];
$_product->setData('minimal_price', $minimalPrice['value']);
$_product->setData('minimal_tax_class_id', $minimalPrice['tax_class_id']);
which doesnt work either because the table 'catalogindex_minimal_price' is empty.
So my question is, how does Magento load the minimal price in the category product listing?
I looked a little deeper into Magento's code and tracked down how Magento loads the products of the product list.
When viewing the product list, the product collection is loaded by the model Mage_Catalog_Model_Layer, which adds the minimal price and other stuff to the products in the collection by adding joins to the collection’s SQL, but I have not yet found a model that does the same thing for single products instead of collections.
Because I don’t want to use a direct SQL query, I checked out the CatalogIndex module, but that module seems not to be working at all because all its indexing tables are empty or even corrupted.
$data_grouped = Mage::getModel("catalogindex/data_grouped");
$minimal = $data_grouped->getMinimalPrice(array($_product->getId()), Mage::app()->getStore());
looked good at first but it gives me the following error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'catalog_product_index_price.value' in 'field list'
The CatalogIndex module is either deprecated or I’m just too stupid to enable it.
However, I have now created a workaround in my price.phtml template, which uses the same method to retrieve the minimal price and tax percents as the product list does:
At the beginning of the template I added the following:
$this->setProduct(
Mage::getModel("catalog/product")->getCollection()
->addAttributeToSelect(Mage::getSingleton("catalog/config")->getProductAttributes())
->addAttributeToFilter("entity_id", $this->getProduct()->getId())
->setPage(1, 1)
->addMinimalPrice()
->addFinalPrice()
->addTaxPercents()
->load()
->getFirstItem()
);
which may not be the perfect solution, but it does the job and it does it a little cleaner than iterating over all child products and finding the minimal price that way.
This isn't an answer as much as a big HTML comment on Subsurf's answer. If you're reading this, you might be implementing your own custom module to display a product list. In my case, it's a single page just for wholesalers. My goal was to get a list of my own company's products and give them a list like it was another category. I copied my template's list.phtml to my new content.phtml. But getMinimalPrice() was returning NULL, meaning that when this code calls the getPriceHtml(), price.phtml wasn't showing wholesale pricing.
I did a simple module with index controller and a content.phtml. Using the boilerplate I see all over the net, in the indexController.php file, change:
$block = $this->getLayout()->createBlock(
'Mage_Core_Block_Template',
'b2b',
array('template' => 'b2b/content.phtml')
);
to:
$block = $this->getLayout()->createBlock(
'Mage_Catalog_Block_Product_List',
'b2b',
array('template' => 'b2b/content.phtml')
);
This does a lot of the heavy lifting for you to show the products list correctly.
Now, on to the template file, in my case content.phtml, you get your product collection and then use Subsurf's code in the top of the foreach() which repeats.
$_productCollection = Mage::getModel('catalog/product')
->getCollection()
// ->addAttributeToSelect('*')
// doesn't work ->addAttributeToSelect('special_price')
->addAttributeToSelect('sku')
->addAttributeToFilter('status', 1)
->addAttributeToFilter('visibility', 4)
// http://stackoverflow.com/questions/1332742/magento-retrieve-products-with-a-specific-attribute-value
->addFieldToFilter( array(
array('attribute'=>'manufacturer','eq'=>'143')
, array('attribute'=>'manufacturer','eq'=>'139')
))
;
echo "<p>There are ".count($_productCollection)." products: </p>";
echo '<div class="category-products">';
// List mode
if($this->getMode()!='grid') {
$_iterator = 0;
echo'<ol class="products-list" id="products-list">';
foreach ($_productCollection as $_product) {
?> <li class="item<?php if( ++$_iterator == sizeof($_productCollection) ): ?> last<?php endif; ?>">
<?php
$_product=Mage::getModel("catalog/product")->getCollection()
->addAttributeToSelect(Mage::getSingleton("catalog/config")->getProductAttributes())
->addAttributeToFilter("entity_id", $_product->getId())
->setPage(1, 1)
->addMinimalPrice()
->addFinalPrice()
->addTaxPercents()
->load()
->getFirstItem()
);
echo "Minimal price: ".$_product->getMinimalPrice()."<br>\n";
Since this isn't a single product's page and I'm using other template code, $this->setProduct() didn't do anything for me. I guessed if there was a set, there might be a get, so $_product=$this->getProduct() was the magic my template's price.phtml needed to work properly. Then I noticed I could just assign the Mage:: in setProduct() directly to $_product.
Thanks, Subsurf!!!
There is another way that will still allow you to use $this->getPriceHtml($_product, true); in your template, which then handles all the complex price display rules and puts "Starting at" before grouped product prices.
I'm using this for a custom featured product block. In a block class I have this function:
class MyCompany_Catalog_Block_Product_Featured extends Mage_Catalog_Block_Product_Abstract {
public function setGroupedProductPrice($group_product) {
$prices = array();
foreach ($group_product->getTypeInstance()->getChildrenIds($group_product->getId()) as $ids) {
foreach ($ids as $id) {
$product = Mage::getModel('catalog/product')->load($id);
$prices[] = $product->getPriceModel()->getPrice($product);
}
}
ksort($prices);
$group_product->setPrice(array_pop($prices));
}
}
Then in the template:
<?php
if ($_product->getTypeId() == 'grouped')
$this->prepareGroupedProduct($_product);
echo $this->getPriceHtml($_product, true);
?>
The following does the trick without using a product collection:
$priceResource = Mage::getResourceSingleton('catalogindex/price');
$select = $priceResource->getReadConnection()->select();
$select->from(
array('price_table' => $priceResource->getMainTable())
)
->where('price_table.entity_id = ?', $_product->getId())
->where('price_table.website_id = ?', Mage::app()->getStore()->getWebsiteId())
->where('price_table.customer_group_id = ?', Mage::getSingleton('customer/session')->getCustomerGroupId());
$result = $priceResource->getReadConnection()->fetchRow($select);
This code is adapted from \Mage_CatalogIndex_Model_Resource_Price::getMinimalPrices and made suitable for one single product.

Resources