update the frontend label of an attribute in magento programmatically? - magento

I have an attribute with some attribute front end label.But I want to change frontendlabel for the product.Is there any function provided in magento to do this programmatically.
If yes,How can this be done???
Thank you,

The safest way to do that is to load the existing labels and then add your new store specific labels:
1 - retrieve the existing labels for all the stores
Mage::getModel('eav/entity_attribute')->getResource()
->getStoreLabelsByAttributeId($attributeId);
or
$attribute = Mage::getModel('catalog/resource_eav_attribute')->load($attributeId);
$labels= $attribute->getStoreLabels();
2 - Add your custom labels
$labels[$storeId] = 'My new label for a specific store';
$attribute->setStoreLabels($labels)->save();

If you want to set up frontend store labels for each store views, you can do it next way(This code for custemer attribute, but you can set frontend labels this way for all type of EAV-attributes.):
$installer->startSetup();
$attribute = array(
'entity_type' => 'customer',
'code' => 'customer_type_id',
'translations' => array(
'store_code_en_en' => 'english name',
'store_code_at_de' => 'german name',
'store_code_fr_fr' => 'franch name'
)
);
$storeLabels = array();
foreach ($attribute['translations'] as $storeViewCode => $text) {
$storeViewId = Mage::getModel('core/store')->load($storeViewCode, 'code')->getId();
$storeLabels[$storeViewId] = $text;
}
$attributeId = $installer->getAttributeId($attribute['entity_type'], $attribute['code']);
Mage::getSingleton('eav/config')->getAttribute($attribute['entity_type'], $attributeId)
->setData('store_labels', $storeLabels)
->save();
$installer->endSetup();

I found the more simpler solution to my question...
$attributeId = Mage::getModel('eav/entity_attribute')->getIdByCode('catalog_product', 'ATTRIBUTE_CODE');
$attribute = Mage::getModel('catalog/resource_eav_attribute')->load($attributeId);
$attribute->setFrontendLabel($displayName)->save();
setFrontendLabel(string $str) is the function which best suits here.

Related

Set Product Custom Options From Observer Magento 1.9

I am trying to add custom options to products on save. I want to add or update custom options (not additional options) on before_product save. I am able to access the observer and it is working on save as well but unable to update the custom options. Create option code is working if run from standalone script but not from observer only.
This is my observer code
`class Company_Module_Model_Observer{
public function updateOptions($observer){
$product = $observer->getEvent()->getProduct();
$categories= $product->getCategoryIds();
$currentCategory = '';
foreach ($categories as $cat_id){
$cat = Mage::getModel('catalog/category')->load($cat_id);
$currentCategory = $cat->getName();
}
$skuList =['LAPTOP_','DESKTOP_'];
$upgrades = $optionValues = [];
if($currentCategory=='Laptops'){
$_productCollection = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToFilter('sku', array('like' => 'LAPTOP_%'));
$upgrades = $_productCollection;
}
$meta = "6 this is product meta with custom plugin ".$product->getName();
foreach ($upgrades as $products) {
$_product = Mage::getModel('catalog/product')->load($products->getId());
$optionValues = array(
'title' => $_product->getName(),
'price' => $_product->getPrice(),
'price_type' => 'fixed',
'sku' => $_product->getSku(),
'sort_order' => 0,
);
}
$options = array(
'title' => 'Upgrades',
'type' => 'drop_down',
'is_required' => 0,
'sort_order' => 0,
'values' => $optionValues
);
$product->setMetaDescription($meta);
$product->setProductOptions(array($options));
$product->setCanSaveCustomOptions(true);
//if uncomment this then save loop continues and site hangs
//$product->save();
}
}`
No error in logs or anything else. Please guide me how I can achieve this.
You are in an infinite loop because the observer relaunches the same function each time, so when you run the save product function ( $product->save(); ), your function is rerun, and so on.
If you use the event catalog_product_save_before observer, you don't have to run the save function.
otherwise here:
foreach ($categories as $cat_id){
$cat = Mage::getModel('catalog/category')->load($cat_id);
$currentCategory = $cat->getName();
}
You get the last category in the collection, is that correct?
I know this is a bit late, but I had a similar issue like this a while back...
You are calling $product->setProductOptions() which without knowing your code I can only guess is setting it on the $product's _data array, which is probably not what you want. You need to stick it on the $product's option instance which will be used during the $product->_afterSave() call (You can see where the custom options are being saved in Mage_Catalog_Model_Product _afterSave() (~line 554 as of 1.9.4.5)). You can get the option instance like this: $optionInstance = $product->getOptionInstance() and set your options like this: $optionInstance->addOption($options). After you do that you should be able to allow the save to continue and your custom options should be created.

Save TCA changes in TYPO3 on select box

I created I new field in my TCA. I want to list all articles and select one, to set the article as top-article.
The articles have a UID and the database a column called istoparticle.
tx_vendor_domain_model_article is the table with all infos of the article.
I added a TCAcolumn.
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addTCAcolumns('tt_content', array(
'tx_test_istoparticle' => array(
'exclude' => 1,
'onChange' => 'reload',
'label' => 'Top Article',
'l10n_mode' => 'exclude',
'config' => array(
'type' => 'select',
'itemsProcFunc' => \Vendor\MyArticles\Hooks\Backend\Preview\ArticleRenderer::class . '->getArticleTitle',
)
),
));
With a userfunction
public function getTopArticles($param){
$pid = $param['row']['pid'];
$articles = $this->getArticles($pid);
foreach ($articles as $article) {
$record = BackendUtility::getRecord('tx_vendor_domain_model_article', $article->getUid());
$title = $record['header'];
$param['items'][][] = $title;
}
}
BTW:$record has all infos that I need, UID, bodytext and so on. But I can only store the header in the array!?
Now I got all the titles listed in my selectbox in the backend.
What do I have to do, to save my toparticle If I select an article in the backend?
Is there a onChange method for the TCA? And how can I get the infos like the Uid if I select one?
Items in TCA configuration should have at least two elements - first one is the label and second is the value. There are more options, but I think not needed in your case. You can read about them here: https://docs.typo3.org/typo3cms/TCAReference/8.7/ColumnsConfig/Type/Select.html#items
It means your usefFunc should look like that:
public function getTopArticles(&$param){
$pid = $param['row']['pid'];
$teasers = $this->getArticles($pid);
foreach ($articles as $article) {
$record = BackendUtility::getRecord('tx_vendor_domain_model_article', $article->getUid());
$param['items'][] = [
$record['header'],
$record['uid'],
]
}
}
And yes, there is onChange functionality in TCA:
https://docs.typo3.org/typo3cms/TCAReference/8.7/Columns/Index.html?highlight=onchange#onchange
If you are using older TYPO3 than 8.6 you would need to look for requestUpdate according to: https://docs.typo3.org/typo3cms/extensions/core/8.7/Changelog/8.6/Deprecation-78899-TCACtrlFieldRequestUpdateDropped.html

Woocommerce Filter Product by Attribute

I've been searching for many blogs and forum but this seems not yet answered yet. So i am trying to find a way how to filter product by attribute. I am using ajax to pull data and append it.The question is what will be the query to make a loop depend on what attribute.
Example.
Product A has Color:Blue,Red,Green and has a brand : BrandA , BrandB Product B has Color:Pink,Red,black.
All i want is to get all product with an attribute of Color [red and green] and Brand [BrandA] in a single query without using any plugin.
Here my code in my functions.php
function advanced_search(){
$html = "";
$args = array( 'post_type' => 'product','product_cat' => 'yarn');
$loop = new WP_Query( $args );
while ( $loop->have_posts() ){
$loop->the_post();
ob_start();
get_template_part( 'templates/part', 'search-result' );
$html = ob_get_contents();
ob_end_clean();
}
wp_send_json(array( "product_id" => $product_id , "html" => $html ));
}
add_action('wp_ajax_get_advanced_search', 'advanced_search');
add_action('wp_ajax_nopriv_get_advanced_search', 'advanced_search');
I dont know where should i put the product attributes in my query. I hope anyone found an answer for this.Thank you very much.
You should be able to achieve what you're looking to do by using a tax_query combined with your WP_Query. Attached is a small example using a 'Brand' attribute and the 'EVGA' term inside it (which WooCommerce will turn into 'pa_brand' - product attribute brand).
$query = new WP_Query( array(
'tax_query' => array(
'relation'=>'AND',
array(
'taxonomy' => 'pa_brand',
'field' => 'slug',
'terms' => 'evga'
)
)
) );
You can find some more documentation on the above links to string a few tax queries together for additional filtering and functionality.

Creating configurable products programmatically - pricing_value not saved

I have a custom xml file and I make a massive import of the products. I have some simples products under configurables ones. All is working well, configurable products are created with the simple products the "associated products" tab but one last thing still doesn't work : the price of each product.
Actually, Each simple product has its own price and the correct value is well saved in its attribute but in the "super product attribute configuration" panel, the values are empty.
When I fill the price fields manually, it works but it obviously must be done by the script, programmatically.
Here is my function to create the configurable product :
protected function createConfigurableProductFromSimpleProduct($product, $flagshipID)
{
$configurableProduct = $product->duplicate();
$configurableProduct->getResource()->save($configurableProduct);
$configurableProduct= Mage::getModel('catalog/product')->load($configurableProduct->getId());
$configurableProduct->setTypeId(Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE)
->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH)
->setSku($flagshipID)
->setDefRef($product_id)
->getTypeInstance()->setUsedProductAttributeIds(array($this->getAttributeId('root_colors'))); //attribute ID of attribute 'root_colors' in my store
$configurableProduct->setName($configurableProduct->getName());
$configurableProduct->setStatus(1);
$configurableProduct->setStockData(array(
'is_in_stock' => 1
));
$configurableProduct->setUrlKey($configurableProduct->getName());
$configurableProduct->save();
return $configurableProduct;
}
And here is the code for linking simple products to this configurable product :
protected function linkSimpleProductsToConfigurableProduct($simpleProducts, $configurableProduct)
{
$configurableProductsData = array();
foreach ($simpleProducts as $_product) {
$_product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE);
$_product->getResource()->save($_product);
$configurableProductsData[$_product->getId()] = array( //[id] = id of a simple product associated with this configurable
'0' => array(
'label' => $this->getAttributeRawValue($this->getAttributeId('root_colors'), $_product->getRoot()), //attribute label
'attribute_id' => $this->getAttributeId('root_colors'), //attribute ID of discriminator attribute in my store
'value_index' => $_product->getColor(),
'pricing_value' => $_product->getPrice(),
'is_percent' => '0'
)
);
}
$configurableAttributesData = $configurableProduct->getTypeInstance()->getConfigurableAttributesAsArray();
$configurableProduct->setCanSaveConfigurableAttributes(true);
$configurableProduct->setConfigurableAttributesData($configurableAttributesData);
$configurableProduct->setConfigurableProductsData($configurableProductsData);
var_dump('saving configurable product after having link some simple products');
$configurableProduct->save();
}
Any help is welcome, thank you !
Hy all! After reading thousand of answer i solved it!
$cProduct->setCanSaveConfigurableAttributes(true);
$cProduct->setCanSaveCustomOptions(true);
$cProductTypeInstance = $cProduct->getTypeInstance();
$cProductTypeInstance->setUsedProductAttributeIds(array($attribute_id));
$attributes_array = $cProductTypeInstance->getConfigurableAttributesAsArray();
foreach($attributes_array as $key => $attribute_array) {
$attributes_array[$key]['use_default'] = 0;
$attributes_array[$key]['position'] = 0;
if (isset($attribute_array['frontend_label'])) {
$attributes_array[$key]['label'] = $attribute_array['frontend_label'];
} else {
$attributes_array[$key]['label'] = $attribute_array['attribute_code'];
}
}
$dataArray = array();
foreach ($simpleProducts as $simpleArray) {
$dataArray[$simpleArray['id']] = array(
"label" => $simpleArray['label'],
"attribute_id" => $simpleArray['attr_id'],
"value_index" => $simpleArray['value'],
"is_percent" => '0',
"pricing_value" => $simpleArray['price']
);
}
// MAIN MOD! Here i prepare an array for attributesData.
$valuesArray = array();
foreach($dataArray as $data){
$valuesArray[] = $data;
}
// MAIN MOD!
// this is not the best, but in my case I've only one attribute.
$attributes_array[0]['values'] = $valuesArray;
$cProduct->setConfigurableProductsData($dataArray);
$cProduct->setConfigurableAttributesData($attributes_array);
I dont post all the codes, but i see that with these little modification it solve the problem!
I'm having the exact same issue and suspect this is due to something in Magento 1.9. I've tried a couple of code workarounds, but none of them work yet. Hmm, same bummer as you are suffering from.
Instead of providing further comments, I'll just provide an answer instead ;)
I digged into this a little bit deeper and found that the setConfigurableProductsData() call is designed to set product information, but the flag "pricing_value" simply does not work (at least it doesn't work in Magento 1.9). The call is only used to identify the Simple Products that are part of this Configurable Product. Instead the setConfigurableAttributesData() call needs to be used to define the relationship between Simple Products and pricing.
The following code worked for me: It moves the definition of specific option values (identified with value_index) with specific prices (pricing_value) as part of the attribute-data and not the product-data.
$configurableAttributeSizeValues = array();
foreach($simpleProducts as $simpleProduct) {
$configurableAttributeSizeValues[] = array(
'label' => $simpleProduct->getAttributeText('size'),
'value_index' => $simpleProduct->getSize(),
'is_percent' => false,
'pricing_value' => $simpleProduct->getPrice(),
);
}
$configurableAttributeSize = array(
'id' => null,
'label' => 'Size',
'frontend_label' => 'Size',
'attribute_id' => $attribute->getId(),
'attribute_code' => 'size',
'values' => $configurableAttributeSizeValues,
'position' => 0,
);
$configurableAttributesData = array($configurableAttributeSize);
$configurableProductsIds = array();
foreach($simpleProducts as $simpleProduct) {
$configurableProductsIds[$simpleProduct->getId()] = $simpleProduct->getId();
}
$product->setConfigurableProductsData($configurableProductsIds);
$product->setConfigurableAttributesData($configurableAttributesData);
$product->setCanSaveConfigurableAttributes(true);
Before this code is put to use, I've loaded a product-collection called $simpleProducts and a single attribute $attribute. If you want to load multiple attributes to the same product, you can by adding them to the $configurableAttributesData array.
The original $configurableProductsData that you created in your code can still be used, however because most of its purpose is moved to the attributes-array instead, you can also just create a simple array of Simple Product IDs instead. That's what I did with $configurableProductsIds.
Hope this helps you out as well.
Here is what worked for me (some code repeated for clarity). Both setConfigurableProductsData and setConfigurableAttributesData need to be used for pricing_value to be saved.
$configurableAttributesData = $product->getTypeInstance()->getConfigurableAttributesAsArray();
$product->getTypeInstance()->setUsedProductAttributeIds(array($attribute->getId()));
$product->setCanSaveConfigurableAttributes(true);
$configurableProductsData[$childId] = array(
$childProductId => array(
'label' => $childProduct->getAttributeText($attribute->getAttributeCode()),
'attribute_id' => $attribute->getId(),
'value_index' => $optionId,
'is_percent' => false,
'pricing_value' => $childProduct->getPrice()
)
);
$configurableAttributesData[0]['values'][] = array(
'label' => $childProduct->getAttributeText($attribute->getAttributeCode()),
'attribute_id' => $attribute->getId(),
'value_index' => $optionId,
'is_percent' => false,
'pricing_value' => $childProduct->getPrice()
);
$configurableAttributesData[0]['attribute_id'] = $attribute->getId();
$product->setConfigurableProductsData($configurableProductsData);
$product->setConfigurableAttributesData($configurableAttributesData);
$product->save();

Magento: add configurable products to cart programmatically

How to add the child product to cart programmatically?
I've a child product SKU, I want to
Fetch the supper attributes like size and color id and values from the products,
Then fetch the parent product id,
Pass the super attributes on param with quantity, to add to function cart.
//$cart->addProduct($product1, $options);
Here, how to pass the supper attributes on the $option variable? Please help me!!!!
Try this. I think it may need some improvements but it works good in simple cases.
$_product = $this->getProduct();
$parentIds = Mage::getResourceSingleton('catalog/product_type_configurable')->getParentIdsByChild($_product->getId());
// check if something is returned
if (!empty(array_filter($parentIds))) {
$pid = $parentIds[0];
// Collect options applicable to the configurable product
$configurableProduct = Mage::getModel('catalog/product')->load($pid);
$productAttributeOptions = $configurableProduct->getTypeInstance(true)->getConfigurableAttributesAsArray($configurableProduct);
$options = array();
foreach ($productAttributeOptions as $productAttribute) {
$allValues = array_column($productAttribute['values'], 'value_index');
$currentProductValue = $_product->getData($productAttribute['attribute_code']);
if (in_array($currentProductValue, $allValues)) {
$options[$productAttribute['attribute_id']] = $currentProductValue;
}
}
// Get cart instance
$cart = Mage::getSingleton('checkout/cart');
$cart->init();
// Add a product with custom options
$params = array(
'product' => $configurableProduct->getId(),
'qty' => 1,
'super_attribute' => $options
);
$request = new Varien_Object();
$request->setData($params);
$cart->addProduct($configurableProduct, $request);
$session = Mage::getSingleton('customer/session');
$session->setCartWasUpdated(true);
$cart->save();
}
U can try.
$cart = Mage::getModel('checkout/cart');
$cart->init();
$productCollection = Mage::getModel('catalog/product')->load($productId);
$cart->addProduct($productCollection ,
array( 'product_id' => $productId,
'qty' => 1,
'options' => array( $optionId => $optionValue));
$cart->save();

Resources