Creating configurable products programmatically - pricing_value not saved - magento

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();

Related

ajax call in magento 2

I have created a custom module in Magento2 where currently I'm selecting a customer and entered multiple order numbers, it will saved into a custom table in the database.
Currently I have to entered order numbers in a textarea but now I want to display all orders after choosing the customer which are not in Complete status.
From this section admin choose orders by clicking on the right side checkbox and Saved it.
Can anyone help me to solve this problem?
Existing Module’s Layout
Want to modify the above layout to the following one: In this desired system when admin change the customer name order numbers associated with that customer will be listed.
New invoice
Code I have used to create the customer dropdown field:
$fieldset->addField('customer_id', 'select', array(
'label' => __('Customer'),
'name' => 'customer_id',
'title' => __('Customer'),
'values' => $this->getCustomerOptionArray()
));
protected function getCustomerOptionArray()
{
$options = array();
$options[] = array(
'value' => 0,
'label' => __('Select Customer'),
);
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerObj = $objectManager->create('Magento\Customer\Model\Customer')->getCollection();
foreach ($customerObj as $customerObjdata ){
$options[] = array(
'value' => $customerObjdata->getId(),
'label' => $customerObjdata->getName(),
);
}
return $options;
}

insert method is overwriting what is in the cart and not adding to it

if($this->input->post('tambah')){
$kode = $this->input->post('kode');
$jumlah = $this->input->post('jumlah');
$hjual = $this->input->post('hjual');
$nama = $this->input->post('nama');
$exp = $this->input->post('tglexp');
$hpp = $this->input->post('hpp');
$temp_stok = $this->input->post('temp_stok');
$diskon = $this->input->post('diskon');
$cart = array(
'id' => $kode,
'qty' => $jumlah,
'price' => $hjual,
'name' => $nama,
'options' => array('exp' => $exp, 'hpp' => $hpp,
'temp_stok' => $temp_stok , 'diskon'=>$diskon ));
$this->cart->insert($cart);
header('location:'.base_url().'penjualan/load_input_barang_eceran');
}
I cant seem to add any more items and the latest one I add replaces the existing one.
I had like this in another controller but strangely can insert and not overwriting
I've had this.
It was non alphanumerics in the product code which caused the whole cart to behave strangely.
Try just having aaa123 etc as codes to test this

How to add categories in Joomla 2.5

Does anyone know how to properly insert new content categories to the DB programatically?
For each post in the categories table, there is also a post saved in the assets table with lft and rgt set.
Is there any native Joomla class I can use for this instead of plain SQL?
Please Please Only use the native classes, which categories will handle for you seamlessly. As soon as you add categories the whole thing will be handled automagically. Just look at any core component to see how.
It is not easy to update the assets table using sql, it is all very specifically managed and part of a complex series of foreign keyed tables.
Extend JTable or JTableContent to handle this.
Here is some code I just whipped together that just uses the JTableCategory class, so it can be used simply on the front or admin side of Joomla
$table = JTable::getInstance('category');
$data = array();
// name the category
$data['title'] = $title;
// set the parent category for the new category
$data['parent_id'] = $parent_id;
// set what extension the category is for
$data['extension'] = $extension;
// Set the category to be published by default
$data['published'] = 1;
// setLocation uses the parent_id and updates the nesting columns correctly
$table->setLocation($data['parent_id'], 'last-child');
// push our data into the table object
$table->bind($data);
// some data checks including setting the alias based on the name
if ($table->check()) {
// and store it!
$table->store();
// Success
} else {
// Error
}
Naturally you would want to get the data pieces set correctly, but these are the core ones to set.
Here is a function I've created just for this purpose, after some digging & experimenting.
It uses core classes, so it needs an access to them (for me it's basically a part of Joomla component).
Mind, it's for Joomla 3, for Joomla 2.5 and before, you need to change JModelLegacy to JModel.
function createCategory( $name, $parent_id, $note )
{
JTable::addIncludePath( JPATH_ADMINISTRATOR . '/components/com_categories/tables' );
$cat_model = JModelLegacy::getInstance( 'Category', 'CategoriesModel' );
$data = array (
'id' => 0,
'parent_id' => $parent_id,
'extension' => 'com_content',
'title' => $name,
'alias' => '',
'note' => $note,
'description' => '',
'published' => '1',
'access' => '1',
'metadesc' => '',
'metakey' => '',
'created_user_id' => '0',
'language' => '*',
'rules' => array(
'core.create' => array(),
'core.delete' => array(),
'core.edit' => array(),
'core.edit.state' => array(),
'core.edit.own' => array(),
),
'params' => array(
'category_layout' => '',
'image' => '',
),
'metadata' => array(
'author' => '',
'robots' => '',
),
);
if( !$cat_model->save( $data ) )
{
return NULL;
}
$categories = JCategories::getInstance( 'Content' );
$subcategory = $categories->get( $cat_model->getState( "category.id" ) );
return $subcategory;
}
You can perhaps use the save() in category.php file.
File location: root\administrator\components\com_categories\models\category.php
It saves the form data supplied to it!
The JOS_assets table is to store the ACL for each asset that is created.
If you do not update this table while programatically creating the category, the default ACL will apply. And when later you open and save the category in the administrative panel, the ACL will be updated as it should have been by core Joomla!.
You can create an SQL query very easily though and update the asset table as well. Its easy to understand once you open the table's content in phpmyadmin.

Magento sort by entity_id

Does anyone know how to make entity_id visible on the frontend as a sortable attribute? I went to manage attributes and I can't add entity_id as an attribute as it says
"The attribute code 'entity_id' is reserved by system. Please try another attribute code"
So I tried to do a search in the whole database I had Magento on using the following SQL CMD:
select attribute_id from eav_attribute where attribute_code = 'updated_at';
and it returned zero results, I tried other attributes and those showed...
Does anyone know how I can add entity_id as an attribute, as I can't even make it visible because I have no idea what the attribute_id # is even while searching the whole database for that value.
Here is the code I use to make a attribute visible on the admin section of magento:
UPDATE `catalog_eav_attribute`
SET `is_visible` = '1'
WHERE `catalog_eav_attribute`.`attribute_id` = 105;
I've tried searching high and low for days, and trying different variations - so stuck at this point, any help would be great.
I'm using Magento Enterprise 12.2 if that helps, but to be honest the DB is not much different than the community version the only differences are the added modules but when it comes to products it's pretty much the same.
This is surprisingly nasty - I can't see a way to do this simply in the DB, as entity_id isn't a standard attribute (it's really just a key field) and the core code repeats the same logic in three place (urgh).
It's also changed a lot since the older versions of Magento, so many of the tutorials and forum posts on this no longer apply.
What you can do is add "entity_id" in as a new sorting option, similar to the way "Best Value" exists as a sorting option. In the following example I've labelled it "Newest"
The usual caveats apply: You should do this in an extension (or at the least in /local/ overrides) but the three core file methods that need overriding in Community Edition 1.7 are:
Mage_Adminhtml_Model_System_Config_Source_Catalog_ListSort
public function toOptionArray()
{
$options = array();
$options[] = array(//benz001
'label' => Mage::helper('catalog')->__('Newest'),
'value' => 'entity_id'
); //end benz001
$options[] = array(
'label' => Mage::helper('catalog')->__('Best Value'),
'value' => 'position'
);
foreach ($this->_getCatalogConfig()->getAttributesUsedForSortBy() as $attribute) {
$options[] = array(
'label' => Mage::helper('catalog')->__($attribute['frontend_label']),
'value' => $attribute['attribute_code']
);
}
return $options;
}
Then Mage_Catalog_Model_Category_Attribute_Source_Sortby
/**
* Retrieve All options
*
* #return array
*/
public function getAllOptions()
{
if (is_null($this->_options)) {
$this->_options = array(
array(//benz001
'label' => Mage::helper('catalog')->__('Newest'),
'value' => 'entity_id'
), //end benz001
array(
'label' => Mage::helper('catalog')->__('Best Value'),
'value' => 'position'
));
foreach ($this->_getCatalogConfig()->getAttributesUsedForSortBy() as $attribute) {
$this->_options[] = array(
'label' => Mage::helper('catalog')->__($attribute['frontend_label']),
'value' => $attribute['attribute_code']
);
}
}
return $this->_options;
}
And then Mage_Catalog_Model_Config
public function getAttributeUsedForSortByArray()
{
$options = array(
'entity_id' => Mage::helper('catalog')->__('Newest'), //benz001
'position' => Mage::helper('catalog')->__('Position'),
);
foreach ($this->getAttributesUsedForSortBy() as $attribute) {
/* #var $attribute Mage_Eav_Model_Entity_Attribute_Abstract */
$options[$attribute->getAttributeCode()] = $attribute->getStoreLabel();
}
return $options;
}
With those in place, flush the cache and refresh and you can then select to sort by Newest/entity_id in the config and on the category page and on the frontend.
Note: even if you have caching turned off it's still a good idea to flush the cache - parts of the admin are cached even when caching is disabled.

List node comments using existing comment.tpl.php from custom Drupal module

I have created a module which gets the comments from the nodes which the user has specified as 'favourites'. So I'm not trying to output all comments from all nodes like the recent comments block do, but just the ones from nodes specified as 'favourites'.
The queries all work, I've tested this by printing values from the different objects. So I've got the whole comment object for each comment and the corresponding node object. I've been able to create lists of the cid, nid, comment text etc. and output these with
$block['content'] = theme('item_list', array('items' => $items));
but how would I go about rendering the comment objects I've got in my module in the same layout/design as I have on my node pages? The comments on my node pages are rendered with the comment.tpl.php file which I set up with my own layout/design and I'd like my module to render these comments the same way.
So this is my hook_block_view() implementation which I believe is the correct way for output from a module:
function jf_comment_feed_block_view($delta = '') {
switch($delta){
case 'jf_comment_feed':
$block['subject'] = t('Comment feed');
if(user_access('access content')){
// Get users favourite locations
$loc_result = jf_comment_feed_locations();
$fav_loc = array();
foreach ($loc_result as $loc) {
$fav_loc[] = array(
'data' => $loc->nid,
);
}
if (empty($fav_loc)) { //No content in the last week.
$block['content'] = t('No favourite locations added.
To see what goes on at your favourite locations add locations to
+My Locations and the posts from those locations will show here.');
} else {
//Use our custom function to retrieve data.
$result = jf_comment_feed_contents($fav_loc);
// ############################################
// Here I need to create my output... I think...
// Previously I rendered my results from the query
// by using this code (this prints the comment id):
// $items = array();
// foreach ($result as $comment){
// $items[] = array(
// 'data' => comment_load($comment->cid),
// );
// }
// ############################################
if (empty($items)) { //No content in the last week.
$block['content'] = t('No posts from last week.');
} else {
// This is the code used to render the
// comment id to the block:
// $block['content'] = theme('item_list', array('items' => $items));
}
}
}
}
return $block;
}
I've also tried with:
$block['content'] = theme('comment_view', $mycomment, $mynode);
$block['content'] = theme('comment', $mycomment, $mynode);
where $mycomment is the comment object and $mynode is the node object. But this breaks the page.
Surely there must be a line of code I'm missing here, but I've now spent two days googling this and had no luck... So thanks for any help with this.
EDIT
#Clive did trigger some ideas and I tried creating my own array based on what the arrays look like on the node page. I got the structure and names for the array with the Devel Themer info module.
This array outputs the comments creators user pic and the date, but I've added a custom field, field_jf_comment, to my comments and this isn't showing, although I can see the information in the array with Devel. I don't use the standard out-of-the-box comment field because I wanted a textfield and not a scalable textarea for the input. A design decision.
Now obviously this isn't ideal as I set most of the values manually. This works for my current project, but would be cool if the module was a bit more generic so other people could use it too. When I click on a individual comment on my node page with Devel Themer info I get an array which has elements, the user object and array items such as db_is_active, is_admin among other things. If I could somehow recreate this array and then set this array to $block['content'] I believe this would work.
Here's the implementation of the array:
foreach ($result as $comment) {
$items[] = array(
'#entity_type' => 'comment',
'#bundle' => 'comment_node_location',
'#theme' => 'comment__node_location',
'#comment' => comment_load($comment->cid, FALSE),
'#node' => node_load($comment->nid),
'#view_mode' => 'full',
'field_jf_comment' => array(
'#theme' => 'field',
'#title' => 'Title',
'#access' => TRUE,
'#label_display' => 'above',
'#view_mode' => 'full',
'#language' => 'und',
'#field_name' => 'field_jf_comment',
'#field_type' => 'text',
'#entity_type' => 'comment',
'#bundle' => 'comment_node_location',
'#items' => array(
'0' => array(
// This isn't working and gives an error saying:
// Notice: Undefined property: stdClass::$field_jf_comment in
// jf_comment_feed_block_view()
'value' => $comment->field_jf_comment['und']['0']['value'],
'format' => $comment->field_jf_comment['und']['0']['format'],
'safe_value' => $comment->field_jf_comment['und']['0']['safe_value']
)
)
)
);
}
And I get it rendered with:
$block['content'] = $items;
EDIT
#Clive was right. His code does the same as mine, but in way less code. And with some modifications I managed to get my custom field in there too:
$content = '';
foreach ($items as $item) {
$single_comment = comment_load($item['cid']);
$custom_field = field_attach_view('comment', $single_comment, 'field_jf_comment');
$to_render = array(
'#theme' => 'comment',
'#comment' => $single_comment,
'#node' => node_load($item['nid']),
'field_jf_comment' => $custom_field
);
$content .= render($to_render);
}
$block['content'] = $content;
Now the only thing I'm missing is the links for each comment. The only one I'm using is the Reply to comment. Anyone got any idea of how to get that to show too?
The theme() calls probably break because you're using Drupal 7 but trying to pass the parameters in a Drupal 6 style. If you have a look at the theme_comment() documentation you can see it takes a single $variables parameter which should be an array. Try this:
$content = '';
foreach ($items as $item) {
$to_render = array(
'#theme' => 'comment',
'#comment' => comment_load($item['cid'])
);
$content .= render($to_render);
}
$block['content'] = $content;
The new Drupal 7 theme() syntax takes an array for its second argument. This array will be extracted before calling the template file so each key will become a new php var.
For example array( 'comment' => $mycomment ) will get you a $commentvariable in your template.
Hope this can help.

Resources