Magento. Create attribute for grouped products only - php

I am trying to create attribute programmatically for all grouped products on my site. I am trying to create custom attribute set with group.
$oEntitySetup = $this;
$oEntitySetup->removeAttribute('catalog_product', 'grouped_base_price');
$skeletonID=$oEntitySetup->getAttributeSetId('catalog_product','Default');
$entityTypeId = Mage::getModel('catalog/product')
->getResource()
->getEntityType()
->getId(); //product entity type
$attributeSet = Mage::getModel('eav/entity_attribute_set')
->setEntityTypeId($entityTypeId)
->setAttributeSetName("oggy_attr_set");
$attributeSet->validate();
$attributeSet->save();
$attributeSet->initFromSkeleton($skeletonID)->save();
$data = array(
'attribute_set' => 'oggy_attr_set',
'group' => 'General',
'label' => 'Base Price',
'apply_to' => 'grouped',
'input' => 'text',
'visible' => true,
'visible_on_front' => true,
'required' => true,
'position' => 1,
'global' => 'Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL',
'note' => "Default Price For Configurable Products"
);
$oEntitySetup->addAttribute('catalog_product', 'grouped_base_price', $data);
$oEntitySetup->endSetup();
The problem is that attribute appears in all product types. But i need for grouped products only. What i am doing wrong ?

Assign created attribute to a particular "attribute set" and then while creating any group product - select this attribute set.

in your code $oEntitySetup have all products, you never take a specific group, and is sure you gift the new attribute to all products

Related

Configurable product created programmatically doesn't show in search - Magento 1.9

I have a script that creates a configurable product and the simple products associated to it. After the creation, in the backend, all of them seems fine (stock, website, status, visibility and association between the simple products and the configurable are ok). The problem is when I try to search for the configurable product or add it to a category, it doesn't display.
All products (configurable and simple) are firstly created with this method:
private function createBaseProduct($sku)
{
$_product = Mage::getModel('catalog/product');
$_product->setSku($sku);
$_product->setAttributeSetId(4);
$_product->setTypeId('simple');
$_product->setWebsiteIDs(array(1));
$_product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);
$_product->setStatus(1);
$_product->setTaxClassId(0);
$_product->setStockData(array(
'use_config_manage_stock' => 0,
'manage_stock' => 1,
'is_in_stock' => 1,
'qty' => 100
));
return $_product;
}
In case the product is configurable, it then goes to this method:
private function setData($configurable)
{
$configurable->setTypeId('configurable');
$configurable->setStockData(array(
'use_config_manage_stock' => 0,
'manage_stock' => 0,
'is_in_stock' => 1,
'qty' => 0,
));
--> $configurable = $this->setAssociativeAttributes($configurable);
$configurableAttributesData = $configurable->getTypeInstance()->getConfigurableAttributesAsArray();
$configurable->setCanSaveConfigurableAttributes(true);
$configurable->setConfigurableAttributesData($configurableAttributesData);
return $configurable;
}
Where the method setAssociateAttributes() set the attributes IDs of the configurable product being created:
private function setAssociativeAttributes()
{
$configurable->getTypeInstance()->setUsedProductAttributeIds($this->configurableAttrsIds);
return $configurable;
}
After that, the configurable product returned in setData() is saved using $product->save(). Then, the simple product's are created (using the createBaseProduct() method), saved, and assigned to the configurable product using this method:
public function associateChildProduct($configurableId, $childProduct)
{
$configurable = Mage::getModel('catalog/product')->load($configurableId);
$childProducts = $configurable->getTypeInstance()->getUsedProducts();
array_push($childProducts, $childProduct);
$childProductsIds = array();
foreach($childProducts as $product) {
array_push($childProductsIds, $product->getId());
}
Mage::getResourceSingleton('catalog/product_type_configurable')
->saveProducts($configurable, $childProductsIds);
}
And all seems good, products are created and correctly assigned to configurable. But in the frontend the configurable product isn't displayed (only if I access it via URL it opens correctly, with the variations and all).
Obs.: simple products are displayed in search correctly, only the configurable is missing.
I believe there's something wrong in the configurable's data, but I can't figure it out :(
----- EDIT -----
So I debugged it a little more and seems that the problem is actually in the attribute used to create the configurable product (I'm also creating this attribute programmatically). If I save the attribute created programatically again, in my admin panel, the link between simple products and their configurable disapear (they don't show linked in the admin panel anymore).The attribute is created before the configurable product using class "CustomAttribute":
public function __construct($attrCode)
{
$attrData = array(
'group' => '',
'type' => 'varchar',
'backend' => '',
'frontend' => '',
'label' => ucfirst($attrCode),
'input' => 'select',
'class' => '',
'source' => '',
'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
'visible' => true,
'required' => false,
'user_defined' => true,
'default' => '0',
'searchable' => false,
'filterable' => false,
'comparable' => false,
'visible_on_front' => false,
'is_configurable' => true,
'unique' => false,
);
$installer = new Mage_Eav_Model_Entity_Setup('core_setup');
$installer->startSetup();
$installer->addAttribute(Mage_Catalog_Model_Product::ENTITY, $attrCode, $attributeData);
$this->addAttributeToDefaultSet();
$installer->endSetup();
}
And this attribute is set to child products (during their creation) using the following method:
private function setCustomAttribute($chidlProduct, $attrCode, $optionLabel)
{
$customAttribute = new CustomAttribute($attrCode);
$customAttribute->addOptionIfNotExists($optionLabel, $attrCode);
$optionId = $customAttribute->getOptionId($optionLabel);
$product->setData($attrCode, $optionId);
}
Where the method $customAttribute->addOptionIfNotExists() creates the attribute's option if not already created:
public function addOptionIfNotExists($optionLabel, $attrCode)
{
$value['option'] = array($optionLabel);
$order['option'] = 0;
$optionData = array(
'value' => $value,
'order' => $order
);
$attribute = Mage::getSingleton('eav/config')
->getAttribute(Mage_Catalog_Model_Product::ENTITY, $attrCode);
$attribute->setData('option', $optionData);
$attribute->save();
}
And after added the method associateChildProduct() is called to associate simple products to their configurable.
Obs.: configurable product is displayed correctly via URL, even the attribute variations are shown.
Obs2.: if I save the attribute via admin panel, delete simple products and create new ones using "Quick create" (with the same values) the configurable product is displayed in search and categories.
Just to put my comments in form of an answer, and organize it...
There are many reasons for a recently created product or one created programmatically to not being displayed in some collection.
Index
The first and most common one is related to indexation.
This could be related to issues in the cronjob (not configured, or not working properly).
You can manually trigger the reindex process by doing:
Magento 1: php shell/indexer.php reindexall
Magento 2: bin/magento indexer:reindex
Product not added to the website or not visible
Check if the product is enabled and visible in catalog. If they are simple products from a configurable product, make sure they are both enabled.
Also check if there is enough inventory of the item and if they are not marked as "out of inventory" (regardless the stock qty).
In multi website stores, check the "Website" group in the product edit page, and see if it's checked to appear in that website. Also check the product scope. Sometimes you disable the product in a inner level (i.e. store view or website).
Some condition is not met
If you believe that you've checked everything, now it's time to debug the collection.
Magento 1 and Magento 2 have the getSelect() method available in collection objects.
Find the phtml or block where your products are being looped, and find the collection variable (generally used in the foreach).
Then, add something like echo (string)$collection->getSelect().
This will show the query used to search the products. See which join or where condition is not met by your missing product.
Here's an example of category collection queries in Magento 1:
SELECT `e`.*,
`cat_index`.`position` AS `cat_index_position`,
`price_index`.`price`,
`price_index`.`tax_class_id`,
`price_index`.`final_price`,
IF(price_index.tier_price IS NOT NULL, LEAST(price_index.min_price, price_index.tier_price),
price_index.min_price) AS `minimal_price`,
`price_index`.`min_price`,
`price_index`.`max_price`,
`price_index`.`tier_price`
FROM `catalog_product_entity` AS `e`
INNER JOIN `catalog_category_product_index` AS `cat_index`
ON cat_index.product_id = e.entity_id AND cat_index.store_id = 4 AND
cat_index.visibility IN (2, 4) AND cat_index.category_id = '10'
INNER JOIN `catalog_product_index_price` AS `price_index`
ON price_index.entity_id = e.entity_id AND price_index.website_id = '4' AND
price_index.customer_group_id = 0
ORDER BY `cat_index`.`position` ASC
LIMIT 12
1 'New Arrivals' category from Magento 1 sample data.
With Ricardo Martins help I was able to debug the problem and discover that the configurable product wasn't being displayed because it's entity_id wasn't being added to the table catalog_product_index_price. This problem seems to be caused because the attribute used in the configurable product's creation had the backend_type set to varchar, instead int (Reference).
So I changed my code for attribute's creation to:
public function __construct($attrCode)
{
$attrData = array(
'group' => '',
--> 'type' => 'int',
'backend' => '',
'frontend' => '',
'label' => ucfirst($attrCode),
'input' => 'select',
'class' => '',
'source' => '',
'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
'visible' => true,
'required' => false,
'user_defined' => true,
'default' => '0',
'searchable' => false,
'filterable' => false,
'comparable' => false,
'visible_on_front' => false,
'is_configurable' => true,
'unique' => false,
);
$installer = new Mage_Eav_Model_Entity_Setup('core_setup');
$installer->startSetup();
$installer->addAttribute(Mage_Catalog_Model_Product::ENTITY, $attrCode, $attributeData);
$this->addAttributeToDefaultSet();
$installer->endSetup();
}
Where in the indicated line the attribute's backend_type is set to int. After this, the configurable product is now being correctly displayed in category and search :)

WooCommerce custom child products to variable products

I have some variable products (different 3-4 variations) with different prices. I want to add some simple products as child products (show as optional checkbox in front). I don't know how to manage that for adding to the cart.
For example let's assume I have a cellphone as main product and when user added it to it's cart it should see 3 sub product (child product) :
Handsfree (in three type of color)
Glass guard (in two type of color )
cell phone shield case ( just black)
as you can understand from above example I wanna to:
add all of this items as one product (includes handsfree, glass guard , cellphone case and cellphone itself ) and calculate it's price .I've read Add a checkbox on single product pages that adds an additional cost in Woocommerce and after that I have codes below to adding options in product edit page.
//custom product tab to woocommerce edit
function sm_wccpd_custom_product_tabs($tabs)
{
$tabs['sm_wcpa_extra_products'] = array(
'label' => __('Samanik Extra Products', 'sm-wcpa'),
'target' => 'sm_wc_extra_products_options',
'class' => array('show_if_variable'),
);
return $tabs;
}
add_filter('woocommerce_product_data_tabs', 'sm_wccpd_custom_product_tabs');
and here is tab content
function extra_products_options_product_tab_content()
{
global $post;
// Note the 'id' attribute needs to match the 'target' parameter set above
?>
<div id='sm_wc_extra_products_options' class='panel woocommerce_options_panel'><?php
?>
<div class='options_group'><?php
woocommerce_wp_checkbox(
[
'id' => '_has_extra_products',
'label' => __('has extra products', 'sm-wcpa'),
]);
woocommerce_wp_select(
[
'class' => 'multiselect attribute_values wc-enhanced-select',
'custom_attributes' => ['multiple' => 'multiple', 'style' => 'width:100% !importan;'],
'id' => '_sm_wcpa_product[]',
'label' => __('Extra Products to be add here', 'sm-wcpa'),
'value' => array_values(json_decode(get_post_meta($post->ID, '_sm_wcpa_product'), true)),
'options' => sm_wcpa_get_products_as_options(),//this is function that I pass Products as array like [product_id => product name]
]);
?></div>
</div><?php
}
// add_filter('woocommerce_product_data_tabs', 'extra_products_options_product_tab_content'); // WC 2.5 and below
add_filter('woocommerce_product_data_panels', 'extra_products_options_product_tab_content'); // WC 2.6 and up
also I can save the data and I think they are not necessary here.
now what I need to do is how to manage this in front. I mean show child products as checkbox, add price to parent price if checked, what about changing variables(those have different prices).
thanks for your patient to read my question.

how to add custom attribute in catalog/category in magento 1.9

how to add custom attribute in catalog/category in admin general tab which will display only on specific store not for all.
$installer = $this;
$installer->startSetup();
$installer->addAttribute(Mage_Catalog_Model_Category::ENTITY,
'banner_img1',
array(
'group' => 'General',
'type' => 'text',
'label' => 'Door Banner Image1',
'visible' => true,
'required' => false,
'visible_on_front' => false,
'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE,
));
$installer->endSetup();`
but above code create attribute in all store view i want to show only for 1 store
Magento attributes do not work that way. Store scope means that attribute can have different value for each store view, but you can't have it exist for one and not for other.
Even tho there's no way to add an attribute only for one store view, you can upload the image only for particular store view and add the check in your theme which will output the attribute only if it's present.

How to add new field to product attributes in magento?

i want to send manufacturer email when order is made . For that i want to add email address of manufacturer in Manufacturer product attribute ? How to achieve this ?
I'm gonna assume that you are asking how to do it in code? Anyway, just build a small module with an install script (tutorials all over the web), and make the setup script look something like this:
$installer = $this;
$installer->startSetup();
// check if the attribute exists
if (Mage::getModel('catalog/resource_eav_attribute')->loadByCode('catalog_product','calculated_sold')->getId() !== NULL) {
$installer->removeAttribute('catalog_product', 'calculated_sold');
}
// not anymore, that's for sure!
// Note! For product attributes the XML set class needs to be "Mage_Catalog_Model_Resource_Setup"
// instead of "Mage_Customer_Model_Entity_Setup" as you would usually go with.
$installer->addAttribute('catalog_product','calculated_sold', array (
'type' => 'decimal',
'label' => 'Calculated sold',
'input' => 'price', // for filtering to work only certain input types allowed
'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE,
'searchable' => true,
'filterable' => true,
'visible' => false,
'required' => false,
'visible_in_advanced_search' => true,
'used_in_product_listing' => true,
'used_for_sort_by' => true,
'apply_to' => 'configurable', // yeah!
));
$installer->endSetup();
This example adds an attribute to keep track of how many items are sold, but it will give you an idea of how to change it for your own needs.

Magento custom dependent category attributes

I have some custom attributes for my project.
Attribute1 : Use in home page sidebar(yes/no)
if it is yes show the below attribute.
Attribute2 : Browse image
I want to add attribute2 based on the attribute1. Only when the Use in Home Page Sidebar is enabled , my new attribute will be shown below of the current. I.e., it will be a dependent attribute. Does somebody know the script for adding dependent attributes in Magento?
Previously i added custom attributes by
$this->startSetup();
$this->addAttribute(Mage_Catalog_Model_Category::ENTITY, 'use_home_page_side_bar', array(
'group' => 'General',
'input' => 'select',
'type' => 'int',
'label' => 'Use in Home Page Sidebar',
'backend' => '',
'source' => 'eav/entity_attribute_source_boolean',
'visible' => true,
'required' => false,
'visible_on_front' => true,
'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
));
$this->endSetup();
Like this script, is there any script for adding dependent attributes?
If you are working on admin forms, then a class exists for automatically hiding elements when the value of fields change.
Below is an example which shows field dependency.
$form = new Varien_Data_Form();
$form->addField('yesno', 'select', array(
'label' => $this->__('Yes or No?'),
'values' => Mage::model('adminhtml/system_config_source_yesnocustom')
->toOptionArray(),
));
$form->addField('custom_value', text, array(
'label' => $this->__('Other'),
));
// Append dependency javascript
$this->setChild('form_after', $this->getLayout()
->createBlock('adminhtml/widget_form_element_dependence')
->addFieldMap('yesno', 'yesno')
->addFieldMap('custom_value', 'custom_value')
->addFieldDependence('custom_value', 'yesno', 2) // 2 = 'Specified'
);
You need to map every field name to an element ID. You can add as many field mappings and field dependencies in this way as you wish.
I have created simple category attribute dependency by adding new input renderer for attribute. It is working this way:
You have several attributes:
– my_attribute
– my_attribute_text
– my_attribute_select
Note that they all start from my_attribute.
First attribute has boolean type. When it is set to true – other attributes that start from my_attribute is visible.
Source - https://github.com/elpas0/category_dependence
Description - http://nwdthemes.com/2015/02/20/magento-category-attributes-dependency/

Categories