Create Magento attribute option multilingual programmatically - magento

i am searching for a way to create magento attribute options multilingual, for more than one language.
Let's say i do have store view name 'german' and 'english'.
I do retrieve the store language codes with (the languages must be set each on the store view configuration pages):
$storelist = Mage::app()->getStores();
$storelang = array();
foreach ($storelist as $id => $s) {
$storelang[$id] = substr(Mage::getStoreConfig('general/locale/code', $id), 0, 2);
}
This way i do create attribute options (the attributes do exist already):
function addAttributeValue($arg_attribute, $arg_value) {
$attribute_model = Mage::getModel('eav/entity_attribute');
$attribute_code = $attribute_model->getIdByCode('catalog_product', $arg_attribute);
$attribute = $attribute_model->load($attribute_code);
if (!attributeValueExists($arg_attribute, $arg_value)) {
$value['option'] = array($arg_value, $arg_value);
$result = array('value' => $value);
$attribute->setData('option', $result);
$attribute->save();
echo "Attribute '" . $arg_attribute . "' with
option '" . $arg_value . "' saved.<br />";
}
But where does the 2nd language come to play? Right now only the default value/default value gets filled into the database.
I would like to prepare a loop for each language, but i do not know the right "switch" for the language.
When creating products, not attribute options, there is a method so set all product fields according to the language with
$Product->setStoreId($lang_value);
but i am not sure about this on attribute options.
Can you guys give me a hint?
Thanks.

Problem solved. Thanks to Marius for pointing out my messed up array.
This line was wrong:
$value['option'] = array($arg_value, $arg_value);
Set it to something like:
$value['option'] = array($arg_value_label, $arg_value_lang1, $arg_value_lang2);
Now i am able to load the the values for each language and set them with that single line above. Maybe this is not the best solution, but it works for me at the moment.
Have a nice weekend everyone.

Related

How to pass an array to a view as Contextual Filter

I am new in Drupal. I am currently developing an e-commerce site using drupal 7. I want to know how can i pass an array of nid to views_embed_view('view_name','display_name',contextual filter) contextual filters. Here is my sample code-
foreach($result as $record)
{
$querystring .= "+";
$querystring .= $record->nid;
}
$querystring = ltrim($querystring, '+');
views_embed_view('tours_listings', 'page_2',$querystring);
You can add accomplish this by:
Checking the
Allow multiple values on the view contextual settings page.
If selected, users can enter multiple values in the form of 1+2+3. Due
to the number of JOINs it would require, AND will be treated as OR
with this filter.
Then instead of code above:
$recordIds = array();
foreach($result as $record)
{
$recordIds[] = $record->nid;
}
$querystring = implode('+', $recordIds);
//Do not forget to print this out.
print views_embed_view('tours_listings', 'page_2', $querystring);

Magento Admin Create Order not showing Custom Options

I have simple products with custom options in my store. They work perfectly from the front end, but if I try to add an order from the admin section, The custom options do not show up.
I only have this problem if the type of custom option is a dropdown, multi select, radio buttons, or check boxes. If it is a text field, date or anything else, it works fine.
I am assumming i need to make some changes to something in the /www/app/design/adminhtml/default/default/template/sales/order/create area, but no clue what i should try.
Looking a bit further, I found this /www/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Items/grid.php
/**
* Get Custom Options of item
*
* #param Mage_Sales_Model_Quote_Item $item
* #return array
*/
public function getCustomOptions(Mage_Sales_Model_Quote_Item $item)
{
$optionStr = '';
$this->_moveToCustomerStorage = true;
if ($optionIds = $item->getOptionByCode('option_ids')) {
foreach (explode(',', $optionIds->getValue()) as $optionId) {
if ($option = $item->getProduct()->getOptionById($optionId)) {
$optionValue = $item->getOptionByCode('option_' . $option->getId())->getValue();
$optionStr .= $option->getTitle() . ':';
$quoteItemOption = $item->getOptionByCode('option_' . $option->getId());
$group = $option->groupFactory($option->getType())
->setOption($option)
->setQuoteItemOption($quoteItemOption);
$optionStr .= $group->getEditableOptionValue($quoteItemOption->getValue());
$optionStr .= "\n";
}
}
}
return $optionStr;
}
The best way to find the correct template path is to turn on admin template hints.
By default magento does not provide a way to accomplish from the admin, but you can easily accomplish this using one of these methods Enable template path hint in admin pages - Magento

Magento mass-assign products to category

As the title says,i need to mass-assign products to a category and from the admin i can only edit one product at a time; i dont know why it just doesnt work to mass add them from the "category products" tab in the category page.
Thats why i need another method that's fast,like using phpMyAdmin or something alike.
Any help?
Thanks in advance!
I created a simple script to do this outside of Magento. Be sure to test this first on a single product and make sure it looks as you'd expect.
// Load Magento
require_once 'path/to/app/Mage.php';
Mage::app();
// $productIds is an array of the products you want to modify.
// Create it however you want, I did it like this...
$productsIds = Mage::getModel('catalog/product')->getCollection()
->addAttributeToFilter('sku', array('like' => 'something'))
->getAllIds();
// Array of category_ids to add.
$newCategories = array(20);
foreach ($productIds as $id) {
$product = Mage::getModel('catalog/product')->load($id);
$product->setCategoryIds(
array_merge($product->getCategoryIds(), $newCategories)
);
$product->save();
}
If you wish to overwrite a product's existing categories, change array_merge(...) to just $newCategories.
I would shy away from tackling this problem from the database side of things. If you do go that direction make sure and take lots of backups and do it during low usage.
The following thread on the Magento forum identifies the very same problem. One poster recommends a raw sql approach with example. Again, I would be careful - make sure you take backups.
The answer I like best from the thread (posted by Magento MVP):
Go into the category you don’t want them in, find the product list.
Click the check boxes on the products you want to remove and select
delete from the little dropdown.
Now go into the category where you
do want them, go to the product list. Select the NO dropdown so it
shows items not in the category. You might have to do a selective
search to limit stuff and do it in a couple iterations. Click the
check boxes and tell it to add stuff.
You may as well do this using the magento API
This is the script I use for mass adding products. sku.txt contains one sku per line.
<?php
$wsdlUrl = "magento-root/index.php/api/soap/?wsdl";
$proxy = new SoapClient($wsdlUrl);
$sessionId = $proxy->login('apiuser', 'apipasswd');
$listOfDiscountedSKUFile = "sku.txt";
function readinFile($filePath)
{
$fp = fopen($filePath,'r') or exit("Unable to open file!");
$dataItems = array();
while(!feof($fp))
{
$dataItems[] = trim(fgets($fp));
}
fclose($fp);
var_dump($dataItems);
return $dataItems;
}
function addToCategory($sku,$categoryId)
{
global $proxy,$sessionId;
$proxy->call($sessionId, 'category.assignProduct', array($categoryId, $sku));
}
function IsNullOrEmptyString($question){
return (!isset($question) || trim($question)==='');
}
$categoryId = 82;//e.g.
$listOfSKU = readinFile($listOfDiscountedSKUFile);
foreach($listOfSKU as $sku)
{
addToCategory($sku,$category);
}
?>
I managed to resolve the problem with the following code :
$write = Mage::getSingleton('core/resource')->getConnection('core_write');
$x = 1171;
$y = 2000;
$categoryID = 4;
$productPosition = 0;
while($x <= $y) {
$write->query("REPLACE INTO `catalog_category_product` (`category_id`, `product_id`, `position`) VALUES ($categoryID, $x++, $productPosition)");
}
echo "The job is done";
?>
I hope the code is clear for everyone,if it's not,reply and i'll try to explain it.
#nachito : here it is.

How to Get Global Article Parameters in Joomla?

I'm programming a module in Joomla! 2.5. The module displays an article at a given position.
I need article attributes (i.e. show_title, link_title ecc.)
With this code I get article's specific attributes:
$db =& JFactory::getDBO();
$query = 'SELECT * FROM #__content WHERE id='.$id.' AND state=1';
$db->setQuery($query);
$item = $db->loadObject();
$attribs = json_decode($item->attribs, true);
If i var_dump the $attribs variable I get:
array(26) {
["show_title"]=>
string(0) ""
["link_titles"]=>
string(0) ""
[...]
}
The variable $attribs represents the article's specific attributes. When an element is set to "" means "use the global configuration".
I can get the global configuration with this query:
SELECT params from #__extensions where extension_id=22;
Where 22 is the id of the com_component extension. Then I can merge the results here with the results for the specific article.
BUT is there an easy way to achieve this? Does Joomla! have a specific class in the framework for this?
I would start with loading the model for articles:
// Get an instance of the generic articles model
$model = JModel::getInstance('Article',
'ContentModel',
array('ignore_request' => true));
The get the specific article...
$model->getItem($id)
To get a components global params I believe you can use:
$params = &JComponentHelper::getParams( 'COMPONENT_NAME' );
In your case you would need something like:
jimport('joomla.application.component.helper'); // load component helper first
$params = JComponentHelper::getParams('com_content');
I would suggest you look at the code of the article modules that ship with Joomla! 2.5.x as they do a lot of similar things to what you're trying to create. You can also have a read of this article, it's a bit dated but I think it still mostly holds true (except for jparams being replaced by jforms).

Programmatically change product attribute at store view level

I'm sorry if this question is trivial but I've been struggling to find what I am doing wrong here. I am trying to change the value of an attribute on a store view level but the default is also changed whereas it shouldn't be. Of course, this attribute is set up to be "store-view-scoped". To keep it simple, I've tried with the product name. No success.
Below are unsuccessful tests I've tried...
Do you see what I am doing wrong here?
Many thanks.
My tries :
$product = Mage::getModel('catalog/product')->load(PRODUCT_ID);
$product->setStoreId(STORE_ID)->setName('new_name')->save();
$product = Mage::getModel('catalog/product')->load(PRODUCT_ID);
$product->setStoreId(STORE_ID)->setStore(STORE_CODE)->setName('new_name')->save();
$product = Mage::getModel('catalog/product')->load(PRODUCT_ID);
$product->setStoreId(STORE_CODE)->setName('new_name')->save();
$product = Mage::getModel('catalog/product')->setStoreId(STORE_ID)->load(PRODUCT_ID);
$product->setName('new_name')->save();
$product = Mage::getModel('catalog/product')->setStoreId(STORE_ID)->load(PRODUCT_ID);
$product->setStoreId(STORE_ID)->setName('new_name')->save();
I even tried by adding the line below before the product model load...
Mage::app()->setCurrentStore(STORE_ID);
So here is the complete snippet to change attribute value for a specific product attribute on a specific store view. Example with the product name :
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$product = Mage::getModel('catalog/product')->load(PRODUCT_ID);
$product->setStoreId(STORE_ID)->setName('my_new_product_name')->save();
And as an additional answer, one could be interested in changing the attribute value to the default one. In this case, the argument 'false' must be passed to the setAttribute :
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$product = Mage::getModel('catalog/product')->load(PRODUCT_ID);
$product->setStoreId(STORE_ID)->setName(false)->save();
You need to set the current store to admin at the top of your code block:
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
note when loading product with data for some store view, also default values get loaded. saving such product will save default values as store values (thus unset "Use Default Value" for fields)
i ended up with following function to clean-up product data from default values
public static function _removeDefaults($item) {
static $attributeCodes = null;
if($attributeCodes == null) {
$attributes = Mage::getSingleton('eav/config')
->getEntityType(Mage_Catalog_Model_Product::ENTITY)->getAttributeCollection();
$attributeCodes = array();
foreach($attributes as $attribute) {
$ac = $attribute->getAttributeCode();
if(in_array($ac, array('sku','has_options','required_options','created_at','updated_at','category_ids'))) {
continue;
}
$attributeCodes[] = $ac;
}
}
foreach($attributeCodes as $ac) {
if(false == $item->getExistsStoreValueFlag($ac)) {
$item->unsetData($ac);
}
}
}
remember to send only product loaded for some store view

Resources