Magento - Get product name for all languages - magento

When reading all magento products for a export extension I've encountered a problem:
when trying to get the name of a product by using getName() on the loaded model you only get the active language name or if that is not set the default name of the product. But I need to get all product names for default, english, german, french, etc.
Does anyone have a solution for this problem or an idea how to solve it?
$model = Mage::getModel('catalog/product');
$collection = $model->getCollection();
foreach ($collection as $product) {
$id = $product->getId();
$model->load($id);
$name = $model->getName(); // gives you only the active language name / default name
}

Since you also want the default store, I'm only aware of one working way:
$aStoreHash = Mage::getModel('core/store')
->getCollection()
->setLoadDefault(true)
->toOptionHash();
$aName = array();
foreach ($aStoreHash as $iStoreId => $sStoreName) {
Mage::app()->setCurrentStore($iStoreId);
$oCollection = Mage::getModel('catalog/product')
->getCollection()
// Uncomment next line for testing if you have thousands of products
// ->addFieldToFilter('entity_id', array('from' => 1, 'to' => 5))
->addAttributeToSelect('name');
foreach ($oCollection as $oProduct) {
$aName[$oProduct->getId()][$iStoreId] = $oProduct->getName();
}
}
var_dump($aName);
If you don't need the default store, you could drop Mage::app()->setCurrentStore($iStoreId); and use ->addStoreFilter($iStoreId) on the collection instead.

Related

how to assign random product positions in Magento category?

I have the following issue in Magento 1.9: there are categories with a lot of products in them and the default sort order is by position and all product position in Magento backend is 1. So what happens is that when you open a category on the frontend a lot of similar products show first followed by another set of similar type of products. I want to randomize their positions somehow (by a script or anything else) so that different kind of products show mixed together.
For example I have categories wine,
champagne and whisky and products
in them and I also have category birthday products that includes products from these categories. And when the category is opened on the frontend first a lot of whisky products
are shown then a lot of wine ... etc I want them mixed. Thanks in advance for
any help!
You can do as below :
First get the category :
$category = Mage::getModel('catalog/category')
->setStoreId(Mage_Core_Model_App::ADMIN_STORE_ID)
->load($categoryId);
Then its product positions :
$products = $category->getProductsPosition();
This will be an array organized like this :
product_id_1 => position_1
product_id_1 => position_2
So foreach one of those products just set a random position (here between 0 and 9999) :
foreach($products as $productId => $position ){
$products[$productId] = '' . rand(0,9999);
}
And finally save :
$category->setPostedProducts($products);
$category->save();
Here is below a script that you could put in /shell magento directory :
<?php
require_once './abstract.php';
class RandomCategoryOrder extends Mage_Shell_Abstract {
private $_categoryId = 188;
public function run(){
$category = Mage::getModel('catalog/category')
->setStoreId(Mage_Core_Model_App::ADMIN_STORE_ID)
->load($this->_categoryId);
$products = $category->getProductsPosition();
foreach($products as $productId => $position ){
$products[$productId] = '' . rand(0,9999);
}
$category->setPostedProducts($products);
try{
$category->save();
}catch(Exception $e){
echo $e->getMessage();
}
}
}
$randowCategoryOrder = new RandomCategoryOrder();
$randowCategoryOrder->run();

Rewriting AutoSuggest (Minisearch) of Magento

I been trying for hours now to successfully rewrite Magento's build-in Autosuggest Function so it displays productnames instead of query history entries. I want nothing fancy, no product pictures and whatnot, just plain product name suggestions.
So to get the productnames, I created under app/code/local/Aw the folder CatalogSearch/Model and there created a file named Query.php. Inside that file I have the following class and rewritten method:
class Aw_CatalogSearch_Model_Query
extends Mage_CatalogSearch_Model_Query {
public function getSuggestCollection() {
$collection = $this->getData('suggest_collection');
if (is_null($collection)) {
$collection = Mage::getModel('catalog/product');
Mage::getSingleton('catalog/product_status')
->addVisibleFilterToCollection($collection);
$collection->getCollection()
->addAttributeToSelect('name')
->addAttributeToFilter('name', array('like' =>
'%'.$this->getQueryText().'%'))
->addExpressionAttributeToSelect('query_text', '{{name}}', 'name')
->addAttributeToSort('name', 'ASC')
->setPageSize(10)
->addStoreFilter($this->getStoreId());
$this->setData('suggest_collection', $collection);
}
return $collection;
}
};
I created the module xml file in app/etc/modules/ and the module configuration in app/code/local/Aw/CatalogSearch/etc/config.xml
All good so far, the overwritten method getSuggestCollection() is executed.
The problem comes in app/code/core/Mage/CatalogSearch/Block/Autocomplete.php, in the getSuggestData() method.
public function getSuggestData()
{
if (!$this->_suggestData) {
$collection = $this->helper('catalogsearch')->getSuggestCollection();
$query = $this->helper('catalogsearch')->getQueryText();
$counter = 0;
$data = array();
foreach ($collection as $item) {
$_data = array(
'title' => $item->getQueryText(),
'row_class' => (++$counter)%2?'odd':'even',
'num_of_results' => $item->getNumResults()
);
if ($item->getQueryText() == $query) {
array_unshift($data, $_data);
}
else {
$data[] = $_data;
}
}
$this->_suggestData = $data;
}
return $this->_suggestData;
}
When it iterates over the collection, I get a
Call to a member function getQueryText() on a non-object ...
The point I do not understand is that I have defined an alias field named 'query_text' in the collection query inside the getSuggestCollection() method. Even when I used something like getData('query_text') or $item->getQuery_text() to get the data of this field is not working.
I have the strong feeling, that the collection object is not valid as it supposed be within the getSuggestData() method of Mage_CatalogSearch_Block_Autocomplete class.
Can anybody point me out how to solve this issue? Is it not possible as above way to gather suggestions from the products collection and pass these to Autocomplete.php?
This is my first magento project, so please bear with me! I am really lost on this one!
Any hint is greatly apprecitated.
Using Magento 1.7.0.2 for this project.
Well, I found a solution. For anyone who might be interested in this, the problem stated in my question is located in the following lines
$collection = Mage::getModel('catalog/product');
Mage::getSingleton('catalog/product_status')
->addVisibleFilterToCollection($collection);
$collection->getCollection() ... // continue method chaining ...
I changed the code, so that the constructor and methods are chained all together, like this:
$collection = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToSelect('name') ... // continue method chaining
...
I added the filters for product_status, cataloginventory/stock and catalog/product_visibility with singleton calls right after the collection is available
In that way, everything works as expected.
For anyone else wanting to do something similar, I just rewrote app/code/core/Mage/CatalogSearch/Block/Autocomplete.php to my own module and made the search results query the sku and return product names. Your mileage may vary, however, my sku codes are sensible names rather than random digits so this worked for me.
public function getSuggestData()
{
if (!$this->_suggestData) {
$collection = $this->helper('catalogsearch')->getSuggestCollection();
$query = $this->helper('catalogsearch')->getQueryText();
$counter = 0;
$data = array();
foreach ($collection as $item) {
$_data = array(
'title' => $item->getQueryText(),
'row_class' => (++$counter)%2?'odd':'even',
'num_of_results' => $item->getNumResults()
);
if ($item->getQueryText() == $query) {
array_unshift($data, $_data);
}
else {
$data[] = $_data;
}
}
// Get products where the url matches the query in some meaningful way
$products = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('name')
->addAttributeToFilter('type_id', 'configurable')
->addAttributeToFilter('sku',array('like'=>'%'.$query.'%'))
->load();
foreach($products as $product) {
$_data = array(
'title' => $product->getName(),
'row_class' => (++$counter)%2?'odd':'even',
'num_of_results' => 1
);
// if ($item->Name() == $query) {
// array_unshift($data, $_data);
// }
// else {
$data[] = $_data;
// }
}
$this->_suggestData = $data;
}
return $this->_suggestData;
}
I did not need to rewrite Mage_CatalogSearch_Model_Query, just the code for the suggestions.

Magento wrong language in wishlist

I've a problem with the magento wishlist. My store has 4 diffrent languages (DE/EN/FR/IT).
All works great but in the wishlist the product name and description are displayed in the wrong language (in Italien) no matter if the store language is set to English, French etc.
I know there's a simliar thread here
Magento Not Translating Wishlist Product Name and Description
But the suggestion to remove $product = $this->_getData('product'); doesn't solve the problem. It only changes product name and description to the default language, which is German.
//SOLUTION//
I finally got it. I know it's not the most perfect solution but it works.
In /app/code/core/Mage/Wishlist/Model/Item.php at public function getProduct()
i removed this line $product = $this->_getData('product'); and added the following:
$store_id = Mage::app()->getStore()->getStoreId();
Then I changed: $product = Mage::getModel('catalog/product')
->setStoreId($this->getStoreId())
->load($this->getProductId());
to:
$product = Mage::getModel('catalog/product')
->setStoreId($store_id)
->load($this->getProductId());
Thanks for your solution. To avoid multiple product reload, I've changed that code to:
public function getProduct() {
$product = null;
$current_store_id = Mage::app()->getStore()->getStoreId();
if (!$this->getProductId()) {
Mage::throwException(Mage::helper('wishlist')->__('Cannot specify product.'));
}
if($this->_getData('last_store_id') != $current_store_id){
$product = Mage::getModel('catalog/product')
->setStoreId($current_store_id)
->load($this->getProductId());
} else {
$product = $this->_getData('product');
}
$this->setData('product', $product);
$this->setData('last_store_id', $current_store_id);
/**
* Reset product final price because it related to custom options
*/
$product->setFinalPrice(null);
$product->setCustomOptions($this->_optionsByCode);
return $product;}

Get attributes and its values using single Collection in Magento?

How to get attributes and its values using single Collection in Magento?
Right now i am using below
$attributesInfo = Mage::getResourceModel('eav/entity_attribute_collection')
->setEntityTypeFilter(4)
->addFieldToFilter('frontend_input','multiselect')
->addSetInfo()
->getData();
to get attribute and below code to get attribute value
$product = Mage::getModel('catalog/product');
$collection = Mage::getResourceModel('eav/entity_attribute_collection')
->setEntityTypeFilter($product->getResource()->getTypeId())
->addFieldToFilter('attribute_code', $attributeName);
My attributes code out put is like below
Color :
Black
Blue
Green
Brand :
Hp
Dell
Apple
Size :
12
14
16
Thanks,
Balan
How about this:
$attributes = Mage::getSingleton('eav/config')
->getEntityType(Mage_Catalog_Model_Product::ENTITY)
->getAttributeCollection()
->addFieldToFilter('source_model', array('notnull' => true))
->addSetInfo();
foreach ($attributes as $attribute)
{
echo "{$attribute->getFrontendLabel()}:\n";
foreach ($attribute->getSource()->getAllOptions() as $option)
{
echo " {$option['label']}\n";
}
echo "\n";
}
By using the eav/config and eav/entity_type chances are you will be reusing an already loaded collection, which of course is more efficient then reloading the same data in new collections.
EDIT: Updated the answer to include the attribute collection filter suggested by Aleksandr Ryabov.

Magento: Filter products by Status

I'm having some serious Magento issues here. As expected the following:
$products = Mage::getModel('catalog/category')->load($category_id)
->getProductCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('status', array('eq' => 1));
Will return all enabled products for my $category_id. However this:
$products = Mage::getModel('catalog/category')->load($category_id)
->getProductCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('status', array('eq' => 0));
Does not return disabled products. I can't seem to find a way to return disabled products, and I don't know why.
I've tried this:
Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($products);
Which was meant to have worked, but apparently may have been deprecated.
Does anyone know how to get all products in a category, enabled and disabled?
Don't worry, you simply got trapped by a very unusual constant definition^^. Just try:
$products = Mage::getModel('catalog/category')->load($category_id)
->getProductCollection()
->addAttributeToSelect('*')
->addAttributeToFilter(
'status',
array('eq' => Mage_Catalog_Model_Product_Status::STATUS_DISABLED)
);
For whatever reasons Varien decided to define this STATUS_DISABLED constant with a value of 2, instead of the more intuitive (and commonly used) value of 0.
I think you can do this by setting store to default like
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
make sure you save the current store value and set it back after doing the above.
Or by using a script from outside magento and invoke mage by
require_once '../app/Mage.php';
$app = Mage::app();
Mage::register('isSecureArea', true);
$products = Mage::getModel('catalog/category')->load($category_id)
->getProductCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('status', 1)
->addAttributeToFilter('visibility', 4)
->setOrder('price', 'ASC');
I haven't found an answer as such to my question above. But I have saved a lot of time by using a different method.
I exported a CSV of all the products in my Magento, deleted all columns except Category ID and SKU (this is all I needed), and then filtered that to return all the skus instead.
If it helps anyone here is the code -
<?php
$file = fopen('allprods.csv', 'r');
// You can use an array to store your search ids, makes things more flexible.
// Supports any number of search ids.
$id = array($_GET['id']);
// Make the search ids safe to use in regex (escapes special characters)
$id = array_map('preg_quote', $id);
// The argument becomes '/id/i', which means 'id, case-insensitive'
$regex = '/'.implode('|', $id).'/i';
$skus = array();
while (($line = fgetcsv($file)) !== FALSE) {
list($ids, $sku) = $line;
if(preg_match($regex, $ids)) {
$skus[] = $sku;
}
}
$count = count($skus);
$i = 1;
echo $category_id;
foreach ($skus as $sku){
echo $sku;
if($i != $count) { echo "`"; }
$i++;
}
This solution was created by using a previous topic about filtering CSVs, here
So for now, I can survive. however - an answer to this question is still needed!
Nothing works if catalog_flat_product is on in backend configuration->catalog.
try this..this will give all the products enabled and disabled ultimately
$collection = Mage::getResourceModel('catalog/product_collection'); //this will give you all products
foreach($collection as $col)
{
$var = Mage::getModel('catalog/product')->loadByAttribute('sku',$col->getSku());
echo"<pre>";print_r($var->getData());echo"</pre>";
}
its really simple and after this you can easily filter products by status

Resources