Programmatically modify related products in magento - magento

I'm trying to programmatically manipulate the product relations in a Magento store.
From what I've read, setRelatedLinkData should be the way to go.
As I simple test, I'm just trying to replace a products related products with nothing (i.e. an empty array), however it's not working - the product in question is still showing the related product in the backend.
The test code I'm working with is:
$product = Mage::getModel('catalog/product')->load($product->getId());
$linkData = array();
print_r($linkData);
$product->setRelatedLinkData($linkData);
echo "Save\n";
$r = $product->save();
As mentioned above however the product still has a related product when I reload it in the backend.
NOTE: I don't only want to remove related products, eventually I want to be able to add new ones as well, so a DELTE FROM... SQL query isn't what I am looking for. However if I can't get it to work to remove products, then it's certainly not going to work to add them, so one step at a time :-)

The quickest way I can think of is to use the Link Resource:
app/code/core/Mage/Catalog/Model/Resource/Product/Link.php saveProductLinks
// sample code
$product = Mage::getModel('catalog/product')->load(147);
$linkData = array();
Mage::getResourceModel('catalog/product_link')->saveProductLinks(
$product, $linkData, Mage_Catalog_Model_Product_Link::LINK_TYPE_RELATED
);
and if you want to assign products use the same code but provide this as $linkData:
$linkData = array(
'145' => array('position' => 1),
'146' => array('position' => 2)
);

Related

Magento - get results view HTML for a collection of products

I get a list of magento ids from a web service. I load these into and array $product_ids, so I have something like this:
Array
(
[0] => 1965
[1] => 3371
[2] => 1052
)
I can then make this into a collection:
$collection = Mage::getModel('catalog/product')->getCollection()
->addIdFilter($product_ids);
Using my Magento inspector, I've seen that the category pages use the class Mage_Catalog_Block_Product_List to display lists of products. I'd like to do something similar in my class. I've tried loading:
$ProductList = new Mage_Catalog_Block_Product_List();
$ProductList->setCollection($collection);
And then I've tried to load the HTML of the results as follows:
$CollectionHTML = $ProductList->_toHtml();
But $CollectionHTML is empty.
How would I get the HTML of what you see in the list view (i.e. the generated output of frontend/base/default/template/catalog/product/list.phtml, but given my collection)?
Making the code work the right way is much more easier in Magento than trying to work with ugly legacy code. I would gladly help you make the code the proper way when you have specific questions. Also, in the longterm, technical debt is gonna cost alot more.
Anyway, back to your issue.
In Magento block are not instantiated like in any app $myvar = new className ... almost never. This tutorial can help you understand better Magento's layout and blocks.
But if you want to create a block a way to do it is:
$block = Mage::getSingleton('core/layout')->createBlock('catalog/product_list')
Now related to your product collection you should check how Mage_Catalog_Block_Product_List::_getProductCollection actually works, because it uses the layered navigation, not a simple product collection.
Further, assuming that at least you are using a Magento controller and you are within a function, the following code will display the first page of products for a specified category:
//$category_id needs to be set
$layout = Mage::getSingleton('core/layout');
$toolbar = $layout->createBlock('catalog/product_list_toolbar');
$block = $layout->createBlock('catalog/product_list');
$block->setChild('toolbar', $toolbar);
$block->setCategoryId($category_id);
$block->setTemplate('catalog/product/list.phtml');
$collection = $block->getLoadedProductCollection();
$toolbar->setCollection($collection);
//render block object
echo $block->renderView();
Displaying specific ids:
you use root category id for $category_id variable (also make sure that display root category is set (or another category id that contains your product ids)
you can hook into catalog_block_product_list_collection event to add your ID Filter to the collection (this is called in _beforeToHtml function)
But, all this construction is not solid and there are still some points that require attention (other child blocks, filters and so on)

How to get a list of last viewed products in Magento?

I am trying to access the list of last viewed items using the below code:
$attributes = Mage::getSingleton('catalog/config')->getProductAttributes();
$model = Mage::getModel('reports/product_index_viewed');
//
$_collection = $model->getCollection()->addAttributeToSelect($attributes)
->excludeProductIds($model->getExcludeProductIds())
->addUrlRewrite()
->setPageSize($columnCount)
->setCurPage(1);
//
$_collection->addPriceData();
$_collection->addIndexFilter();
$_collection->setAddedAtOrder();
//
Mage::getSingleton('catalog/product_visibility')->addVisibleInSiteFilterToCollection($_collection);
I copied this from the Mage_Reports_Block_Product_Abstract but this is giving the products in the creation order.
I doubt Prasanth will ever come back to this but I too having been trying to get a simple list of products without using a block which may not always be available. Eventually I found you need this:
$viewedCollection = Mage::getModel('reports/product_index_viewed')
->getCollection()
->addIndexFilter();
The secret is in addIndexFilter(), it uses the current customer or - if not logged in - the current visitor instead. From this you can loop through as with any other collection or extract a single array:
$viewedProductIds = $viewedCollection->getColumnValues('product_id');

Magento filter products by items that have this item in their related products

I wish to get a collection of products that have product x as a related product.
So, say I'm starting with
$_productCollection = $product->getCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('status',1)
->addStoreFilter()
->distinct(true);
And wish to add something like (but with some reverse in instead of eq):
$_productCollection->addAttributeToFilter('related_ids',array('eq' => $idofproductx));
I can't find anything, but assume it will include a join of some description. I'd rather avoid loading all products and then all related for each cycling through them all, for obvious reasons.
You may be able to do
// #var $products array
$_productCollection->getSelect()->join(array('links' => 'catalog_product_link'), 'e.entity_id = links.product_id');
$_productCollection->getSelect()->where('links.linked_product_id IN (?)', $products);
I tested that it runs without error against my DB, but I don't have product links in my database (we fetch from a web service), so I can't be certain it returns the expected products.
I recently had the same issue, but I ended up making a small module for this so it's reusable.
But for simplicity a stripped back version of my solution can be found below.
// load by a product Id
$_product = Mage::getModel('catalog/product')->load($_productId);
$_linkInstance = $_product->getLinkInstance();
$collection = $_linkInstance->getLinkCollection();
// get products which have $_productId as a link
$collection->addFieldToFilter('linked_product_id', array('eq' => $_product->getId()));
// 1 = related products
$collection->addLinkTypeIdFilter(1);
$collection->joinAttributes();
The above code will populate $collection with an array of IDs which have assigned $_productId as a related product.
Note: This works on CE 1.9.1.0

Programmatically ship and comment single item of an order in Magento

I know there is a way to programmatically invoice, ship, and set state on an order (http://www.magentocommerce.com/boards/viewthread/74072/), but I actually need to drill down even deeper to the item level of an order. We have a situation where, depending on item type, two different items can be processed in two different locations (from the same order). I can go into the Magento back-end and "ship" one item without "shipping" the other and append comments to that one item, but I'm looking for a way to do this programmatically. Thank you in advance for your help!
Update:
Here is the code I ended up using to accomplish this:
$client = new SoapClient('http://somesite.domain/magento/index.php/api/?wsdl');
$session = $client->login('username', 'password');
function extract_item_id($items, $sku ){
foreach($items as $item ){
if ($item["sku"]==$sku) {
return $item["item_id"];
}
}
}
$orderNum = "200000052";
$oderInfo = $client->call($session, "sales_order.info", $orderNum );
$item_id = extract_item_id($oderInfo["items"], "someSKU") ;
$itemsQty = array( $item_id => "1" );
$shipment = array(
$orderNum,
$itemsQty,
"Comment associated with item shipped.",
true,
true
);
var_dump($shipment);
$nship = $client->call($session, 'sales_order_shipment.create', $shipment);
I've never done it, but it looks like the SOAP API supports creating individual shipment items. That'd be the first thing I'd check.
If that doesn't work, I'd examine the source code the the Magento admin and reverse engineer what its doing with to create a single item shipment. Specifically, start tracing at the saveAction of the admin's Shipment Controller
app/code/core/Mage/Adminhtml/controllers/Sales/Order/ShipmentController.php
The order/shipment/invoice section of Magento codebase is one of the most volatile/iterative sections, with the core objects/methods/dependencies changing subtly between versions. Finding one "right" answer for this will prove difficult, if not impossible.

Magento Product Insert Function

I need to add a custom option to all products as they get saved. For that I need to find the function that inserts the products into the database, which I'm not able to find.
Please, any help would be appreciated.
thanx
$client = new SoapClient('http://www.magentolocal.it/api/?wsdl');
$session = $client->login('productloader', '1234567890');
$sku = "123456";
$attrs['name'] = "Template #1";
$attrs['description'] = "This is the first template.";
$attrs['short_description'] = "This is the short description of the template";
$attrs['websites'] = array('1');
$attrs['price'] = "11.53";
$attrs['categories'] = array('35');
$attrs['images'] = array()
$result = $client->call($session, 'catalog_product.create', array('simple', '63', $sku, $attrs));
echo $result;
$client->endSession($session);
Magento's EAV system is pretty strung out among several files, so you won't find a single function that accomplishes what you want. If you did go looking for it, and changed it, you would also be changing the same save method that mostly every other object in Magento uses, which is probably not what you want.
To do what you want, try setting up an observer/listener on the events that catalog products use when saving, namely catalog_product_save_before or catalog_product_save_after. That way, you don't have to hack the framework.
Hope that helps!
Thanks,
Joe
How about http://www.magentocommerce.com/wiki/doc/webservices-api/api/catalog_product#catalog_product.create?

Resources