Add products to order programmatically magento admin - magento

I have customized my create order page and in that after selecting customer and store id I have information of the product(Ex product A), I want that after admin reaches the sales_order_create then there must be that product(Product A) in the 'Items Ordered' list by default.
Thanks in advance

One of the solutions is to add an observer for the event called "create_order_session_quote_initialized". In the observer you need to add something like this:
$session = $observer->getSession();
if ($session->getProductAdded()) {
return $this;
}
$product = Mage::getModel('catalog/product')->load($productId);
$session->getQuote()->addProduct($product);
$session->setProductAdded(true);
return $this;
It's not the exact code which already works. But I hope that this will help.

First we need to initialize the quote with product(Product A).
$quoteItem = Mage::getModel('sales/quote_item')
->setProduct($product)
->setQuote($this->getQuote())
->setQty($qty)
->setPrice($product->getPrice())
->save();
Convert this quote item to order item.
$orderItem = Mage::getModel('sales/convert_quote')
->itemToOrderItem($quoteItem)
->save($this->getOrder->getId());

Related

How to change the weight before sending to fedex magento?

In magento checkout page, after giving billing information and shipping information, i understand that these details are sending to fedex then the shipping rates are populating in chekout page, before sending theses details to fedex, i want to change the weight of the product, i Want to add additional weights for each products,
suppose user adding a product with weight of 2 pounds, i want to send
these weight to 2*5 = 10pounds, how can i do that in magento? please
help.
Not sure to understand what you want exactly but I'll give a try.
I think you can override Mage_Checkout_OnepageController::savePaymentAction method in your local pool and in your local method, dispatch your own new event 'save_payment_action_before' and pass your objects as parameters.
In your fedex module, create an observer, get your object and change the order weight before it's sent to fedex.
To create your custom event, check this post
Finally i find out that it is happening in the sales/quote/item.php file, there is a function called setProduct, here we need to add addititonal info while setting data.
public function setProduct($product)
{
$batchQty = Mage::getModel('catalog/product')->load($product->getId())->getBatchQty();
$roleId = Mage::getSingleton('customer/session')->getCustomerGroupId();
$userrole = Mage::getSingleton('customer/group')->load($roleId)->getData('customer_group_code');
$userrole = strtolower($userrole);
if ($this->getQuote()) {
$product->setStoreId($this->getQuote()->getStoreId());
$product->setCustomerGroupId($this->getQuote()->getCustomerGroupId());
}
if($userrole=="retailer" && $batchQty>0 ){
$this->setData('product', $product)
->setProductId($product->getId())
->setProductType($product->getTypeId())
->setSku($this->getProduct()->getSku())
->setName($product->getName())
->setWeight($this->getProduct()->getWeight()*$batchQty)
->setTaxClassId($product->getTaxClassId())
->setBaseCost($product->getCost())
->setIsRecurring($product->getIsRecurring());
} else {
$this->setData('product', $product)
->setProductId($product->getId())
->setProductType($product->getTypeId())
->setSku($this->getProduct()->getSku())
->setName($product->getName())
->setWeight($this->getProduct()->getWeight())
->setTaxClassId($product->getTaxClassId())
->setBaseCost($product->getCost())
->setIsRecurring($product->getIsRecurring());
}
if ($product->getStockItem()) {
$this->setIsQtyDecimal($product->getStockItem()->getIsQtyDecimal());
}
Mage::dispatchEvent('sales_quote_item_set_product', array(
'product' => $product,
'quote_item' => $this
));
return $this;
}

Magento: get block of product view

I instanciate the following block by using the operator new but when I am going to use getProduct() it does not return anything because it doesn't have the ID of the product. How can I add it?
$block = new Mage_Catalog_Block_Product_View_Options();
Thanks in advance.
Try this:
$product_id = Mage::registry('current_product')->getId();

How to check if a Magento product is already added in cart or not?

I want to show popup when a product is first added to cart in Magento and don't want to show a popup if the product was added again or updated.In short, I want to know product which is going to be added in the cart is First occurence or not?
The answer largely depends on how you want to deal with parent/child type products (if you need to).
If you are only dealing only with simple products or you have parent/child type products and you need to test for child id's then:
$productId = 1;
$quote = Mage::getSingleton('checkout/session')->getQuote();
if (! $quote->hasProductId($productId)) {
// Product is not in the shopping cart so
// go head and show the popup.
}
Alternatively, if you are dealing with parent/child type products and you only want to test for the parent id then:
$productId = 1;
$quote = Mage::getSingleton('checkout/session')->getQuote();
$foundInCart = false;
foreach($quote->getAllVisibleItems() as $item) {
if ($item->getData('product_id') == $productId) {
$foundInCart = true;
break;
}
}
EDIT
The question was asked in a comment as to why setting a registry value in controller_action_predispatch_checkout_cart_add is not available to retrieve in cart.phtml.
Essentially registry value are only available through the life of a single request - you are posting to checkout/cart/add and then being redirected to checkout/cart/index - so your registry values are lost.
If you would like to persist a value across these then you can use the session instead:
In your observer:
Mage::getSingleton('core/session')->setData('your_var', 'your_value');
To retrieve the value
$yourVar = Mage::getSingleton('core/session')->getData('your_var', true);
The true flag being passed to getData will remove the value from the session for you.
In order check if the product is already in cart or not, you can simply use the following code:
$productId = $_product->getId(); //or however you want to get product id
$quote = Mage::getSingleton('checkout/session')->getQuote();
$items = $quote->getAllVisibleItems();
$isProductInCart = false;
foreach($items as $_item) {
if($_item->getProductId() == $productId){
$isProductInCart = true;
break;
}
}
var_dump($isProductInCart);
Hope this helps!

Magento mass-assign products to category

As the title says,i need to mass-assign products to a category and from the admin i can only edit one product at a time; i dont know why it just doesnt work to mass add them from the "category products" tab in the category page.
Thats why i need another method that's fast,like using phpMyAdmin or something alike.
Any help?
Thanks in advance!
I created a simple script to do this outside of Magento. Be sure to test this first on a single product and make sure it looks as you'd expect.
// Load Magento
require_once 'path/to/app/Mage.php';
Mage::app();
// $productIds is an array of the products you want to modify.
// Create it however you want, I did it like this...
$productsIds = Mage::getModel('catalog/product')->getCollection()
->addAttributeToFilter('sku', array('like' => 'something'))
->getAllIds();
// Array of category_ids to add.
$newCategories = array(20);
foreach ($productIds as $id) {
$product = Mage::getModel('catalog/product')->load($id);
$product->setCategoryIds(
array_merge($product->getCategoryIds(), $newCategories)
);
$product->save();
}
If you wish to overwrite a product's existing categories, change array_merge(...) to just $newCategories.
I would shy away from tackling this problem from the database side of things. If you do go that direction make sure and take lots of backups and do it during low usage.
The following thread on the Magento forum identifies the very same problem. One poster recommends a raw sql approach with example. Again, I would be careful - make sure you take backups.
The answer I like best from the thread (posted by Magento MVP):
Go into the category you don’t want them in, find the product list.
Click the check boxes on the products you want to remove and select
delete from the little dropdown.
Now go into the category where you
do want them, go to the product list. Select the NO dropdown so it
shows items not in the category. You might have to do a selective
search to limit stuff and do it in a couple iterations. Click the
check boxes and tell it to add stuff.
You may as well do this using the magento API
This is the script I use for mass adding products. sku.txt contains one sku per line.
<?php
$wsdlUrl = "magento-root/index.php/api/soap/?wsdl";
$proxy = new SoapClient($wsdlUrl);
$sessionId = $proxy->login('apiuser', 'apipasswd');
$listOfDiscountedSKUFile = "sku.txt";
function readinFile($filePath)
{
$fp = fopen($filePath,'r') or exit("Unable to open file!");
$dataItems = array();
while(!feof($fp))
{
$dataItems[] = trim(fgets($fp));
}
fclose($fp);
var_dump($dataItems);
return $dataItems;
}
function addToCategory($sku,$categoryId)
{
global $proxy,$sessionId;
$proxy->call($sessionId, 'category.assignProduct', array($categoryId, $sku));
}
function IsNullOrEmptyString($question){
return (!isset($question) || trim($question)==='');
}
$categoryId = 82;//e.g.
$listOfSKU = readinFile($listOfDiscountedSKUFile);
foreach($listOfSKU as $sku)
{
addToCategory($sku,$category);
}
?>
I managed to resolve the problem with the following code :
$write = Mage::getSingleton('core/resource')->getConnection('core_write');
$x = 1171;
$y = 2000;
$categoryID = 4;
$productPosition = 0;
while($x <= $y) {
$write->query("REPLACE INTO `catalog_category_product` (`category_id`, `product_id`, `position`) VALUES ($categoryID, $x++, $productPosition)");
}
echo "The job is done";
?>
I hope the code is clear for everyone,if it's not,reply and i'll try to explain it.
#nachito : here it is.

Magento - Check for Customer's First Order

Is there a quick way to programatically check if the currently logged in customer has ever placed an order? I'm writing an observer and at a point I want to simply say
if ($this->isCustomerLoggedIn() && (has never placed an order))
{
do this
}
possible?
Thanks!
$orders = Mage::getResourceModel('sales/order_collection')
->addFieldToSelect('*')
->addFieldToFilter('customer_id', $customer->getId());
if ($this->isCustomerLoggedIn() && (!$orders->getSize()))
{
// has never placed an order
}
The above assumes that you have a $customer but if it is not accessible from the event you can usually get the currently logged in customer with:
$customer = Mage::getSingleton('customer/session')->getCustomer();
Do you need to create an event?
$session = Mage::getModel('customer/session');
$order = Mage::getModel('sales/order')->getCollection()->addAttributeToFilter('customer_id',$session->getId())->getFirstItem();

Resources