Adding custom option to a product programatically in custom module frontend controller? - magento-1.6

i am trying to add product from frontend programatically following this link :
Magento: Adding new products programmatically
but i want to extend it to add custom options too to it .And i added the following code to it
$options = array();
$options[$sku] = array(
'title' => 'Option Title',
'type' => 'radio',
'is_require' => 1,
'sort_order' => 0,
'values' => array()
);
$options[$addvp['product']['sku']]['values'][] = array(
'title' => 'Option Value 1',
'price' => 0.00,
'price_type' => 'fixed',
'sku' => '',
'sort_order' => '1'
);
$options[$sku]['values'][] = array(
'title' => 'Option Value 2',
'price' => 89.00,
'price_type' => 'fixed',
'sku' => '',
'sort_order' => '1'
);
foreach($options as $sku => $option) {
$id = Mage::getModel('catalog/product')->getIdBySku($sku);
$product = Mage::getModel('catalog/product')->load($id);
if(!$product->getOptionsReadonly()) {
$product->setProductOptions(array($option));
$product->setCanSaveCustomOptions(true);
//$product->save();
}
}
but it prints this error instead of adding custom option to product.
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`vendor`.`catalog_product_entity`, CONSTRAINT `FK_CAT_PRD_ENTT_ATTR_SET_ID_EAV_ATTR_SET_ATTR_SET_ID` FOREIGN KEY (`attribute_set_id`) REFERENCES `eav_attribute_set` (`attribute_set_id`) ON DEL)

http://www.fontis.com.au/blog/magento/add-product-custom-options
Note:
The above link did what i want it to do. But one thing to be kept in mind that you must add the custom option to a product already exists/saved.

I had a similar issue. Turned out that the auto-generated SKU was somehow invalid or not properly saved on the new product I created for testing. The product was not invalid, as it did save properly on the first go, but when I revisited the product via the CMS and tried to click "save and continue" it suddenly prompted me to enter a SKU. When I re-entered the auto-generated sku it worked!
So the short answer would be: Check that your product exists by that SKU number. If it does, re-check that the SKU is being saved properly.

Related

Prestashop 1.6.1 Helper Form fields undefined index

I'm struggling with this for quite some hours:
I'm trying to add new fields to a form generated with the HelperForm class in Prestashop for a custom module.
I try to do this for the configuration page of the module in the getContent() function
The following field is accepted and it works:
array(
'type' => 'file',
'label' => $this->l('Button image'),
'id' => 'button_image_path',
'name' => 'button_image_path',
'image' => '<img src="'._MODULE_DIR_.$this->name.'\\img\\'.basename($buttonImage["setting_value"]).'" class="button-image-preview" width="30">'
)
However, when i try to add other fields like this:
array(
'type' => 'text',
'label' => $this->l('Number of displayed products'),
'name' => 'CROSSSELLING_NBR',
'desc' => $this->l('Set the number of products displayed in this block.'
)
It gives this error:
Notice on line 387 in file D:\wamp\www\qmart.ro\tools\smarty\sysplugins\smarty_internal_templatebase.php(157) : eval()'d code
[8] Undefined index: CROSSSELLING_NBR
However, the input is still generated, and it looks like this:
<input type="text" name="CROSSSELLING_NBR" id="CROSSSELLING_NBR" value="" class="">
What i tried:
Changing the input type from text to color for example, and it gave the same error
Changing the label content and the name content, and the error still appeared
I did not change anything in the core files.
So, the form is being built for those inputs, but this "undefined index" thing still occurs.
So, apparentply they force you to choose some default value for the inputs.
i simplu solved it by adding this line:
$helper->fields_value['CROSSSELLING_NBR'] = '';
According to your code...
array(
'type' => 'text',
'label' => $this->l('Number of displayed products'),
'name' => 'CROSSSELLING_NBR',
'desc' => $this->l('Set the number of products displayed in this block.'
)
You have an error in 'desc', you need close the final parenthesis, this should works...
array(
'type' => 'text',
'label' => $this->l('Number of displayed products'),
'name' => 'CROSSSELLING_NBR',
'desc' => $this->l('Set the number of products displayed in this block.')
)

Pardot API: Add new prospect to certain list

$prospectData = array(
'user_key' => $user_key,
'api_key' => $api_key,
'first_name' => $firstName,
'last_name' => $lastName,
'city' => $city,
'state' => $state,
'comments' => $comments
);
callPardotApi('https://pi.pardot.com/api/prospect/version/4/do/create/email/'.$email, $prospectData);
I'm able to create a new prospect with a form that I have. It inserts all the data I supplied it (name, city, state, etc), but I need to also add this prospect to a list.
I tried adding to my $prospectData things like list => '1234' or "list_id" => '1234', but that doesn't seem to be working.
Is this possible to do? I know I can assign a prospect to a list via another api route using their ID, but I need this prospect to be added immediately upon form submit
Well it's not exactly ideal, but I had to do a new api call after creating the user.
$addprospect = callPardotApi('https://pi.pardot.com/api/prospect/version/4/do/create/email/'.$email, $prospectData);
$addprospectxml = new SimpleXMLElement($addprospect);
$id = $addprospectxml->prospect->id;
$listData = array(
'user_key' => $user_key,
'api_key' => $api_key,
'list_32106' => "1"
);
$updateProspect = callPardotApi('https://pi.pardot.com/api/prospect/version/4/do/update/id/'.(String)$id[0], $listData);
When creating a prospect, it will return XML with the newly crated prospect's ID. that ID can be used in a new api update call where you can set the list.

Magento API: Set dropdown attribute option for a storeview

I am working with magento API and need to create dropdown options for different storeviews.
I found a function to to create a dropdown option for default storeview:
public function addAttributeOption($arg_attribute, $arg_value)
{
$attribute_model = Mage::getModel('eav/entity_attribute');
$attribute_options_model= Mage::getModel('eav/entity_attribute_source_table');
$attribute_code = $attribute_model->getIdByCode('catalog_product', $arg_attribute);
$attribute = $attribute_model->load($attribute_code);
$attribute_table = $attribute_options_model->setAttribute($attribute);
$options = $attribute_options_model->getAllOptions(false);
$value['option'] = array($arg_value,$arg_value);
$result = array('value' => $value);
$attribute->setData('option',$result);
$attribute->save();
}
This functions works fine, I can add a new attribut value for default storeview.
Example:
I have the attribute "mycolor" and call the function like
addAttributeOption("mycolor", "black")
Now I have a storeview for a german shop and like to set the german color. I would need something like
addAttributeOption("mycolor", "black", "schwarz", $storeview)
Means set the color option of storeview to schwarz where the color of the default value is black.
Does anybody has an Idea how can I do that?
Best regards
I figure you alreay found your solution but perhaps I can help someone else who's new to Magento like I am. Today I had to find a way to import attributes (Product Attributes only that is) from an external Products-Managing-System into Magento running with multiple store views, too. I don't know where the questioner's addAttributeOption function came from but the Magento installer script offers its very own addAttributeOption(). So I took a look into Setup.php where Magento's addAttributeOption() is defined:
{Your Magento Path}/app/code/core/Mage/Eav/Model/Entity/Setup.php
Now, in the Magento Version i'm working with (1.9.1.0) addAttributeOption() expects one argument, an array called $option. It's architecture looks as follows:
Array (
'attribute_id' => '{attributeId}',
'value' => array(
'{optionId}' => array(
'{storeId}' => '{labelName}',
),
),
'delete' => array(
//...
),
'order' => array(
//...
)
);
As you can see, 'value' expects an array and this array's key determines the storeID. In most addAttributeOption()-introductions I found on the web, the storeID is hard coded to 0 with no further explanation - 0 makes it the required default admin value. So, quite obviously by now, for adding Options with StoreView-dependent labels we simply have to add an extra array value for each StoreView like this:
Array (
'attribute_id' => $attribute_id,
'value' => array(
'option1' => array(
'0' => 'black', // required admin value
'1' => 'Schwarz (RAL 9005)', // if storeId = 1 is German
'2' => 'Black (RAL 9005)', // if storeId = 2 is English
),
'option2' => array(
'0' => 'blue',
'1' => 'Blau (RAL 5015)',
'2' => 'Blue (RAL 5015)',
),
// And so on...
)
);
Note: If your option's array-index is a number addAttributeOption() expects it to be the ID-Number of an already existing Option. This is great in case you want to update already existing options but this also means a new Option musn't be numeric. Hence I named them 'option1' & 'option2'.
You can call addAttributeOption() like this:
Mage::app();
$installer = Mage::getResourceModel('catalog/setup','catalog_setup');
$installer->startSetup();
// ...
// generate your Options-Array
// I called it $newOptions
$installer->addAttributeOption($newOptions);
$installer->endSetup();

Restricting a category for a certain country in Prestashop 1.5

I need to restrict a category to a set of countries in Prestashop 1.5.
This restriction would prevent the shipping of a product belonging to such a category; as such, the users would still be able to see the products but they would not be able to buy them.
Ideally, I wanted to develop a module that would insert a list of countries (checkbox style, as in the Modules -> Payment page (AdminPayment)) inside a category's edit page, but I haven't been able to do so.
Why can't i simply paste the following code inside the renderForm() function?
Only the description is visible if i do so...
array(
'items' =>Country::getCountries(Context::getContext()->language->id),
'title' => $this->l('Country restrictions'),
'desc' => $this->l('Please mark the checkbox(es) for the country or countries for which you want to block the shipping.'),
'name_id' => 'country',
'identifier' => 'id_country',
'icon' => 'world',
),
EDIT:
I managed to get the list of countries working:
array(
'type' => 'checkbox',
'label' => $this->l('Restricted Countries').':',
'class' => 'sel_country',
'name' => 'restricted_countries',
'values' => array(
'query' => Country::getCountries(Context::getContext()->language->id),
'id' => 'id_country',
'name' => 'name'
),
'desc' => $this->l('Mark all the countries you want to block the selling to. The restrictions will always be applied to every subcategory as well')
),
Now, I can save these values by checking if the value "submitAddcategory" is being submitted in the postProcess function and by running an insert query there. Similarly, I can also load the IDs of the blocked countries from the database, but how can I tick the respective select boxes in the list of countries?
My initial "quick and dirty" idea was to use jQuery selectors inside a document.ready(), but the code gets inserted before everything else and, as such, it won't work because jQuery isn't even loaded yet.
How can this be done?
Cheers
I solved it by using the following code right before the end of the renderForm() function.
The Pièce de résistance was $this->fields_value, as sadly I didn't known of its existence.
public function getRestrictedCountries($obj)
{
// Loading blacklisted countries
$country = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('
SELECT DISTINCT id_country
FROM `'._DB_PREFIX_.'category_country_restriction`
WHERE id_category = ' . (int)Tools::getValue('id_category') . ';');
$blacklisted_countries = array();
if (is_array($country))
foreach ($country as $cnt)
$blacklisted_countries[] = $cnt['id_country'];
// Global country list
$c_todos = Country::getCountries(Context::getContext()->language->id);
// Crossmatching everything
foreach ($c_todos as $c)
$this->fields_value['restricted_countries_'.$c['id_country']] = Tools::getValue('restricted_countries_'.$c['id_country'], (in_array($c['id_country'], $blacklisted_countries)));
}
PS: The table I am reading from is basically an associative table between 'category' and 'country'

Set Magento Attribute to Configurable Product with Soap API

I need to create a new configurable product via Magento Soap API and add a related product to it.
I use this code that create 2 products ( one simple and one configur. ) then i try to link the simple one to the config one...this don't work..
There is a tutorial for do that??
Any help??
Many thanks.
// Magento login information
$mage_url = 'http://test.de/api/?wsdl';
$mage_user = 'admin';
$mage_api_key = 'admin';
// Initialize the SOAP client
$soap = new SoapClient( $mage_url );
// Login to Magento
$session = $soap->login( $mage_user, $mage_api_key );
$attributeSets = $soap->call($session,'product_attribute_set.list');
$set = current($attributeSets);
$sku = 'iphone-12345';
//configurable
$newProductData = array(
'name' => 'iPhone',
'websites' => array(1),
'short_description' => 'short description',
'description' => 'description',
'price' => 150,
'status' => '1',
'categories' => array(138),
);
$newProductRelated = array(
'name' => 'iPhone',
'websites' => array(1),
'short_description' => 'short description',
'description' => 'description',
'price' => 150,
'status' => '1',
'sku' => '2551464'
);
$productId = $soap->call($session,'product.create',array('configurable', $set['set_id'], $sku ,$newProductData));
$productId2 = $soap->call($session,'product.create',array('simple', $set['set_id'], $newProductRelated['sku'] ,$newProductRelated));
$soap->call($session, 'product_link.assign', array('configurable', $sku, $newProductRelated['sku'], array('position'=>0, 'colore'=> 21, 'qty'=>6)));
mant thx again.
Dealing with a similar issue and resorted to using the CSV import to create the relation for products imported from the API. This may may be a usable approach for a one time import via a generated CSV.