Echo custom options with the values for Magento - php

How to echo all custom options with all the values by product id for Magento?
If i am using this code...
public function ws_productdetail($store_id, $service, $productid)
{
$res=array();
$productsCollection = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToFilter('entity_id', array('in' => $productid))
->addAttributeToSelect('*');
$all_product_images = array();
$product = Mage::getModel('catalog/product')->load($productid);
foreach ($product->getMediaGalleryImages() as $image) {
$all_product_images[] = $image->getUrl();
}
foreach($productsCollection as $product)
{
$res["id"] = $product->getId();
$res["name"] = $product->getName();
$res["price"] = number_format($product->getPrice(),2);
}
return($res);
}
... how can I get the custom options?
For example say for a product JEANS, COLOR with various values {blue,black,brown} and every option will have different prices, then how i get all this information as output.

According to my understanding, you want to show the all DROPDOWN custom option on view page then try this.
$productid = $_product->getId(); //PLEASE ENTER THE PRODUCT ID HERE
$product = Mage::getModel("catalog/product")->load($productid);
$attVal = $product->getOptions();
$optStr = "";
foreach($attVal as $optionKey => $optionVal)
{
$optStr.='<dl><div class="custom_select_css">
<dt><label>'.$optionVal->getTitle().'</label></dt>
<dd class="last">
<div class="input-box">';
$optStr.= "<select id='".$optionVal->getId()."' name='options[".$optionVal->getId()."]'>";
foreach($optionVal->getValues() as $valuesKey => $valuesVal)
{
$price = number_format($valuesVal->getPrice(),0);
$optStr.= "<option price='".number_format($valuesVal->getPrice(),0)."' data-label='".$colorarray[$valuesVal->getTitle()]."' value='".$valuesVal->getId()."'>".$valuesVal->getTitle(); if($price != '0'){$optStr.=" +$".number_format($valuesVal->getPrice(),2);}$optStr.=" </option>";
}
$optStr.= "</select></div></dd><div></dl>";
}
echo $optStr;
------------------------------ UPDATED CODE -------------------------------
public function ws_customdetail ($productid)
{
$all_custom_option_array = array();
$product = Mage::getModel("catalog/product")->load($productid);
$attVal = $product->getOptions();
$optStr = "";
$inc=0;
foreach($attVal as $optionKey => $optionVal)
{
$all_custom_option_array[$inc]['custom_option_name']=$optionVal->getTitle();
$all_custom_option_array[$inc]['custom_option_id']=$optionVal->getId();
$inner_inc =0;
foreach($optionVal->getValues() as $valuesKey => $valuesVal)
{
$all_custom_option_array[$inc]['custom_option_value_array'][$inner_inc]['title'] = $valuesVal->getTitle();
$all_custom_option_array[$inc]['custom_option_value_array'][$inner_inc]['price'] = number_format($valuesVal->getPrice(),0);
$inner_inc++;
}
$inc++;
}
return $all_custom_option_array;
}
Use ws_customdetail function and pass the product id in it.

THIS IS THE EXACT CODE THAT WORKED FOR ME.
public function customdetail($productid){
$all_custom_option_array = array();
$product = Mage::getModel("catalog/product")->load($productid);
$attVal = $product->getOptions();
$optStr = "";
$inc=0;
foreach($attVal as $optionKey => $optionVal){
$all_custom_option_array[$inc]['custom_option_name']=$optionVal->getTitle();
$all_custom_option_array[$inc]['custom_option_id']=$optionVal->getId();
$all_custom_option_array[$inc]['custom_option_type']=$optionVal->getType();
$all_custom_option_array[$inc]['custom_option_value_array'];
$inner_inc =0;
foreach($optionVal->getValues() as $valuesKey => $valuesVal){
$all_custom_option_array[$inc]['custom_option_value_array'][$inner_inc]['title'] = $valuesVal->getTitle();
$all_custom_option_array[$inc]['custom_option_value_array'][$inner_inc]['price'] = number_format($valuesVal->getPrice(),0);
$inner_inc++;}
$inc++;}
return $all_custom_option_array;}
HOPE THIS WILL HELP SOMEONE :)
THANX

Related

How to Programatically cancel order in magento 2

If a customer placed an order of 3 different items with different quantities like
shirt 2 qty
Watch 1qty
pant 3qty
and cancels the order item at different times I have to set the state to order cancelled
here's my code can anyone please tell me where I am wrong
if (isset($_POST['order'])) {
$_orderCollectionFactory = $objectManager->create('\Magento\Sales\Model\ResourceModel\Order\CollectionFactory');
$collection = $_orderCollectionFactory->create()
->addFieldToSelect('*')
->addFieldToFilter('status', ['neq' => 'cancelled']);
foreach ($collectionFactory as $order)
{
$items = $order->getAllVisibleItems();
foreach ($items as $items) {
$totalitem = $totalitem + ($item['qty_canceled']);
$itemcount = $order->getQtyOrdered();
if ($itemcount == ($totalitem))
{
$order->setState("canceled");
$order->save();
}
}
}
}
Finally, I have Solved the issue for the above code
$_orderCollectionFactory = $objectManager->create('\Magento\Sales\Model\ResourceModel\Order\CollectionFactory');
$collection = $_orderCollectionFactory->create()
->addFieldToSelect('*')
->addFieldToFilter('status', ['neq' => 'cancelled']);
foreach ($collection as $order)
{
$items = $order->getAllVisibleItems();
$totalitem=0;
foreach ($items as $item) {
// echo '<pre>';print_r(get_class_methods($item));
// die();
$totalitem = $totalitem + ($item['qty_canceled']);
$itemcount = $order->getQtyOrdered();
if ($itemcount == ($totalitem))
{
echo $order->getIncrementId();
$order->setState("canceled");
$order->setStatus("canceled");
$order->save();
}
}
}

Programmatically Create configurable product in Magento 2.1 Issue

I facing issue while creating configurable product in Magento 2.1 programmatically. I'm reading products from xml and save. The issue is when i associate simple product with configurable product. Products are created successfully. But configurable product associated products are not shown on backend. Here is my code:
<?php
/**
* Created by PhpStorm.
* User: Muhammad Noman Rauf
* Date: 15/12/2016
* Time: 1:15 AM
*/
use Magento\Framework\App\Bootstrap;
error_reporting(E_ALL);
ini_set("display_errors", 1);
if (file_exists('Export_Products_20170104_152014.xml')) {
$content = simplexml_load_file('Export_Products_20170104_152014.xml', 'SimpleXMLElement', LIBXML_NOCDATA);
include('app/bootstrap.php');
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$_categoryFactory = $objectManager->get('Magento\Catalog\Model\CategoryFactory');
$url = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager = $url->get('\Magento\Store\Model\StoreManagerInterface');
$mediaurl = $storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
/// Get Website ID
$websiteId = $storeManager->getWebsite()->getWebsiteId();
/// Get Store ID
$store = $storeManager->getStore();
$storeId = $store->getStoreId();
/// Get Root Category ID
$rootNodeId = $store->getRootCategoryId();
/// Get Root Category
$rootCat = $objectManager->get('Magento\Catalog\Model\Category');
$cat_info = $rootCat->load($rootNodeId);
$product = $objectManager->get('Magento\Catalog\Model\Product');
foreach ($content as $key => $value) {
echo "<pre>";
$_product = $objectManager->create('Magento\Catalog\Model\Product');
//print_r($value->images);
$sku = $value->ID;
$name = $value->name;
$description = $value->commercial_desc;
$catgory = $value->category;
$color = array();
if (isset($value->prices) && !empty($value->prices)) {
foreach ($value->prices->pricelist as $k => $v):
$vn = (array)$v;
ksort($vn);
if ($vn['currency'] == 'EUR') {
$price = $vn['price'];
}
endforeach;
}
if (isset($value->images) && !empty($value->images)) {
foreach ($value->images->img_url as $k => $v):
$v;
endforeach;
}
if (isset($value->colors) && !empty($value->colors)) {
foreach ($value->colors->color as $k => $v):
$color[] = $v->Description;
foreach ($v->sizes->size as $sizes => $size) {
$s = $size->ID;
}
if (isset($v->images) && !empty($v->images->img_url)) {
foreach ($v->images->img_url as $imgs => $img) {
$color_img = $img;
}
}
endforeach;
}
$collection = $_categoryFactory->create()->getCollection()->addFieldToFilter('name', $catgory);
if ($collection->getSize()) {
$categoryId = $collection->getFirstItem()->getId();
$categoryId;
} else {
$name = ucfirst($catgory);
$url = strtolower($catgory);
$cleanurl = trim(preg_replace('/ +/', '', preg_replace('/[^A-Za-z0-9 ]/', '', urldecode(html_entity_decode(strip_tags($url))))));
/// Add a new sub category under root category
$categoryTmp = $_categoryFactory->create();
$categoryTmp->setName($name);
$categoryTmp->setIsActive(true);
$categoryTmp->setUrlKey($cleanurl);
$categoryTmp->setData('description', $catgory);
$categoryTmp->setParentId(2);
$categoryTmp->setStoreId($storeId);
$categoryTmp->setPath($rootCat->getPath());
$categoryTmp->save();
$categoryId = $categoryTmp->getId();
}
if ($product->getIdBySku($sku)) {
echo "already in database " . $sku . " Please change name and sku in xml file.";
continue;
} else {
/** #var \Magento\Catalog\Api\ProductAttributeRepositoryInterface $attributeRepo */
$attributeRepo = $objectManager->get(\Magento\Catalog\Api\ProductAttributeRepositoryInterface::class);
$attribute = $attributeRepo->get('color'); // color should be in default attribute set
$ids = [];
$values = [];
$_product->setName($name);
$_product->setTypeId('configurable');
$_product->setAttributeSetId(4);
$_product->setSku($sku);
$_product->setDescription($description);
$_product->setShortDescription($description);
$_product->setWebsiteIds(array($websiteId));
$_product->setVisibility(4);
$_product->setPrice($price);
$_product->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
$_product->setCategoryIds(array($categoryId));
$_product->setImage('img1.jpg');
$_product->setSmallImage('img1.jpg');
$_product->setThumbnail('img1.jpg');
$_product->setStockData(
array(
'use_config_manage_stock' => 0, //'Use config settings' checkbox
'manage_stock' => 1, //manage stock
'min_sale_qty' => 1, //Minimum Qty Allowed in Shopping Cart
'max_sale_qty' => 2, //Maximum Qty Allowed in Shopping Cart
'is_in_stock' => 1, //Stock Availability
'qty' => 100 //qty
)
);
$_product->save();
foreach ($attribute->getOptions() as $option) {
$label = $option->getLabel();
if (in_array($label, $color)) {
$id = $option->getValue();
/** #var \Magento\Catalog\Api\Data\ProductInterface $p */
$p = $objectManager->create('Magento\Catalog\Model\Product');
$p->setSku($sku . '-' . $option->getLabel());
$p->setName($sku . '-' . $option->getLabel());
$p->setPrice($price);
$p->setTypeId('virtual');
$p->setColor($option->getValue());
$p->setWebsiteIds(array($websiteId));
$p->setCategoryIds(array($categoryId));
$p->setAttributeSetID($id);
$p->setVisibility(Magento\Catalog\Model\Product\Visibility::VISIBILITY_NOT_VISIBLE);
$p->setAttributeSetId(4);
$p->save();
$ids[] = $p->getId();
/** #var \Magento\ConfigurableProduct\Api\Data\OptionValueInterface $opVal */
$opVal = $objectManager->create(\Magento\ConfigurableProduct\Api\Data\OptionValueInterface::class);
$opVal->setValueIndex($id);
$values[] = $opVal;
}
}
/* IF CODE NOT WORKED PLEASE REMOVE THIS CODE : START REMOVE*/
$pro = $objectManager->create('Magento\Catalog\Model\Product')->load($_product->getId()); // Load Configurable Product
$attributeModel = $objectManager->create('Magento\ConfigurableProduct\Model\Product\Type\Configurable\Attribute');
$position = 0;
$attributes = array($attribute->getAttributeId()); // Super Attribute Ids Used To Create Configurable Product
foreach ($attributes as $attributeId) {
$data = array('attribute_id' => $attributeId, 'product_id' => $_product->getId(), 'position' => $position);
$position++;
$attributeModel->setData($data)->save();
}
$pro->setTypeId("configurable"); // Setting Product Type As Configurable
$pro->setAffectConfigurableProductAttributes(4);
$objectManager->create('Magento\ConfigurableProduct\Model\Product\Type\Configurable')->setUsedProductAttributeIds($attributes, $pro);
$pro->setNewVariationsAttributeSetId(4); // Setting Attribute Set Id
$pro->setAssociatedProductIds($ids);// Setting Associated Products
$pro->setCanSaveConfigurableAttributes(true);
$pro->save();
/* IF CODE NOT WORKED PLEASE REMOVE THIS CODE : END REMOVE*/
echo "New Product id:" . $_product->getId() . '<br>';
}
//print_r($_product->getData());
}
} else {
exit('Failed to open xml.');
}
I also followed other solution but can't find any solution.
link 1
link2
link3
Do not forget to use store id in your import.
Set store ID "0".
public function setConfigurable_oldfunc($config_id,$simple_prod_id){
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager = $objectManager->get('Magento\Store\Model\StoreManagerInterface');
$store = $storeManager->getStore(0);
$storeManager->setCurrentStore($store->getCode());
$productId = $config_id; // Configurable Product Id
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($productId); // Load Configurable Product
$attributeModel = $objectManager->create('Magento\ConfigurableProduct\Model\Product\Type\Configurable\Attribute');
$position = 0;
$attributes = array(160); // Super Attribute Ids Used To Create Configurable Product
$associatedProductIds = array($simple_prod_id);
$optionsData = $product->getTypeInstance(true)->getUsedProducts($product);
$array_ids = array();
if(is_array($array_ids) && !empty($array_ids)){
}else{
foreach ($attributes as $attributeId) {
$data = array('attribute_id' => $attributeId, 'product_id' => $productId, 'position' => $position);
$position++;
$attributeModel->setData($data)->save();
}
}
$objectManager->create('Magento\ConfigurableProduct\Model\Product\Type\Configurable')->setUsedProductAttributeIds($attributes, $product);
$product->setTypeId("configurable"); // Setting Product Type As Configurable
$product->setAffectConfigurableProductAttributes(4);
$product->setNewVariationsAttributeSetId(4); // Setting Attribute Set Id
$product->setAssociatedProductIds($associatedProductIds);// Setting Associated Products
$product->setCanSaveConfigurableAttributes(true);
$product->setStoreId(0);
$product->save();
}

Why doesn't my shopping cart count products of the same type?

This is the code so far.
I know its not very secure for injections, I'll take care of that later.
but my problem is that my cart adds product but sometimes i get the:
Unsupported operand types in E:\HostingSpaces\Knoppers1\topjop.nl\wwwroot\portal\core\tj_functions.php on line 358
error and i can't add multiple items of the same type.
line 358: $_SESSION['cart'][$uid] += 1;//
Maybe some of you know because other related questions didn't helped me.
function toevoegen(){
session_start();
if(!isset($_SESSION['cart'])){
$_SESSION['cart'] = array();
}
if(isset($_GET['add'])) {
$info = 'U heeft een product toegevoegd <META HTTP-EQUIV=REFRESH CONTENT="1; URL=http://topjop.nl/portal/winkelmandje.php">';
$uid = 0; //update id
foreach($_SESSION['cart'] as $id => $data){
if($data[0]==$_GET['add']){
$uid = $id;//
}
}
if($uid == 0){
array_push($_SESSION['cart'],array($_GET['add'],1));//
}else{
$_SESSION['cart'][$uid] += 1;//
}
}
else {
$info = '';
}
return $info;
}
function winkelmandje(){
mysql_connect("mysql8.mijnhostingpartner.nl","","");
mysql_select_db("Knoppers1_portal");
session_start();
$mand = '<table id="winkelmandje_tabel"><tr><td>Product</td>
<td>Stukprijs</td><td>Aantal</td><td>Totaal bedrag</td><td></td></tr>';
foreach($_SESSION['cart'] as $data){
$id = $data[0];//
$value = $data[1];//
if($value>0){
$get = mysql_query('SELECT id, name, price FROM products WHERE id='.mysql_real_escape_string((int)$id));
while ($get_row = mysql_fetch_assoc($get)) {
$totaal = $get_row['price']*$value;
$totaalprijs = number_format($totaal,2,',','.');
$mand .= '<tr><td>'.$get_row['name'].'</td>
<td>€'.$get_row['price'].'</td><td>'. $value .'</td> <td>€'.$totaalprijs.'</td></tr>';
}
}
else{
}
}
$aantal = '';
$kosten = '';
return $mand.'<tr><td><b>Totaal:</b></td><td></td><td><b>'. $aantal .'</b></td><td><b>'. $kosten .'</b></td></tr></table>';
}
toevoegen = ADD<br>
winkelmandje = SHOPPINGCART
Seems like $_SESSION['cart'][$uid] is an array containing id and value as you read it like that in the follwoing snippet:
$id = $data[0];//
$value = $data[1];//
it seems $_SESSION['cart'][$uid] is an array. so you can't do +=1
maybe do
$_SESSION['cart'][$uid][1] += 1; // increment $value

how to get multiple categories and subcategories for a product in a custom script in magento

i'm trying to build a feed generator based on this post Magento: Product data extraction for product feed. for the time beeing my problem is with the categories and subcategories of the product.
my code:
<?php
error_reporting(E_ALL | E_STRICT);
ini_set("display_errors", 1);
define('SAVE_FEED_LOCATION','feed/compari.csv');
//$objDateTime = new DateTime('NOW');
require 'app/Mage.php';
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$products = Mage::getModel('catalog/product')->getCollection();
$products->addAttributeToFilter('status', 1); //1 is set to select product in stock
$products->addAttributeToFilter('visibility', 4); //4 is set to select active products
$products->addAttributeToSelect('*');
$prodIds=$products->getAllIds();
$product = Mage::getModel('catalog/product');
$counter = 0;
$feedaray=[];
foreach($prodIds as $productId) {
if (++$counter < 500000){
$product->load($productId);
$title_temp = $product->getName();
if (strlen($title_temp) > 255){
$title_temp = str_replace("Supply", "", $title_temp);
$title_temp = str_replace(" ", " ", $title_temp);
} //$title_temp will hold the product name
$maincat = $subcats = '';
$categoryCollection = $product->getCategoryCollection();
if i do a var_dump($title_temp.' categorie: '.$categorie_id);
foreach($categoryCollection as $cat){
$categorie_id=$cat->getData()['entity_id'];
$_cat_ac = Mage::getModel('catalog/category')->load($categorie_id);
if($subcats_ac == ''){
$maincat_ac = $subcats_ac = $_cat_ac->getName();
}else {
$subcats_ac .= ">".$_cat_ac->getName();
}
echo '<pre>';
var_dump($title_temp.' categorie: '.$categorie_id);
echo '</pre>';
}
i'm geting the corect result:
string(59) "product 1 categorie: 3" - prime category
string(60) "product 1 categorie: 37" - sub category
string(45) "product 2 categorie: 4" - prime category
string(46) "product 2 categorie: 21" - sub category
further i need to prepare the data for exporting to csv, and i do it like this:
$stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($productId);
$product_data = array();
$product_data['ProductID'] = $productId;
$product_data['ProductName'] = substr(iconv("UTF-8","UTF-8//IGNORE",$title_temp), 0, 255);
$product_data['SKUnumber'] = $product->getSku();
$product_data['PrimaryCategory'] = $maincat_ac; //this is spitting same data for all products
$product_data['SecondaryCategory'] = $subcats_ac; //this is spitting same data for all products
$product_data['ProductURL'] = $StoreURL.$product->getUrlPath(); //$StroeURL is set as a string
$product_data['ProductImageURL'] = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA).'catalog/product'.$product->getImage();
$product_data['ShortProductDescription'] = substr(iconv("UTF-8","UTF-8//IGNORE",$product->getDescription()), 0, 80)."...";
$product_data['LongProductDescription'] = substr(iconv("UTF-8","UTF-8//IGNORE",$product->getDescription()), 0, 2000);
$product_data['SalePrice'] = round($product->getFinalPrice(),2);
$product_data['RetailPrice'] = round($product->getPrice(),2);
$product_data['ManufacturerName'] =$product->getAttributeText('manufacturer');
$product_data['Quantity'] = round($stock->getQty(),2);
$product_data['Currency'] = Mage::app()->getStore()->getCurrentCurrencyCode();
foreach($product_data as $k=>$val){
$bad=array('"',"\r\n","\n","\r","\t");
$good=array(""," "," "," ","");
$product_data[$k] = str_replace($bad,$good,$val);
}
$feedaray[]=$product_data;
echo $counter . " ";
}
}
$handle=fopen(SAVE_FEED_LOCATION, 'w');
foreach ($feedaray as $fields) {
fputcsv($handle, $fields);
}
fclose($handle);
?>
the problem is with the maincat_ac and subcat_ac that are not displaing corect data.
solution for the problem
$cats=[];
foreach($categoryCollection as $cat){
$cats[]=$cat->getData()['entity_id'];
}
foreach ($cats as $category_id) {
$_cat = Mage::getModel('catalog/category')->load($category_id) ;
if($subcats == ''){
$maincat = $subcats = $_cat->getName();
}else {
$subcats .= ">".$_cat->getName();
}
}
may be it isn't the best solution. if you have another idea please share.
regards

Create order programmatically in Magento

I'm using these two methods to create orders programmatically in Magento.
The first one creates a Quote:
public function prepareCustomerOrder($customerId, array $shoppingCart, array $shippingAddress, array $billingAddress,
$shippingMethod, $couponCode = null)
{
$customerObj = Mage::getModel('customer/customer')->load($customerId);
$storeId = $customerObj->getStoreId();
$quoteObj = Mage::getModel('sales/quote')->assignCustomer($customerObj);
$storeObj = $quoteObj->getStore()->load($storeId);
$quoteObj->setStore($storeObj);
// add products to quote
foreach($shoppingCart as $part) {
$productModel = Mage::getModel('catalog/product');
$productObj = $productModel->setStore($storeId)->setStoreId($storeId)->load($part['PartId']);
$productObj->setSkipCheckRequiredOption(true);
try{
$quoteItem = $quoteObj->addProduct($productObj);
$quoteItem->setPrice(20);
$quoteItem->setQty(3);
$quoteItem->setQuote($quoteObj);
$quoteObj->addItem($quoteItem);
} catch (exception $e) {
return false;
}
$productObj->unsSkipCheckRequiredOption();
$quoteItem->checkData();
}
// addresses
$quoteShippingAddress = new Mage_Sales_Model_Quote_Address();
$quoteShippingAddress->setData($shippingAddress);
$quoteBillingAddress = new Mage_Sales_Model_Quote_Address();
$quoteBillingAddress->setData($billingAddress);
$quoteObj->setShippingAddress($quoteShippingAddress);
$quoteObj->setBillingAddress($quoteBillingAddress);
// coupon code
if(!empty($couponCode)) $quoteObj->setCouponCode($couponCode);
// shipping method an collect
$quoteObj->getShippingAddress()->setShippingMethod($shippingMethod);
$quoteObj->getShippingAddress()->setCollectShippingRates(true);
$quoteObj->getShippingAddress()->collectShippingRates();
$quoteObj->collectTotals(); // calls $address->collectTotals();
$quoteObj->setIsActive(0);
$quoteObj->save();
return $quoteObj->getId();
}
And the second one uses that Quote to create Order:
public function createOrder($quoteId, $paymentMethod, $paymentData)
{
$quoteObj = Mage::getModel('sales/quote')->load($quoteId); // Mage_Sales_Model_Quote
$items = $quoteObj->getAllItems();
$quoteObj->reserveOrderId();
// set payment method
$quotePaymentObj = $quoteObj->getPayment(); // Mage_Sales_Model_Quote_Payment
$quotePaymentObj->setMethod($paymentMethod);
$quoteObj->setPayment($quotePaymentObj);
// convert quote to order
$convertQuoteObj = Mage::getSingleton('sales/convert_quote');
$orderObj = $convertQuoteObj->addressToOrder($quoteObj->getShippingAddress());
$orderPaymentObj = $convertQuoteObj->paymentToOrderPayment($quotePaymentObj);
// convert quote addresses
$orderObj->setBillingAddress($convertQuoteObj->addressToOrderAddress($quoteObj->getBillingAddress()));
$orderObj->setShippingAddress($convertQuoteObj->addressToOrderAddress($quoteObj->getShippingAddress()));
// set payment options
$orderObj->setPayment($convertQuoteObj->paymentToOrderPayment($quoteObj->getPayment()));
if ($paymentData) {
$orderObj->getPayment()->setCcNumber($paymentData->ccNumber);
$orderObj->getPayment()->setCcType($paymentData->ccType);
$orderObj->getPayment()->setCcExpMonth($paymentData->ccExpMonth);
$orderObj->getPayment()->setCcExpYear($paymentData->ccExpYear);
$orderObj->getPayment()->setCcLast4(substr($paymentData->ccNumber,-4));
}
// convert quote items
foreach ($items as $item) {
// #var $item Mage_Sales_Model_Quote_Item
$orderItem = $convertQuoteObj->itemToOrderItem($item);
$options = array();
if ($productOptions = $item->getProduct()->getTypeInstance(true)->getOrderOptions($item->getProduct())) {
$options = $productOptions;
}
if ($addOptions = $item->getOptionByCode('additional_options')) {
$options['additional_options'] = unserialize($addOptions->getValue());
}
if ($options) {
$orderItem->setProductOptions($options);
}
if ($item->getParentItem()) {
$orderItem->setParentItem($orderObj->getItemByQuoteItemId($item->getParentItem()->getId()));
}
$orderObj->addItem($orderItem);
}
$orderObj->setCanShipPartiallyItem(false);
try {
$orderObj->place();
} catch (Exception $e){
Mage::log($e->getMessage());
Mage::log($e->getTraceAsString());
}
$orderObj->save();
//$orderObj->sendNewOrderEmail();
return $orderObj->getId();
}
The process works fine, no errors, and the order is created. But the total is 0 and there are no products in it no matter what I put.
I've traced it and I can confirm that the rows are added to the sales_flat_quote and sales_flat_quote_item tables, so that is ok. But when running the createOrder and calling
$items = $quoteObj->getAllItems();
an empty array is always returned, and I have no idea why. I have configurable and simple products in my shop. This happens when I add simple, when I add configurable the error appears as the method
$quoteItem = $quoteObj->addProduct($productObj);
returns null.
It seems to me, you didn't load product collection, therefore, the cart always return empty. Try this link, it will give you more clear help. Create order programmatically
// this is get only one product, you can refactor the code
$this->_product = Mage::getModel('catalog/product')->getCollection()
->addAttributeToFilter('sku', 'Some value here...')
->addAttributeToSelect('*')
->getFirstItem();
// load product data
$this->_product->load($this->_product->getId());
This code worked for me,
public function createorder(array $orderdata)
{
$quoteId = $orderdata['quoteId'];
$paymentMethod = $orderdata['paymentMethod'];
$paymentData = $orderdata['paymentData'];
$quoteObj = Mage::getModel('sales/quote')->load($quoteId);
$items = $quoteObj->getAllItems();
$quoteObj->reserveOrderId();
$quotePaymentObj = $quoteObj->getPayment();
$quotePaymentObj->setMethod($paymentMethod);
$quoteObj->setPayment($quotePaymentObj);
$convertQuoteObj = Mage::getSingleton('sales/convert_quote');
$orderObj = $convertQuoteObj->addressToOrder($quoteObj->getShippingAddress());
$orderPaymentObj = $convertQuoteObj->paymentToOrderPayment($quotePaymentObj);
$orderObj->setBillingAddress($convertQuoteObj->addressToOrderAddress($quoteObj->getBillingAddress()));
$orderObj->setShippingAddress($convertQuoteObj->addressToOrderAddress($quoteObj->getShippingAddress()));
$orderObj->setPayment($convertQuoteObj->paymentToOrderPayment($quoteObj->getPayment()));
foreach ($items as $item)
{
$orderItem = $convertQuoteObj->itemToOrderItem($item);
$options = array();
if ($productOptions = $item->getProduct()->getTypeInstance(true)->getOrderOptions($item->getProduct()))
{
$options = $productOptions;
}
if ($addOptions = $item->getOptionByCode('additional_options'))
{
$options['additional_options'] = unserialize($addOptions->getValue());
}
if ($options)
{
$orderItem->setProductOptions($options);
}
if ($item->getParentItem())
{
$orderItem->setParentItem($orderObj->getItemByQuoteItemId($item->getParentItem()->getId()));
}
$orderObj->addItem($orderItem);
}
$quoteObj->collectTotals();
$service = Mage::getModel('sales/service_quote', $quoteObj);
$service->submitAll();
$orderObj->setCanShipPartiallyItem(false);
try
{
$last_order_increment_id = Mage::getModel("sales/order")->getCollection()->getLastItem()->getIncrementId();
return $last_order_increment_id;
}
catch (Exception $e)
{
Mage::log($e->getMessage());
Mage::log($e->getTraceAsString());
return "Exception:".$e;
} }
I had the same problem and delved into the API to find a solution. I changed the way that I loaded a product by using :
$productEntityId = '123456';
$store_code = 'my_store_code';
$product = Mage::helper('catalog/product')->getProduct($productEntityId,Mage::app()->getStore($store_code)->getId());
I found this tutorial to be very useful too :
http://www.classyllama.com/content/unravelling-magentos-collecttotals
If you are looking for a script on order creation this is a very good start :
http://pastebin.com/8cft4d8v
Hope that this helps someone ;)

Categories