Get base product image in Magento - php

I want to get base product image in Magento to resize it and display in cart sidebar.
Unfortunatelly this:
echo $this->helper('catalog/image')->init($_product, 'image')->resize(38, 38);
prints Magento placeholder image.
Base image is set for this product properly. Small image and thumbnail works great.
No idea what's going on.
EDIT:
Solution:
Get full product data this way:
$_product = Mage::getModel('catalog/product')->load($_item->getProduct()->getId());
and then use it as you wish:
echo $this->helper('catalog/image')->init($_product, 'image')->resize(38, 38);

I think you are looking for this:
echo Mage::getModel('catalog/product_media_config')
->getMediaUrl( $product->getImage() ); //getSmallImage(), getThumbnail()
Credit should be given to BenMarks who gave this answer.

Try:
$this->helper('catalog/image')->init($_product, 'image')->keepFrame(false)
->constrainOnly(true)->resize(38,38);

BE AWARE!
$this->helper('catalog/image')->init($_product, 'small_image')->resize(38, 38);
is object, not url string it self. Yes, you can use it directly with echo, but shouldn't assign it to var. For example this wont work:
$images = array();
foreach($products as $_product){
$images[]=$this->helper('catalog/image')->init($_product, 'small_image')
->resize(38, 38);
}
After foreach, you will have only one last image url saved. Simple way is to get truly string url is:
$images = array();
foreach($products as $_product){
$images_obj = $this->helper('catalog/image')->init($_product, 'small_image')
->resize(38, 38);
$images[] = (string)$images_obj;
}

The reason this is happening is because the image attribute is not loaded in the product listing. Normally you can change this while editing the attribute, but you can't edit those settings for this attribute. I think that's because it is a stock attribute.
TLDR;
UPDATE catalog_eav_attribute SET used_in_product_listing = 1 WHERE attribute_id = 106;
** Warning, you should not execute this ^^^ query until you are certain your image attribute_id for the catalog_product entity is 106!
Some answers are suggesting this method:
$_product = Mage::getModel('catalog/product')->load($_item->getProduct()->getId());
echo $this->helper('catalog/image')->init($_product, 'image')->resize(38, 38);
You should not do this! This is because you will do a full product load! This is not efficient, and is most likely being done inside of a loop which is even worse! Sorry for screaming!
I usually do not condone direct DB edits, but in this case it was the easiest solution for me:
# First make sure we are using all the right IDs, who knows, I have seen some fubar'ed deployments
SELECT entity_type_id FROM eav_entity_type WHERE entity_type_code = 'catalog_product';
# 10
SELECT attribute_id FROM eav_attribute WHERE attribute_code = 'image' AND entity_type_id = 10;
# 106
# Now that we know the exact attribute_id....
UPDATE catalog_eav_attribute SET used_in_product_listing = 1 WHERE attribute_id = 106;
Now the image attribute data will be automagically loaded on the product listing pages, then you can access it like this:
echo $this->helper('catalog/image')->init($_product, 'image');
The best part is that you are not loading the entire product in a loop! DO NOT EVER DO THAT EVER
** Also, because I know I am going to get people saying that this is not the Magento way, the alternative would be to create a module that has an SQL setup script that runs the command.

Small image and thumbnail works great.
Then try small_image instead of image, like this:
echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(38, 38);

<img src='.$this->helper('catalog/image')->init($product, 'small_image')->resize(225, 225).' width=\'225\' height=\'225\'/>

Magento Product image assigning to Variable
$product_image = Mage::helper('catalog/image')->init($productmodel,'small_image')->keepFrame(true)->resize(width,height).'';
Magento Product image assigning to Object
$products[] = Mage::helper('catalog/image')->init($productmodel,'small_image')->keepFrame(true)->resize(width,height).'';
It Works for me....

Related

Prestashop, Get other products with same ean13 in product page

I'm newbie to smarty and php.
My situation is that my product_reference is unique but product_ean13 is similar in some products which are like each other. What I need is to have product_id of those products in one of them product page. I mean when visitors open a product page I want to show Image of those products which have the same ean13. Showing the images and HTML, CSS is ok for me, my problem is in PHP,SMARTY which should pass the value from PHP file to TPL file.
I guess I should write a function in Product.php file and pass array values to product.tpl file. But I couldn't.
Would you please help me?
Edited: As you may know a weakness in Prestashop 1.6 is that if your products nature is to have colors and size, like clothes and smartphones! you have two approach to create them. first approach is to create them as a combination of one product and second approach is to create them as separated and not related products. first approach has a good point that all of them will be showed up in product page when customer visits each of them and also have a weakness of exposure in category page which all those attributes will be seen as one product.(imagine between all colors of one shirt only one is seen and your costumer may like blue more but always the red is being showed in category page. or its not easy to know from category page that you also have the gold color of the smartphone) this solution will helps you what to create your products as separated products but you what to show them in product page of each of them. this way we will use benefit of both approach and we wont have the weakness of any of them. we use ean13 (or any other unused field you have, to use as a code that is a same value in same products)
I you have created the function in product.php, you should use it in ProductContronller.php and here you can assign a value that contains the list of your products wich has the same ean13.
we should add a class in product.php to get cover images of products with the same ean13:
public static function getImageByEan13Product($ean13_colors)
{
$rows = Db::getInstance()->executeS('
SELECT `id_product`, `id_image`
FROM `'._DB_PREFIX_.'image`
WHERE `id_product` IN ('.implode(',', $ean13_colors).') AND `cover` = 1'
);
$images = array();
foreach ($rows as $row){
$images[] = array(
'idProduct' => $row['id_product'],
'idImage' => $row['id_image']
);
}
return $images;
}
and the following function which gets the color attributes of the products which contain same ean13 code:
public static function getColorByEan13Product($ean13)
{
$rows = Db::getInstance()->executeS('
SELECT `id_product`
FROM `'._DB_PREFIX_.'product`
WHERE `ean13` = '.$ean13.' AND `active` = 1 AND `id_product` IN (SELECT DISTINCT `id_product` FROM `'._DB_PREFIX_.'stock_available` WHERE `quantity` > 0)');
$colors = array();
foreach ($rows as $row){
$colors[] = $row['id_product'];
}
return $colors;
}
and also there is another class in the ProductController.php named assignAttributesGroups() which provide attributes of the product. in this class we should add following code:
$ean13_colors = array();
$ean13_colors = Product::getColorByEan13Product($this->product->ean13);
$this->context->smarty->assign('ean13colors', $ean13_colors);
$ean13_images = array();
$ean13_images = Product::getImageByEan13Product($ean13_colors);
$this->context->smarty->assign('ean13images', $ean13_images);
then these two values ean13_images and ean13_coloes can be used in TPL file product.tpl and showed up instead of color attributes. like the code bellow:
{foreach from=$ean13images key=k item=v}
{if $product->id != $v.idProduct}
<li>
<a href="{$link->getProductLink($v.idProduct)|escape:'html':'UTF-8'}" class="pro_column_left selected">
<img src="{$link->getImageLink($product->link_rewrite, $v.idImage, 'small_default')}" height="{$smallSize.height}" width="{$smallSize.width}" class="replace-2x img-responsive" {if !isset($from_product_secondary_column) || !$from_product_secondary_column} itemprop="image"{/if} />
</a>
</li>
{/if}
{/foreach}
and the value ean13colors can be used where we want to show a balloon tooltip on mouseover the image to say whats the color attribute of the other product that is being showed by same ean13.

Set Base Image Programmatically

I've got this problem that I can't solve. Partly because I can't explain it with the right terms. I'm new to this so sorry for this clumsy question.
Below you can see an overview of my goal.
I am trying to sell Similar product in my magento for this i wrote some code that every thing is working fine..
But i have only one problem with images..
that is I am getting all images of current product but the base image is not selected, How can i set the very first image as base image Programmatically.
Any ideas ?
Hello You can do as follows :
$image =$imagePath."image.png";
$product->setMediaGallery(array('images'=>array (), 'values'=>array ()));
if(is_file($image))
{
$product->addImageToMediaGallery($image, array ('image', 'small_image', 'thumbnail'), false, false);
}
i.e you need to first set the media gallery, P.S This is a necessary step.
then add all images to gallery using addImageToMediaGallery where 'image' ref to 'base_image'
i.e in above example we are setting image.png to base_image, small_image and thumbnail image in a single call.
hope this helps you.
I've achieved the same result by using:
$product->setSmallImage($path)
->setThumbnail($path)
->setImage($path)
->save();
Works better for the case where your media gallery has one or more pictures in it.
I'm doing
$product->load();
$gallery = $product->getMediaGalleryImages();
$paths = array();
foreach ($gallery as $image) {
$paths[] = $image->getFile();
}
sort($paths);
$path = array_shift($paths);
try {
$product->setSmallImage($path)
->setThumbnail($path)
->setImage($path)
->save();
} catch (Exception $e) {
echo $e->getMessage();
}
Which gets all the product images, sort's them by file name and sets the first to the product primary image. As I ran a import and added all my pictures, but didn't set the primary image.
To grab a set or "broken" products I used:
$collection = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToFilter('small_image', array('eq' => ''));

Get product atribute value in magento

Hi i have got the maximum elements of products using below code but it doesn't show the size attribute of my product, the size attribute is visible on front-end but i cant understand why it is not printing with this code
<?php
ob_start();
session_start();
ini_set('display_errors', 1);
//for order update
include '../../../../app/Mage.php';
Mage::app('default');
echo '<pre>';
if(isset($_REQUEST['productid'])){
$productId = $_REQUEST['productid'];
}else{
$productId = '12402'; // product ID 10 is an actual product, and used here for a test
}
$product = Mage::getModel('catalog/product')->load($productId); //load the product
//$product_id = $product->getId();
//$created_at = $product->getcreated_at();
//$description = $product->getdescription();
//$short_description = $product->getshort_description();
//$sku = $product->getsku();
//$size_fit = $product->getsize_fit();
//$style_ideas = $product->getstyle_ideas();
//$name = $product->getname();
//$price = $product->getprice();
//$stocklevel = (int)Mage::getModel('cataloginventory/stock_item')->loadByProduct($product)->getQty();
If its the size_fit attribute (i'm guessing that because its the only size attempt in your code..) use $product->getSizeFit(). For just size use $product->getSize(). When this is not returning anything, please post the attribute installer if you have one. Mufadall his answer is also correct but judging your code you are just using wrong syntax.
Basicly according to the magic get method the first letter is turned into a capital and all other letters after an underscore.
Ex.: To fetch my_sample_attribute use getMySampleAttribute().
getData('my_sample_attribute') would also be an option but you shouldn't make a habbit of doing that because in some cases, for some attributes getData('attribute') returns a different value then getAttribute()....
$product->getData($attribute_code);
will return you the actual attribute value. For attribute with type dropdown it will return option id
$product->getResource()->getAttribute($attribute_code)->getFrontend()->getValue($product);
will return actual value
You can use this:
$product->getData('Your Attribute ID');
Go to Size attribute and check for Drop Down used in product listing if it set to No then set it to Yes, after that you can get your size attribute with other product attribute
You can use the getters, or getData();
The getter is set in magento with the magic __get() method, and you can use it in the following way:
$product->getDescription() // ( to get description attribute)
$product->getShortDescription() // (to get short_description attribute)
So basically you explode the attribute with underscores, and capitalize the words, and you will get what you need to put after "get".
Here is something very useful I use all the time
Zend_Debug::dump($product->getData());
This gets you all the data you have to work with. If you are missing data, it means it's not loaded.
Good luck!

Magento: How to get thumbnail?

I downloaded a script to create a CSV datafeed of my products and I would also like to include a url to the thumbnail. The code already has the following for the product image url:
$product_data['ImageURL']=Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA).'catalog/product'.$product->getImage();
So I tried to adjust this to:
$product_data['ThumbnailURL']=Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA).'catalog/product'.$product->getThumbnail();
Which displays exactly the same image url (not the thumb). How would I fix this?
I did a var_dump($product); and the result was:
["image"]=> string(18) "/f/i/file_2_18.png" ["small_image"]=> string(18) "/f/i/file_2_18.png" ["thumbnail"]=> string(18) "/f/i/file_2_18.png"
I also need to get the subcategory for the product but I don't know how to call this. How can I see which variables are possible? E.g. $product->getPrice or $product->getName?
I recently needed to do this as well... here's how I got to it:
$_product->getMediaGalleryImages()->getItemByColumnValue('label', 'LABEL_NAME')->getUrl();
Or another example
You should use the catalog product media config model for this purpose.
<?php
//your code ...
echo Mage::getModel('catalog/product_media_config')
->getMediaUrl( $product->getImage() ); //getSmallImage(), getThumbnail()
Edit After your comment.
Update Answer
See below URL
Make all store images the base, small and thumbnail images in Magento?
Try it
$products = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect('*');
foreach ($products as $product) {
if (!$product->hasImage()) continue;
if (!$product->hasSmallImage()) $product->setSmallImage($product->getImage());
if (!$product->hasThumbnail()) $product->setThumbnail($product->getImage());
$product->save();
}
Hope that helps you!
If you want to see which data you can access you could try this:
<?php var_dump(array_keys($product->getData())); ?>
You can then use two methods to get this data:
<?php $product->getAttributeName() // Use CamcelCase ?>
or
<?php $product->getData('attribute_name') // underscores ?>

Grabbing a custom product image label in Magento?

I have a block on my front page that is grabbing the two newest products with a custom product image called image_feature_front_right.
I use this code as the query:
$_helper = $this->helper('catalog/output');
$_productCollection = Mage::getModel("catalog/product")->getCollection();
$_productCollection->addAttributeToSelect('*');
$_productCollection->addAttributeToFilter("image_feature_front_right", array("notnull" => 1));
$_productCollection->addAttributeToFilter("image_feature_front_right", array("neq" => 'no_selection'));
$_productCollection->addAttributeToSort('updated_at', 'DESC');
$_productCollection->setPageSize(2);
I am able to get:
the image: echo $this->helper('catalog/image')->init($_product, 'image_feature_front_right')->directResize(230,315,4)
the product url: echo $_product->getProductUrl()
the product name: $this->stripTags($_product->getName(), null, true)
The only thing I am unable to get is the custom images label. I have tried echo $this->getImageLabel($_product, 'image_feature_front_right'), but that seems to do nothing.
Can anyone point me in the right direction?
Thanks!
Tre
I imagine this is some sort of magento bug. The issue seems to be that the Magento core is not setting the custom_image_label attribute. Whereas for the default built-in images [image, small_image, thumbnail_image] it does set these attributes - so you could do something like:
$_product->getData('small_image_label');
If you look at Mage_Catalog_Block_Product_Abstract::getImageLabel() it just appends '_label' to the $mediaAttributeCode that you pass in as the 2nd param and calls $_product->getData().
If you call $_product->getData('media_gallery'); you'll see the custom image label is available. It's just nested in an array. So use this function:
function getImageLabel($_product, $key) {
$gallery = $_product->getData('media_gallery');
$file = $_product->getData($key);
if ($file && $gallery && array_key_exists('images', $gallery)) {
foreach ($gallery['images'] as $image) {
if ($image['file'] == $file)
return $image['label'];
}
}
return '';
}
It'd be prudent to extend the Magento core code (Ideally Mage_Catalog_Block_Product_Abstract, but I don't think Magento lets you override Abstract classes), but if you need a quick hack - just stick this function in your phtml file then call:
<?php echo getImageLabel($_product, 'image_feature_front_right')?>

Categories