Grabbing a custom product image label in Magento? - php

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')?>

Related

Joomla custom fields inside template

I would like to customize my template for Joomla 3.7 so that I can use the new feature of Joomla 3.7, Custom fields (com_fields), and display and format them via CSS in my template where I need to display them.
Can someone suggest me the PHP code I should use in the template to display field(s), some example please.
Thanks in advance.
For everyone getting late to the party. In case you want to use your custom form fields in a Module-Override (which really are the only way to modify j!-templates, so google 'joomla template override') you can use this handy snippet:
<?php
JLoader::register('FieldsHelper', JPATH_ADMINISTRATOR . '/components/com_fields/helpers/fields.php');
$jcFields = FieldsHelper::getFields('com_content.article', $item, true);
$itemCustomFields = array();
foreach($jcFields as $field) {
$itemCustomFields[$field->name] = $field->rawvalue;
}
?>
Now you cna use your customfields like so: itemCustomFields['customFieldName1']
Haven't tested in article overrides. May soon, if so, this will get updated.
certainly not the right way to do it but I had the same need and I found a work around based on https://www.giudansky.com/news/12-coding/146-joomla-custom-fields
Copie default.php from /components/com_content/views/article/tmpl/default.php to
templates/YOUR_THEME/html/com_content/article/default.php
Add following code line 25 :
$myCustomFields = array();
foreach($this->item->jcfields as $field) {
$myCustomFields[$field->name] = $field->value;
}
$GLOBALS['myCustomFields'] = $myCustomFields;
Typically you put on a global var the content of fields attached to your article.
On your template page you can know retrieved value of your field.
just print_r($GLOBALS['myCustomFields']); to view the content of your array.
That will do the trick waiting for a better answer..
This is absolutely the wrong way to do this I think but I was tearing my hair out so i came up with this quick db query to return custom field values in the template. surely this violates some kind of joomla protocol?
obviously this assumes you can get $articleid into your template already which is the Current ID of your article.
I too am waiting on a better solution but hope this helps
$db =& JFactory::getDBO();
$sql = "select * from #__fields_values where `item_id` = $articleid";
$db->setQuery($sql);
$fieldslist = $db->loadObjectList();
echo $fieldslist[0]->value;
echo $fieldslist[1]->value;
echo $fieldslist[your field ID here]->value;
I found it was easiest to follow how com_fields does it in its rendering code. In Joomla!3.7+, you'll find it in [joomla_root]/components/com_fields/layouts/fields/render.php .
Here are the main parts you need to reproduce the formatting that Joomla has:
JLoader::register('FieldsHelper', JPATH_ADMINISTRATOR . '/components/com_fields/helpers/fields.php');
<dl class="fields-container">
<?php foreach ($this->item->jcfields as $field) : ?>
<?php // If the value is empty do nothing ?>
<?php if (!isset($field->value) || $field->value == '') : ?>
<?php continue; ?>
<?php endif; ?>
<?php $class = $field->params->get('render_class'); ?>
<dd class="field-entry <?php echo $class; ?>">
<?php echo FieldsHelper::render($context, 'field.render', array('field' => $field)); ?>
</dd>
<?php endforeach; ?>
</dl>
This loops through all available tags for the component or article. The nice thing about this method is it still applies the render classes you include with the fields.
Make sure to set Automatic Display to Do not automatically display on your fields; otherwise you will see them twice on your page view.
If you want to just target specific fields to show, you can use the name of the field to target it. (The label and value pair is underneath.) See the field Joomla docs for more info.
I implemented this small function to get specific custom field values:
function getCustomFieldValue($field_name, $article_id, $default_value = '') {
// Load custom field list
$fields = FieldsHelper::getFields('com_content.article', $article_id, true);
$field_ids = array_column($fields, 'id', 'name');
$model = JModelLegacy::getInstance('Field', 'FieldsModel', array('ignore_request' => true));
// Return the value if the field exists, otherwise the default
return array_key_exists($field_name, $field_ids)
? $model->getFieldValue($field_ids[$field_name] , $article_id)
: $default_value;
}
Usage:
$some_field_value = getCustomFieldValue('some-field-name', $some_article_id);
Optimization: I placed the function into a helper class, implemented the variables $fields, $field_ids and $model static and checked if they are already loaded to prevent redundant loading of the same data.

Magento How to use translation on attribute label?

I use Magento and I need help to use in frontend the translation of an attribute label !
I use this on my marketplace.phtml to load the attribute label
<?php
$attribute = Mage::getModel('eav/config')->getAttribute('catalog_product', 'etat_verres');
$allOptions = $attribute->getSource()->getAllOptions(true, true);
foreach ($allOptions as $instance) { if($instance['label']) {
echo $instance['value'] // to show the value
echo $instance["label"] // to show the label
} }
?>
The problem is that Magento use Admin Value and not french value or english value.
Thanks in advance !
Sincerely yours,
John
Using the $this->__ is the core Magento helper which also contains the translation functionality, now assuming your module has extends the core Magento helper this will work. Now you can use a theme translate.csv file to translate your text.
<?php
$attribute = Mage::getModel('eav/config')->getAttribute('catalog_product', 'etat_verres');
$allOptions = $attribute->getSource()->getAllOptions(true, true);
foreach($allOptions as $instance)
{
if ($instance['label'])
{
echo $this->__($instance['value']) // to show the value
echo $this->__($instance["label"]) // to show the label
}
}
Also keep in mind, translating the "labels" should not be necessary as you can use the Magento admin store view translations within Catalog->Manage Attributes Select your attribute and manage attributes per store view, however, I'm not entirely sure of the context. While what I provided should work, having context will provide a better solution.

if title contains string 'aaa','bbb' or ,'ccc' replace field {category[1}

Hello gods of Stackoverflow,
Now i hate to be "that guy" who didnt search properly but i am running into a problem that i need a fix for and can't find a solution i can work with because of my lack in coding skills, my knowledge barely tickles the surface.
Here's the thing.
I am using a tool to import feeds into my website (WP all Import) as woocommerceproducts. But in the categorization the feed suppliers made errors which i want to tackle without emailing them everytime i stumble upon one.
i.e: the title contains words like satchel, bag, clutch etc but the product is categorized as 'jewellery > earrings' in the CSV or XML.
The import tool will ask me where to find the product category, i point it to the node {category[1]}
But when the category is missing or faulty i want it to check the title for certain words, and if present change the value of it to that found word.
something like:
[if ({title[1]}contains "satchel") {
category = "bags > satchel",
} else if ({title[1]} contains clutch) {
category = "bags > clutch",
} else {
category = {sub_category[1]} #the normal value if nothing was found
}]
I just can't find the pieces to put the formatting together. I might need to work towards a function that i could expand to generate categories based solely out of presence of certain words in the title but maybe when i get better that would be an option.
I hope i was able to provide a clear view on the problem. The "[ ]" is there because thats how the plugin wants code to be entered instead of a {fieldname[1]}, another example below:
The following was an example of a problem i was able to fix:
i needed to replace values like "0/3months/1/2months" to "0-3 months/1-2months" before i replaced the slash"/" with a pipe"|" for wordpress to recognize it as a seperate value.
[str_replace("/","|",
str_replace("0/3","0-3",
str_replace("1/2","1-2",
str_replace("3/6","3-6",{size[1]}))))]
The fields can also be used to call functions but only in the 'pro' version of the plugin.
Any help is very much appreciated, thanks in advance.
You could use strpos.
Example:
if (strpos($title, "satchel") !== false) {
$category = "bags > satchel";
}
So after an afternoon of poking around, testing stuff, and not knowing alot about php i came up with a solution with help from a friend.
Wp All Import does not allow custom php directly from the field itself, it does however support custom php functions and provides an editor for these on the bottom of the import configuration page. I did the following:
<?php
//Checks Title for keywords and
//uses those to create categories
//We are using our own Main categories so only
//sub and subsub categroies need to be created.
//Call function
[get_subcat_from_title({title[1]},{category[1]})]
//Function
function get_subcat_from_title($title,$defaultcat)
{
if (strpos($title,"Satchel") !== false) {
$cat = "Tassen";
} elseif (strpos($title,"Travel") !== false) {
$cat = "Tassen";
} elseif (strpos($title,"Gusset") !== false) {
$cat = "Tassen";
} else {
$cat = $defaultcat;
}
return $cat;
}
//Checks Title for keywords and uses those to create subcategories
//Call Function
[get_subsubcat_from_title({title[1]},{sub_category[1]})]
//Function
function get_subsubcat_from_title($title,$defaultcat)
{
if (strpos($title,"Satchel") !== false) {
$cat = "Satchel";
} elseif (strpos($title,"Travel") !== false) {
$cat = "Travel";
} elseif (strpos($title,"Gusset") !== false) {
$cat = "Gusset";
} else {
$cat = $defaultcat;
}
return $cat;
}
?>
On the Taxonomies, Tags, Categories option we can create our own hierarchical order like this:
[main category]
+[sub category]
++[sub sub category]
The main category field is given a name we use as our main category.
The sub category is filled with function SUBCAT
The subsub category is filled with function SUBSUBCAT
this way it will create a parent by our own name, a child that has the named 'Tassen' if any keyword is present, and a grandchild with the specific keyword as it's name.
This way i can expand the function using all kinds of statements when the right category isn't present in de provided feed.
thanks #sebastianForsberg for responding.
I hope this helps anyone who comes across a similar problem in the future..

Use Product Image as category Image in Virtuemart

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);
}

How to find out master product of simple product?

How can I find out, if a simple product is part of a configurable product and then get the master product? I need this for the product listing.
Just found out:
$_product->loadParentProductIds();
$parentIds = $_product->getParentProductIds();
Let's say that you have your simple product's Product ID.
To get all the parent configurable product IDs of this simple product, use the following code:-
<?php
$_product = Mage::getModel('catalog/product')->load(YOUR_SIMPLE_PRODUCT_ID);
$parentIdArray = $_product->loadParentProductIds()
->getData('parent_product_ids');
if(!empty($parentIdArray)) {
// currently in the master configurable product
print_r($parentIdArray); // this prints all the parent product IDs using your simple product.
}
?>
I suppose this should get you going.
For Magento 1.4.2 and above use the following method instead:
$configurable_product_model = Mage::getModel(‘catalog/product_type_configurable’);
$parentIdArray = $configurable_product_model->getParentIdsByChild($simple_product_id);
After version 1.4.2.0 the loadParentProductIds() and getParentProductIds() methods are deprecated. Don't ask me why. Personally I kind of liked those methods. So I've reintroduced them to my local Mage classes. This is how:
Copy
app/code/core/Mage/Catalog/Model/Product.php
to
app/code/local/Mage/Catalog/Model/Product.php
and change the loadParentProductIds() method, found around line 1349 to:
public function loadParentProductIds()
{
return $this->_getResource()->getParentProductIds($this);
}
This piece of code will query its resource for its parent product ids. For this to work we'll need to rewrite the getParentProductIds() method in the resource class.
So copy:
app/code/core/Mage/Catalog/Model/Resource/Eav/Mysql4/Product.php
to
app/code/local/Mage/Catalog/Model/Resource/Eav/Mysql4/Product.php
Find the deprecated getParentProductIds() method. Should be somewhere around line 535. Overwrite it with the pre 1.4.2.0 code:
public function getParentProductIds($object){
$childId = $object->getId();
$groupedProductsTable = $this->getTable('catalog/product_link');
$groupedLinkTypeId = Mage_Catalog_Model_Product_Link::LINK_TYPE_GROUPED;
$configurableProductsTable = $this->getTable('catalog/product_super_link');
$groupedSelect = $this->_getReadAdapter()->select()
->from(array('g'=>$groupedProductsTable), 'g.product_id')
->where("g.linked_product_id = ?", $childId)
->where("link_type_id = ?", $groupedLinkTypeId);
$groupedIds = $this->_getReadAdapter()->fetchCol($groupedSelect);
$configurableSelect = $this->_getReadAdapter()->select()
->from(array('c'=>$configurableProductsTable), 'c.parent_id')
->where("c.product_id = ?", $childId);
$configurableIds = $this->_getReadAdapter()->fetchCol($configurableSelect);
return array_merge($groupedIds, $configurableIds);
}
Now you once again can do this:
$_product->loadParentProductIds()->getData('parent_product_ids');
Hope this helps you out!

Categories