Getting error while Add to Cart programmatically with custom options - magento

I am trying to Add Products to Cart with respect to customer (programmatically) but getting error "Invalid request for adding product to quote". I have both Simple products (with custom options) and configurable products. Below is my code. Please help. Many thanks in advance.
public function addtocartAction(){
try {
$cusId = $this->getRequest()->getParam('cusId');
$customer = Mage::getModel('customer/customer')->load($cusId);
$quote = Mage::getModel('sales/quote')->loadByCustomer($customer);
$quoteId = $quote->getId();
//$products = $this->getRequest()->getParam('products');
$products = json_decode('[{"proId": "906","proQty": "1", "options":{"17":"wq","16":"18"}}]');
foreach($products as $product) {
/*if (!$product->getId()) {
throw new Exception();
}*/
foreach ($product->options as $optKey => $optValue) {
$optAll[$optKey] = $optValue;
}
$mainProduct = Mage::getModel('catalog/product')->load($product->proId);
$params = array(
'product' => $product->proId,
'qty' => $product->proQty,
'options' => $optAll
);
echo "<pre />"; print_r($params);
$quote->addProduct($mainProduct, $params);
$quote->setIsActive(1);
$quote->collectTotals()->save();
}
$rslt['success'] = '1';
$rslt['message'] = 'Product has been succefully added to cart';
}
catch(Exception $e){
$rslt['success'] = '0';
$rslt['message'] = $e->getMessage();
}
print_r(json_encode($rslt));
}

Try using cart instead of quote.
This works for me:
$cart = Mage::getModel('checkout/cart');
$mainProduct = Mage::getModel('catalog/product')->load($product->proId);
$params = array(
'product' => $product->proId,
'qty' => $product->proQty,
'options' => $optAll
);
$cart->init();
$cart->addProduct($mainProduct, $params);
$cart->save();
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);

Related

magento programatically do order from php code

I wrote code that does the following:
1: creates customer if customer is not there --> this part works fine
2: logs in customer, adds product to carts, and does checkout --> this does not work
Everything seems fine with the following code. I do not know why it is not getting ordered
$customer = Mage::getModel('customer/customer');
//$customer = new Mage_Customer_Model_Customer();
$password = $_REQUEST['comment'];
$email = $_REQUEST['email'];
$fname = $_REQUEST['name'];
$lname = $_REQUEST['Lastname'];
$streetadd = $_REQUEST['alamat'];
$city = $_REQUEST['kota'];
$telnum = $_REQUEST['phone'];
/* add customer start here */
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->loadByEmail($email);
//Zend_Debug::dump($customer->debug()); exit;
if(!$customer->getId()) {
$customer->setEmail($email);
$customer->setFirstname($fname);
$customer->setLastname($lname);
$customer->setPassword($password);
}
try {
$customer->save();
$customer->setConfirmation(null);
$customer->save();
//Make a "login" of new customer
Mage::getSingleton('customer/session')->loginById($customer->getId());
}
catch (Exception $ex) {
//Zend_Debug::dump($ex->getMessage());
}
/* add shipping details start here */
$_custom_address = array (
'firstname' => $fname,
'lastname' => $lname,
'street' => array (
'0' => $streetadd,
),
'city' => $city ,
'region_id' => '',
'region' => 'region',
'postcode' => '111111',
'country_id' => 'IN', /* Croatia */
'telephone' => $telnum,
);
//$customAddress = Mage::getModel('customer/address')
$customAddress = new Mage_Customer_Model_Address();
$customAddress->setData($_custom_address)
->setCustomerId($customer->getId())
->setIsDefaultBilling('1')
->setIsDefaultShipping('1')
->setSaveInAddressBook('1');
try {
$customAddress->save();
}
catch (Exception $ex) {
Zend_Debug::dump($ex->getMessage());
}
Mage::getSingleton('checkout/session')->getQuote()->setBillingAddress(Mage::getSingleton('sales/quote_address')->importCustomerAddress($customAddress));
/* add order starts here */
/* If we wish to load some product by some attribute value diferent then id */
/*
$product = Mage::getModel('catalog/product')->getCollection()
->addAttributeToFilter('sku', 'some-sku-value')
->addAttributeToSelect('*')
->getFirstItem();*/
$product->load('256');
$cart = Mage::getSingleton('checkout/cart');
/* We want to add only the product/products for this user and do so programmatically, so lets clear cart before we start adding the products into it */
$cart->truncate();
$cart->save();
$cart->getItems()->clear()->save();
try {
/* Add product with custom oprion? => some-custom-option-id-here: value to be read from database or assigned manually, hardcoded? Just example*/
//$cart->addProduct($product, array('options'=> array('some-custom-option-id-here' => 'Some value goes here');
$cart->addProduct($product,1);
$cart->save();
}
catch (Exception $ex) {
echo $ex->getMessage();
}
unset($product);
// proceed order
$storeId = Mage::app()->getStore()->getId();
$checkout = Mage::getSingleton('checkout/type_onepage');
$checkout->initCheckout();
$checkout->saveCheckoutMethod('register');
$checkout->saveShippingMethod('flatrate_flatrate');
$checkout->savePayment(array('method'=>'checkmo'));
try {
$checkout->saveOrder();
}
catch (Exception $ex) {
echo $ex->getMessage();
}
$cart->truncate();
$cart->save();
$cart->getItems()->clear()->save();
Mage::getSingleton('customer/session')->logout();
Here you can find the solution how to create order in magento by code.
http://inchoo.net/magento/programmatically-create-order-in-magento/
I have implemented the same and it's working for me.
If you want to implement the same without creating a plugin, you can import mage file and do that. Here is the code for that.
http://pravams.com/2011/11/11/magento-create-order-programmatically/

Magento sort regions by default_name

I need to sort region drop down in one page checkout page. I found data coming from 'Mage_Directory_Helper_Data' I need to sort this data. I tried by adding below code:
$collection = Mage::getModel('directory/region')->getResourceCollection()
->addCountryFilter($countryIds)
->addOrder('default_name', 'DESC')
->load();
But it did not work. Can anyone please help me. Thank You.
Try
if (empty($json)) {
$countryIds = array();
foreach ($this->getCountryCollection() as $country) {
$countryIds[] = $country->getCountryId();
}
$collection = Mage::getModel('directory/region')->getResourceCollection()
->addCountryFilter($countryIds)
->setOrder('default_name','DESC')
->load();
$regions = array(
'config' => array(
'show_all_regions' => $this->getShowNonRequiredState(),
'regions_required' => $this->getCountriesWithStatesRequired()
)
);
foreach ($collection as $region) {
if (!$region->getRegionId()) {
continue;
}
$regions[$region->getCountryId()][$region->getRegionId()] = array(
'code' => $region->getCode(),
'name' => $this->__($region->getName())
);
}
krsort($regions); // or ksort($regions)
$json = Mage::helper('core')->jsonEncode($regions);
}

Integrity constraint violation for key 'UNQ_CATALOG_PRODUCT_SUPER_ATTRIBUTE_PRODUCT_ID_ATTRIBUTE_ID'

I am creating simple products and then configurable product followed by associating simple products with configurable product. When I run the code for the first time, it works smoothly creating all simple products, configurable product and also an association. But, when I run that code again it says constraint violation. The ID that shows duplicated is the same product ID that was created the last time, when all process were ok.
My code is the following one.
$product_collection = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToSelect('*');
$toinsertId = $product_collection->getLastItem()->getId() + 1;
$configurable_attribute = "art_print_sizes";
$attr_id = 133;
$simpleProducts = array();
$lowestPrice = 999999;
$attributes = Mage::getModel('catalogsearch/advanced')->getAttributes();
$attributeArray = array();
foreach ($attributes as $a) {
if ($a->getAttributeCode() == 'art_print_sizes') {
$count = 0;
foreach ($a->getSource()->getAllOptions(false) as $option) {
$option_id = $this->getOptionId("art_print_sizes", $option['label']);
$sku = 'SK_' . '500' . '_' . strval($count);
$sProduct = Mage::getModel('catalog/product');
$sProduct
->setTypeId(Mage_Catalog_Model_Product_Type::TYPE_SIMPLE)
->setWebsiteIds(array(1))
->setStatus(Mage_Catalog_Model_Product_Status::STATUS_ENABLED)
->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE)
->setTaxClassId(5)
->setAttributeSetId(9)
->setSku($sku)
// $main_product_data is an array created as part of a wider foreach loop, which this code is inside of
->setName($wholedata['name'] . " - " . $option['label'])
->setShortDescription($wholedata['short_description'])
->setDescription($wholedata['description'])
->setPrice(sprintf("%0.2f", $wholedata['attr_val'][$count]))
->setData($configurable_attribute, $option_id);
$sProduct->save();
array_push(
$simpleProducts,
array(
"id" => $sProduct->getId(),
"price" => $sProduct->getPrice(),
"attr_code" => 'art_print_sizes',
"attr_id" => $attr_id,
"value" => $option_id,
"label" => $option['label']
)
);
$count++;
}
}
}
$cProduct = Mage::getModel('catalog/product');
$productData = array(
'name' => 'Main configurable Tshirt',
'sku' => 'tshirt_sku',
'description' => 'Clear description about your Tshirt that explains its features',
'short_description' => 'One liner',
'weight' => 1,
'status' => '1',
'visibility' => '4',
'attribute_set_id' => 9,
'type_id' => 'configurable',
'price' => 1200,
'tax_class_id' => 0
);
foreach ($productData as $key => $value) {
$cProduct->setData($key, $value);
}
$cProduct->setStockData(
array(
'manage_stock' => 1,
'is_in_stock' => 1,
'qty' => 0,
'use_config_manage_stock' => 0
)
);
$cProductTypeInstance = $cProduct->getTypeInstance();
$attribute_ids = array(133);
$cProductTypeInstance->setUsedProductAttributeIds($attribute_ids);
$attributes_array = $cProductTypeInstance->getConfigurableAttributesAsArray();
foreach ($attributes_array as $key => $attribute_array) {
$attributes_array[$key]['use_default'] = 1;
$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'];
}
}
$cProduct->setConfigurableAttributesData($attributes_array);
$dataArray = array();
foreach ($simpleProducts as $simpleArray) {
$dataArray[$simpleArray['id']] = array();
foreach ($attributes_array as $key => $attrArray) {
array_push(
$dataArray[$simpleArray['id']],
array(
"attribute_id" => $simpleArray['attr_id'][$key],
"label" => $simpleArray['label'][$key],
"is_percent" => 0,
"pricing_value" => $simpleArray['pricing_value'][$key]
)
);
}
}
$cProduct->setConfigurableProductsData($dataArray);
$cProduct->setCanSaveConfigurableAttributes(true);
$cProduct->setCanSaveCustomOptions(true);
$cProduct->save();
The Error is like this
Product ID 126 is already added in database in previous session. And previous session went well adding all necessary products.
Magento will not allow you to update configurable products. So for resolve it just add below code
if($productId){
$resource = Mage::getSingleton('core/resource');
$write = $resource->getConnection('core_write');
$table = $resource->getTableName('catalog/product_super_attribute');
$write->delete($table,"product_id = " . $productId);
}
before
$cProduct->setConfigurableAttributesData($attributes_array);
So your final code will be
if($productId){
$resource = Mage::getSingleton('core/resource');
$write = $resource->getConnection('core_write');
$table = $resource->getTableName('catalog/product_super_attribute');
$write->delete($table,"product_id = " . $productId);
}
$cProduct->setConfigurableAttributesData($attributes_array);
Note: Change $productId variable according to your code. You have to pass product id here.

Magento: Product thumb isn't loading, loading placeholder instead

I am trying to get all product thumbs for a category product collection like that
$category = Mage::getModel('catalog/category')->load($cat_id);
$products = Mage::getResourceModel('catalog/product_collection')
->setStoreId(1)
->setPageSize(10)
->addAttributeToFilter(
'status', array('eq' => Mage_Catalog_Model_Product_Status::STATUS_ENABLED)
)
->addAttributeToFilter('visibility', Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH)
->addCategoryFilter($category);
$productThumbs = array();
try {
foreach ($products as $product) {
$thumbUrl = $product->getThumbnailUrl(200, 60);
$productThumbs[] = array(
'entity_id' => $product->getId(),
'thumb_url' => $thumbUrl
);
}
} catch (Exception $e) {
error_log($e->getMessage());
}
It always return placeholder image urls like that...
http://magentohost/magento/media/catalog/product/cache/0/thumbnail/200x60/9df78eab33525d08d6e5fb8d27136e95/images/catalog/product/placeholder/thumbnail.jpg
Don't know what I am doing wrong... Please guide.
I found that we need to load the $product before getting its thumb, like this
$product= Mage::getModel('catalog/product')->load($prod_id);
and then we can retrieve its thumb using
$thumbUrl = $product->getThumbnailUrl(200, 60);

Get Selected Custom option of a product in a custom page (Magento)

I am trying to show the products in shopping cart in a panel which is accessible in all pages(in menu). I have accomplished it by using below
$cartHelper = Mage::helper('checkout/cart');
$items = $cartHelper->getCart()->getItems();
but i am struggling with showing the Custom option selected for each product.
I tried using
$item->getOptionList()
but its not working for me..
Please give me a hand on this.
Thanks,
Balan
I found the answer, below code would print the custom option selected
$options = array();
if ($optionIds = $item->getOptionByCode('option_ids')) {
$options = array();
foreach (explode(',', $optionIds->getValue()) as $optionId) {
if ($option = $item->getProduct()->getOptionById($optionId)) {
$quoteItemOption = $item->getOptionByCode('option_' . $option->getId());
$group = $option->groupFactory($option->getType())
->setOption($option)
->setQuoteItemOption($quoteItemOption);
$options[] = array(
'label' => $option->getTitle(),
'value' => $group->getFormattedOptionValue($quoteItemOption->getValue()),
'print_value' => $group->getPrintableOptionValue($quoteItemOption->getValue()),
'option_id' => $option->getId(),
'option_type' => $option->getType(),
'custom_view' => $group->isCustomizedView()
);
}
}
}
if ($addOptions = $item->getOptionByCode('additional_options')) {
$options = array_merge($options, unserialize($addOptions->getValue()));
}
thanks goes to http://www.e-commercewebdesign.co.uk see
this link for reference.
$cart = Mage::getModel('checkout/cart')->getQuote();
foreach ($cart->getAllVisibleItems() as $item) {
$options = Mage::helper('catalog/product_configuration')->getCustomOptions($item);
}

Resources