Magento get product collection via custom observer - magento

I have a custom observer in Magento 1.8.1.0 that is called on Product view page when current product having any upsell products. I have verified (using Mage::log()) that the observer is working, however when I try the following:
public function updateUpsells(Varien_Event_Observer $oObserver)
{
$iCurrentCategory = Mage::registry('current_category')->getId();
$oUpsellCollection = $oObserver->getCollection();
foreach ($oUpsellCollection->getItems() as $key => $oUpsellProduct) {
$aCategoriesIds = $oUpsellProduct->getCategoryIds();
if (!in_array($iCurrentCategory, $aCategoriesIds)) {
$oUpsellCollection->removeItemByKey($key);
}
}
}
On echo $oUpsellCollection; i got nothing returned ?
Is anyone know how to get upsell products collection ? Is this a proper way to do it ?

$upsellCollection = $_product->getUpSellProductCollection();

Related

Only 2 related products are showing in backend

Only two products are displaying as recommended product in magento product admin grid whereas we have assign 10 product with a product as recommended product.
It is the default issue of magento, can be resolved by changing the following file with mentioned changes.
Magento\Catalog\Model\ProductLink\CollectionProvider on method getCollection
foreach ($output as $item) {
$itemPosition = (int)$item['position'];
while(true) {
if (!isset($sorterItems[$itemPosition])) {
break;
}
$itemPosition += 1;
}
$sorterItems[$itemPosition] = $item;
}

Prevent automatic URL rewrites created that include category URL key in product URL

Whenever I create a new product, Magento automatically creates unnecessary URL rewrites that include each category and subcategory combination, that use the categories' URL keys in the product path. For example, for a product product-name with the categories:
category
category > subcategory
category > subcategory > third
...Magento will automatically create URL rewrites with the following request paths:
/category/product-name
/category/subcategory/product-name
/category/subcategory/third/product-name
...as well as also creating the in-use URL rewrite with request path:
/product-name
My question is, even though I have the setting Use Categories Path for Product URLs set to No in:
System > Configuration > Catalog > Search Engine Optimizations
...how do I stop these additional URL rewrites from being created automatically?
Now, again, I realize that the site isn't linking to these additional paths anywhere on the site, but if for some reason a search engine picked up:
http://example.com/category/subcategory/third/product-name
...this would load! I'm nervous this will result in duplicate content being indexed by search engines. Since the Use Categories Path for Product URLs setting is set to No, and all links to the product on the site are pointing to:
http://example.com/product-name
...I want to stop Magento from creating these unnecessary URL rewrites automatically.
For reference, I tried truncating the core_url_rewrite table to zero (basically emptying it out) and reindexing the Catalog URL Rewrites in System > Index Management. This still results in Magento automatically creating these unnecessary URL rewrites.
Also, for reference, I am using Magento Community 1.9.1.
Please advise! Your help is much appreciated.
Its not only about canonical links the problem is mainly another: crawling budget. You dont want to waste your crawling budget so the unnecessary urls need to go.
You should modify every entry in core_url_rewrite by shell script which:
is_system = 1
product_id not null
category_id not null
there you set:
target_path = direct product url
options = RP
Now you created 301 redirects to the real page and only have one problem left:
If a product has no category-product-urls no other urls will be created if the feature is turned off via backend config settings, this is what we want.
But if a product yet has category-product-urls and you add this product to a category still a new category-product-url would be created. So you need to change one method by rewriting/extending Mage_Catalog_Model_Url :
/**
* Refresh product rewrite
*
* #param Varien_Object $product
* #param Varien_Object $category
* #return Mage_Catalog_Model_Url
*/
protected function _refreshProductRewrite(Varien_Object $product, Varien_Object $category)
{
//FIX: DONT ADD CATEGORY-PRODUCT-URL - MIGHT HAPPEN IF CATEGORY-PRODUCT-URL EXIST YET FOR THIS PRODUCT
if (Mage::getStoreConfigFlag('catalog/seo/product_use_categories')) {
if ($category->getId() && $product->getId()) {
return $this;
}
}
parent::_refreshProductRewrite($product, $category);
}
I suggest that rather than trying to disable this built-in functionality, instead turn on canonical links. If you have an older version of Magento without this option, there are other ways to implement it.
However, if one were still inclined to remove it, they could probably create an extension that extends Mage_Catalog_Model_Url to do something like this:
class My_Catalog_Model_Url extends Mage_Catalog_Model_Url
{
public function refreshProductRewrite($productId, $storeId = null)
{
if (is_null($storeId)) {
foreach ($this->getStores() as $store) {
$this->refreshProductRewrite($productId, $store->getId());
}
return $this;
}
$product = $this->getResource()->getProduct($productId, $storeId);
if ($product) {
$store = $this->getStores($storeId);
$storeRootCategoryId = $store->getRootCategoryId();
// List of categories the product is assigned to, filtered by being within the store's categories root
// CUSTOMIZATION: Ignore product categories if the 'catalog/seo/product_use_categories' config setting is false.
if (Mage::getStoreConfigFlag('catalog/seo/product_use_categories', $storeId)) {
$categories = $this->getResource()->getCategories($product->getCategoryIds(), $storeId);
} else {
$categories = array();
}
$this->_rewrites = $this->getResource()->prepareRewrites($storeId, '', $productId);
// Add rewrites for all needed categories
// If product is assigned to any of store's categories -
// we also should use store root category to create root product url rewrite
if (!isset($categories[$storeRootCategoryId])) {
$categories[$storeRootCategoryId] = $this->getResource()->getCategory($storeRootCategoryId, $storeId);
}
// Create product url rewrites
foreach ($categories as $category) {
$this->_refreshProductRewrite($product, $category);
}
// Remove all other product rewrites created earlier for this store - they're invalid now
$excludeCategoryIds = array_keys($categories);
$this->getResource()->clearProductRewrites($productId, $storeId, $excludeCategoryIds);
unset($categories);
unset($product);
} else {
// Product doesn't belong to this store - clear all its url rewrites including root one
$this->getResource()->clearProductRewrites($productId, $storeId, array());
}
return $this;
}
}

Can one generate a link to the checkout page for a cart in magento?

I've got an instance of magento 1.7 CE running, and a second site that calls it via the SOAP api v2 from php.
I can't seem to find out how to add an array of products (given by productId or SKU) to a cart and then redirect to the cart page.
I've tried adding the items to the cart via shoppingCartProductAdd, which works, however I can't find out how to then open that cart back on magento.
I've also tried directly formulating a link that passes products via GET, however this only works for a single product ( checkout/cart/add?product=[id]&qty=[qty] ), for my purpose a whole array of products needs to be passed before redirecting to magento.
Any ideas?
Figured it out.
Basically one can use a link shaped like
http://example.com/checkout/cart/add?product=1&related_product=2,3,4,5
To fill the shoppingcart with products with id 1 .. 5 and then go to the cart in magento.
In my case I generated the link like this
if(!isset($session)) {
$client = new SoapClient('http://example.com/index.php/api/v2_soap?wsdl=1');
$session = $client->login('username', 'Qq314asdgUScrncfD7VMb');
}
if(!isset($cart)) {
$cart = $client->shoppingCartCreate($session);
}
$ids = array();
foreach($items as $id) {
$result = $client->catalogProductInfo($session, $id." ", null, 'sku');
$ids[] = $result->product_id;
}
$this->Session->delete('Cart');
$this->redirect('http://example.com/checkout/cart/add?product='.$ids[0].'&related_product=' . implode(array_slice($ids, 1), ','));

Magento: How to Print backend invoices like frontend as HTML?

I'm on Magento 1.7.0.2. How can I print invoices from backend with the same manner that frontend uses? I want it to be on HTML format not PDF.
Assuming that you want to print one invoice at a time from the admin order detail page
Create a custom admin module
Add a controller with the method below
public function printInvoiceAction()
{
$invoiceId = (int) $this->getRequest()->getParam('invoice_id');
if ($invoiceId) {
$invoice = Mage::getModel('sales/order_invoice')->load($invoiceId);
$order = $invoice->getOrder();
} else {
$order = Mage::registry('current_order');
}
if (isset($invoice)) {
Mage::register('current_invoice', $invoice);
}
$this->loadLayout('print');
$this->renderLayout();
}
Reference printInvoiceAction() in app/code/core/Mage/Sales/controllers/GuestController.php
Then in your custom layout.xml use <sales_guest_printinvoice> in /app/design/frontend/base/default/layout/sales.xml as your template
Then add a button with link to the following url (need to get invoice id from order) /customModule/controller/printInvoice/invoice_id/xxx
(Not tested, so let me know if you run into any issues)
You should create your custom css file for printing print.css. And you should add "Print Button", that will call window.print()

Duplicating a product with Code in Magento

I am trying to write a custom module which is capable of duplicating a product into multiple products with only varying SKU. I have tried using function duplicate() under /app/code/core/Mage/Catalog/Model/Product.php in my custom module. But its not working.
I am using the below code in my custom Obesrever.php file to duplicate, but duplication is not occuring
$product = $observer->getEvent()->getProduct();
$newProduct = $product->duplicate();
can anyone suggest me any links to do this or any code format would be helpful.
Thanks
It would be great if you can post the complete function that you are trying to debug or create duplicate products and config.xml (where you are trying to call the event).
Below code works for me in CE 1.9.2.2 without any problems. This function does the following tasks:
Creates duplicate of the original product
Sets the stock to "In Stock" and Qty to "100" (hard coded for now)
Automates reindexing
public function indexAction() //change the function name
{
$productId = $observer->getEvent()->getProduct()->getId();
$productObject = Mage::getModel('catalog/product');
$_product = $productObject->load($productId);
$newProduct = $_product->duplicate();
//new product status is disabled - to view in the frontend you will need to set the status as enabled
$newProduct->setStatus(1);
$newProduct->setName('Duplicate-' . $_product->getName());
$newProduct->setSku('value-' . $productId);
$newProduct->setWebsiteIds($_product->getWebsiteIds());
//set the product stock and qty to display product in the frontend
//while creating duplicate product, it will update the new product to have qty 0 and out of stock
$stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($newProduct->getId());
if ($stockItem->getId() > 0 && $stockItem->getManageStock())
{
$qty = 100;
$stockItem->setQty($qty);
$stockItem->setIsInStock((int)($qty > 0));
$stockItem->save();
}
$newProduct->getResource()->save($newProduct);
//automate reindexing - to display the product in the frontend
$indexers = Mage::getSingleton('index/indexer')->getProcessesCollection();
foreach ($indexers as $indexer)
{
$indexer->reindexEverything();
}
}
Hope this helps.
Happy Coding...

Resources