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' => ''));
Related
I have created view that displays on page 10 newest article. I have in row two fields: image and content. In settings of image field I chose image style (for example: medium). How can I change image style to another (example: large) only in first row?
I have tried it in preprocess but i don't know where is stored information about image style:
function theme_preprocess_views_view_unformatted__lista_depesz_default(&$variables) {
$view = $variables['view'];
$rows = $variables['rows'];
$style = $view->style_plugin;
$options = $style->options;
$variables['default_row_class'] = !empty($options['default_row_class']);
foreach ($rows as $id => $row) { $variables['rows'][$id] = array();
$variables['rows'][$id]['content'] = $row;
$variables['rows'][$id]['attributes'] = new Attribute();
if ($row_class = $view->style_plugin->getRowClass($id)) {
$variables['rows'][$id]['attributes']->addClass($row_class);
}
if ($id == 0 && $row['content']['#row']->_entity->field_image[0] != NULL) {
//some php code to change image style
}
}
}
Regards
You can create view with original images, and set style inside your twig files, using for example twig tweak:
https://www.drupal.org/project/twig_tweak
Inside twig file you can set any style with conditioning
{{ 'public://images/ocean.jpg' | image_style('thumbnail') }}
Regarding your code and your explanations, I'm not sure to understand what you are trying to achieve.
1/ you try to add a CSS class to the 1st image of your view. Why not using the following CSS path .my_view .first img {}
2/ if you try to call another image style, can you create a view with only the 1st item, or a promoted? Then a second view with the rest of the items ?
3/ if you try to call another image style, you can do it without any code.
You install the module http://drupal.org/project/views_conditional then you add 2 images with 2 different image style, and you apply your condition inside the condition fieldset.
I really prefer the solution 3 because it's pure Drupal build.
I hope it helps.
Cheers
I have a page on my website that filters content from a separate page using the entityFieldQuery method. The problem is that the images I am filtering on to the new page need a different image style applied to them so that they load into smaller images. I have picture mapping set up on the site but I have only applied it via the Drupal workbench in the image fields where you can choose an image style from a dropdown.
The code below is my entityfieldquery and the conditional statement that creates the content that is being filtered from another page on to the current page. Is there any way I can revise this code to apply a different image style to the images that are being generated?
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
->propertyCondition('status', NODE_PUBLISHED)
->propertyCondition('type', 'Blog')
->propertyCondition('created', array($old_date, $current_date),'BETWEEN')
->propertyOrderBy('created', 'DESC')
->fieldCondition('field_blog_categories', 'tid', $term_id)
->fieldCondition('field_blog_categories', 'tid', array('55', '26'))
->range(0, 9);
$result = $query->execute();
}
if(isset($result['node'])) {
$blog_items_nids = array_keys($result['node']);
$blog_items = entity_load('node', $blog_items_nids);
if (count($blog_items)>2){
$data = array();
foreach ($blog_items as $blg) {
$field_blog_header_image = field_view_field('node', $blg, 'field_blog_header_image', 'picture');
$temp_blog_cat = field_view_field('node', $blg, 'field_blog_categories');
$data[$temp_blog_cat['#items'][0]['tid']][] = array(
'blog' => $temp_blog_cat["#object"]->title,
'img' => isset($field_blog_header_image) ? render($field_blog_header_image) : '',
'link' => $temp_blog_cat['#object']->path['alias'],
);
}
?>
Yes, you can use function image_style_url():
https://api.drupal.org/api/drupal/modules!image!image.module/function/image_style_url/7
That function will give you path to image in any style you pass to it as long as you can acquire and pass image URI to it as parameter.
So, check the values you get from your view, find how to get image URI and call it like:
$image_path = image_style_url('style_name', $uri);
I m making a website using Joomla (2.5) and Virtuemart (2.6.14) . My question is :
Is it possible to fill category view thumbnails with a thumbnail of a product that belongs to this category?
I dont want to upload photos to categories one by one because this would take huge amount of time.
Thank you.
You have to create a template override of /components/com_virtuemart/sublayouts/categories.php to /templates/your_template/html/com_virtuemart/sublayouts/categories.php.
And replace this code (approx. line: 74):
echo $category->images[0]->displayMediaThumb("",false);
With:
$productModel = VmModel::getModel('product');
$prod_in_category = $productModel->getProductListing(false, 1, false, true, true, true, $category->virtuemart_category_id);
$productModel->addImages($prod_in_category[0],1);
if(!empty($prod_in_category[0]->images[0])){
echo $prod_in_category[0]->images[0]->displayMediaThumb("",false);
} else {
echo $category->images[0]->displayMediaThumb("",false);
}
You could also use this method that takes a random image but it will take much more memory as it uses an array of all category products.
$productModel = VmModel::getModel('product');
$prod_in_category = $productModel->getProductsInCategory($category->virtuemart_category_id);
$sel = array_rand($prod_in_category);
$productModel->addImages($prod_in_category[$sel],1);
if(!empty($prod_in_category[$sel]->images[0])){
echo $prod_in_category[$sel]->images[0]->displayMediaThumb("",false);
} else {
echo $category->images[0]->displayMediaThumb("",false);
}
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....
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')?>