magento - get attribute option label by store view - magento

Like the title, how can I get the attribute option value of a specific store view instead of the current store view ?
What I am trying to implement is something like this :
public function getAttributeOptionValue($attributeCode, $attributeOptionLabel, $storeView)
The attributeOptionLabel is the current attribute option label.

Simple! Ref Mage_Eav_Model_Entity_Attribute::getStoreLabel() [link]:
<?php
include 'app/Mage.php';
Mage::app('default');
//Generic access
$eavConfig = Mage::getSingleton('eav/config');
/* #var $eavConfig Mage_Eav_Model_Config */
$eavAttribute = $eavConfig->getAttribute(
Mage_Catalog_Model_Product::ENTITY, // 'catalog_product'; see db.eav_entity_type
'description' // attribute code
);
/* #var $eavAttribute Mage_Eav_Model_Entity_Attribute */
Zend_Debug::dump(
$eavAttribute->getStoreLabel('admin')
);
//For a given EAV entity-based model, the resource requires only the attribute
$product = Mage::getModel('catalog/product')->load(2);
/* #var $product Mage_Catalog_Model_Product */
$productAttribute = $product->getResource()->getAttribute('description');
/* #var $productAttribute Mage_Eav_Model_Entity_Attribute */
Zend_Debug::dump(
$productAttribute->getStoreLabel('admin')
);
//It's also possible to get all labels:
Zend_Debug::dump(
$productAttribute->getStoreLabels()
);

Related

Joomla 3 Lis users in usergroup module

Anyone know of such a module?
Basically I want to dynamically load the users in certain usergroups inside an article with the loadmodule option.
Ended up building myself.
modfile:
<?php
defined('_JEXEC') or die;
// Include the latest functions only once
require_once __DIR__ . '/helper.php';
$shownumber = $params->get('shownumber', 10);
$groupnumber = $params->get('group', 4);
$names = ModUsersUsergroupHelper::getUsers($params);
$moduleclass_sfx = htmlspecialchars($params->get('moduleclass_sfx'), ENT_COMPAT, 'UTF-8');
require JModuleHelper::getLayoutPath('mod_users_usergroup', $params->get('layout', 'default'));
helper:
<?php
defined('_JEXEC') or die;
/**
* Helper for mod_users_usergroup
*
* #package Joomla.Site
* #subpackage mod_users_usergroup
*
* #since 1.6
*/
class ModUsersUsergroupHelper
{
/**
* Get users in a certain usergroup
*
* #param \Joomla\Registry\Registry $params module parameters
*
* #return array The array of users
*
* #since 1.6
*/
public static function getUsers($params)
{
$db = JFactory::getDbo();
$groupId = $params->get('group', 2);
$query = $db->getQuery(true)
->select($db->quoteName(array('u.id', 'u.name', 'u.username', 'u.registerDate')))
->order($db->quoteName('u.registerDate') . ' DESC')
->from('#__users AS u')
->join('INNER', '#__user_usergroup_map AS ugm ON ugm.user_id = u.id')
->where('ugm.group_id =' . $db->quote($groupId));
$db->setQuery($query, 0, $params->get('shownumber'));
try
{
return (array) $db->loadObjectList();
}
catch (RuntimeException $e)
{
JFactory::getApplication()->enqueueMessage(JText::_('JERROR_AN_ERROR_HAS_OCCURRED'), 'error');
return array();
}
}
}
I am not aware of such an extension but you could include some code in a Custom HTML module using Sourcerer or similar to achieve the desired result.
The Custom HTML module can then be displayed in an article using loadmodule.
For some example code see: https://stackoverflow.com/a/20743966

Creating categories and sub-categories in Magento Extension

I am new to Magento Extension Development and wondering which is the best way to create categories and sub-categories from within an extension. The Extension I am working on is synchronizing product-data from an ERP-System. The extension is operating with a System->Configuration Dialog which holds the data for the connection to the server (user/pwd/etc.) Now I am wondering, if it is better to connect via Ajax request or use a Soap call. Ajax seems very slow in this case for about 700 Products. So what do you suggest?
Furthermore, I am a little stuck by creating categories and sub-categories. Is there simple way to do that. I found some stuff on creating a category and then use the ->move() function. Moreover I am wondering if the 'path' of the category is essential on creating sub-categories.
You should use magento models:
Create category with subcategory:
/**
* After installation system has two categories: root one with ID:1 and Default category with ID:2
*/
/** #var $category1 Mage_Catalog_Model_Category */
$category1 = Mage::getModel('catalog/category');
$category1->setName('Category 1')
->setParentId(2)
->setLevel(2)
->setAvailableSortBy('name')
->setDefaultSortBy('name')
->setIsActive(true)
->setPosition(1)
->save();
/** #var $category2 Mage_Catalog_Model_Category */
$category2 = Mage::getModel('catalog/category');
$category2->setName('Category 1.1')
->setParentId($category1->getId()) // set parent category which was created above
->setLevel(3)
->setAvailableSortBy('name')
->setDefaultSortBy('name')
->setIsActive(true)
->setIsAnchor(true)
->setPosition(1)
->save();
public static function addCatalogCategory($item, $id, $storeId = 0) {
/*
* resource for checking category exists
* http://fishpig.co.uk/blog/load-a-category-or-product-by-an-attribute.html
*/
$categories = Mage::getResourceModel('catalog/category_collection');
// Select which fields to load into the category
// * will load all fields but it is possible to pass an array of
// select fields to load
$categories->addAttributeToSelect('*');
// Ensure the category is active
$categories->addAttributeToFilter('is_active', 1);
// Add Name filter
$categories->addAttributeToFilter('name', $item->GROUP_NAME);
// Limit the collection to 1 result
$categories->setCurPage(1)->setPageSize(1);
// Load the collection
$categories->load();
if ($categories->getFirstItem()->getId()) {
$category = $categories->getFirstItem();
return $category->getId();
}
/* get category object model */
$category = Mage::getModel('catalog/category');
$category->setStoreId($storeId);
$data = array();
/* if the node is root */
if (Heliumv_Synchronization_Helper_Data::xml_attribute($item, 'type') == 'root') {
$data['category']['parent'] = 2; // 2 top level id
} else {
/* is node/leaf */
$data['category']['parent'] = $id;
}
$data['general']['path'] = $item->PARENT_ID;
$data['general']['name'] = $item->GROUP_NAME;
$data['general']['meta_title'] = "";
$data['general']['meta_description'] = "";
$data['general']['is_active'] = "1";
$data['general']['url_key'] = "";
$data['general']['display_mode'] = "PRODUCTS";
$data['general']['is_anchor'] = 0;
/* add data to category model */
$category->addData($data['general']);
if (!$category->getId()) {
$parentId = $data['category']['parent'];
if (!$parentId) {
if ($storeId) {
$parentId = Mage::app()->getStore($storeId)->getRootCategoryId();
} else {
$parentId = Mage_Catalog_Model_Category::TREE_ROOT_ID;
}
}
$parentCategory = Mage::getModel('catalog/category')->load($parentId);
$category->setPath($parentCategory->getPath());
}
$category->setAttributeSetId($category->getDefaultAttributeSetId());
try {
$category->save();
return $category->getId();
} catch (Exception $e) {
echo Mage::log($e->getMessage());
}
}
I hope this helps someone. cheers

Using event sales_order_place_after doesn't return custom product attributes in magento

I try to get the products which have been bought.
This is my code:
/** #var $order Mage_Sales_Model_Order */
$order = $eventObserver->getOrder();
/** #var $items Mage_Sales_Model_Resource_Order_Collection */
$items = $order->getItemsCollection(array(), TRUE);
/** #var $item Mage_Sales_Model_Order_Item */
foreach($items as $item) {
$product = $item->getProduct();
var_dump($product->getData('language'));
}
Language is a custom attribute. In this case it is empty, and I have no idea why. All default attributes, like name, id or sku are working.
This language is used as configurable attribute.
What have I to do, to get the value?
Try this:
$items = $order->getAllVisibleItems()
Got it!
When I take the product ID and load the product again:
$product = $item->getProduct();
$product = Mage::getModel('catalog/product')->load( $product->getId() );
I get the language as number.

Retrieve default product image without product - Magento

I would like to retrieve the default product thumbnail in Magento to apply it to something else other than a product, so I don't have access to $product. Would it be possible?
Thanks,
Krt_Malta
Untested but this should work:
/**
* Get the resource model
*/
$resource = Mage::getSingleton('core/resource');
/**
* Retrieve the read connection
*/
$readConnection = $resource->getConnection('core_read');
$query = 'SELECT thumbnail FROM ' . $resource->getTableName('catalog/product_flat') . ' WHERE sku = "(insert your product SKU here)"'; // Insert SKU here
/**
* Execute the query and store the results in $results
*/
$results = $readConnection->fetchAll($query);
/**
* Print out the results
*/
echo sprintf('<pre>%s</pre>' print_r($results, true));

How to print collection mysql query in magento

Let's say I have a collection like:
$products = Mage::getModel('catalog/product')
->getCollection()
...
->load();
How do I print the actual MySQL code that gets executed?
You can always view your sql query at a certain point by echoing getSelect as shown:
$products = Mage::getModel('catalog/product')
->getCollection();
echo $products->getSelect();
To change query parameters you want to check out methods like:
$products->addAttributeToSelect('someattribute');
$products->addAttributeToFilter('someattribute', array('eq'=>'1'));
You can print collection using below code:
We can print query of collection using getSelect()->__toString()
$products = Mage::getModel(‘catalog/product’)
->addAttributeToFilter(‘status’, array(‘eq’ => 1));
echo $products->getSelect()->__toString();
Have you seen http://kuldipchudasama.wordpress.com/2012/07/16/magento-print-query-of-collection/?
This works well.
Most other answers here say that $products->getSelect() will do it - this is fine if all you're going to do with it is echo, but in fact getSelect() doesn't just return a string, it returns a Varien_Db_Select object.
Invoking echo on that object automatically triggers its __toString() method, so you just get the SQL string, but try passing it to Mage::log() and you'll get a lot more than you expected.
If you just want to log the SQL, you can use:
Mage::log($products->getSelect()->__toString());
Or how about using the object's own:
$products->printLogQuery(false, true); // don't echo, do log
printLogQuery is defined in lib/Varien/Data/Collection/Db.php.
You can print
$products->getSelect()->assemble();
I work with collections every day. This is without a doubt the correct way.
echo $collection->getSelectSql(true);
If you simple set the first parameter of ->load() to true, like so:
$products = Mage::getModel('catalog/product')
->getCollection()
...
->load(true);
In Magento 2:-
namespace <Company>\<Module>\Block\Adminhtml\Tab\Log;
class Grid
extends \Magento\Backend\Block\Widget\Grid\Extended
{
protected $_collectionFactory;
/**
* Constructor
*
* #param \Magento\Backend\Block\Template\Context $context
* #param \Magento\Backend\Helper\Data $backendHelper
* #param \<Company>\<Module>\Model\ResourceModel\Log\CollectionFactory $collectionFactory
* #param Psr\Log\LoggerInterface $logger
* #param array $data
*/
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\<Company>\<Module>\Model\ResourceModel\Log\CollectionFactory $collectionFactory,
\Psr\Log\LoggerInterface $logger,
array $data = []
) {
$this->_logger = $logger;
$this->_collectionFactory = $collectionFactory;
parent::__construct($context, $backendHelper, $data);
}
/**
* {#inheritdoc}
*/
protected function _prepareCollection()
{
$collection = $this->_collectionFactory->create();
$this->_logger->info($collection->getSelect()->__toString());
$this->setCollection($collection);
return parent::_prepareCollection();
}
}
And remember that the collection factory is a magic class that can attaches to every class as Magento 1 wasn't complicated enough.
Step 1-
$result_colletion = print_r($collection->getSelect());
Mage::log($$result_colletion, null, custom_collection.log,true);
Step 2-
After that Login into magento admin section and enable to log setting . Please see below .
System > Configuration > Developer > Log Settings
Step 3-
After that see the log file custom_collection.log in var/log/ folder .
Try following code.
$products = Mage::getModel('catalog/product')
->getCollection();
echo $products->getSelect();

Resources