How to add custom product relations in Magento

Inchoo_CustomLinkedProducts

Currently there are three types of product relations in Magento: Up-sells, Related Products, and Cross-sell Products. Recently while discussing client’s requirements, we’ve come to conclusion it would serve our purpose best to link products in the same way Magento does, and then use our own relations independently of Magento’s built in product relations. In this article I’ll show you how to add custom product relations as addition to existing Magento product relations.

Introduction

Inside following paragraphs I’ll do my best to present code snippets from Magento extension created to illustrate process of adding custom product relations in Magento. Full source code for the extension named Inchoo_CustomLinkedProducts is available from its GitHub repository page.

Installer script

First thing we need to do is notify Magento database about out new product link type. We will do this using following installer script:

app/code/community/Inchoo/CustomLinkedProducts/sql/inchoo_customlinkedproducts_setup/install-0.0.1.php

<?php
 
$installer = $this;
 
/**
 * Install product link types
 */
$data = array(
    array(
        'link_type_id'  => Inchoo_CustomLinkedProducts_Model_Catalog_Product_Link::LINK_TYPE_CUSTOM,
        'code'          => 'custom'
    )
);
 
foreach ($data as $bind) {
    $installer->getConnection()->insertForce($installer->getTable('catalog/product_link_type'), $bind);
}
 
/**
 * Install product link attributes
 */
$data = array(
    array(
        'link_type_id'                  => Inchoo_CustomLinkedProducts_Model_Catalog_Product_Link::LINK_TYPE_CUSTOM,
        'product_link_attribute_code'   => 'position',
        'data_type'                     => 'int'
    )
);
 
$installer->getConnection()->insertMultiple($installer->getTable('catalog/product_link_attribute'), $data);

Admin interface

Next thing is to add a new tab to Product Information screen at admin side. First here’s the PHP code, later we will add it to layout using our layout XML file:

app/code/community/Inchoo/CustomLinkedProducts/Block/Adminhtml/Catalog/Product/Edit/Tab.php

<?php
 
class Inchoo_CustomLinkedProducts_Block_Adminhtml_Catalog_Product_Edit_Tab
extends Mage_Adminhtml_Block_Widget
implements Mage_Adminhtml_Block_Widget_Tab_Interface
{
    public function canShowTab() 
    {
        return true;
    }
 
    public function getTabLabel() 
    {
        return $this->__('Custom Linked Products');
    }
 
    public function getTabTitle()        
    {
        return $this->__('Custom Linked Products');
    }
 
    public function isHidden()
    {
        return false;
    }
 
    public function getTabUrl() 
    {
        return $this->getUrl('*/*/custom', array('_current' => true));
    }
 
    public function getTabClass()
    {
        return 'ajax';
    }
 
}

Since our tab points to ‘*/*/custom’ route, we need to add it to Mage_Adminhtml_Catalog_ProductController by rewriting it:

app/code/community/Inchoo/CustomLinkedProducts/controllers/Adminhtml/Catalog/ProductController.php

<?php
 
require_once(Mage::getModuleDir('controllers','Mage_Adminhtml').DS.'Catalog'.DS.'ProductController.php');
 
class Inchoo_CustomLinkedProducts_Adminhtml_Catalog_ProductController extends Mage_Adminhtml_Catalog_ProductController
{
    /**
     * Get custom products grid and serializer block
     */
    public function customAction()
    {
        $this->_initProduct();
        $this->loadLayout();
        $this->getLayout()->getBlock('catalog.product.edit.tab.custom')
            ->setProductsCustom($this->getRequest()->getPost('products_custom', null));
        $this->renderLayout();
    }
 
    /**
     * Get custom products grid
     */
    public function customGridAction()
    {
        $this->_initProduct();
        $this->loadLayout();
        $this->getLayout()->getBlock('catalog.product.edit.tab.custom')
            ->setProductsRelated($this->getRequest()->getPost('products_custom', null));
        $this->renderLayout();
    }
 
}

To add our new tab to Product Information screen and for getBlock(‘catalog.product.edit.tab.custom’) to work on both customAction() and customGridAction(), we also need to add a bit of XML to our layout:

app/design/adminhtml/default/default/layout/inchoo_customlinkedproducts.xml

<?xml version="1.0" encoding="UTF-8"?>
 
<layout>
 
    <adminhtml_catalog_product_edit>
        <reference name="product_tabs">
            <action method="addTab">
                <name>custom</name>
                <block>inchoo_customlinkedproducts/adminhtml_catalog_product_edit_tab</block>
            </action>
        </reference>
    </adminhtml_catalog_product_edit>
 
    <adminhtml_catalog_product_custom>
        <block type="core/text_list" name="root" output="toHtml">
            <block type="inchoo_customlinkedproducts/adminhtml_catalog_product_edit_tab_custom" name="catalog.product.edit.tab.custom"/>
            <block type="adminhtml/widget_grid_serializer" name="custom_grid_serializer">
                <reference name="custom_grid_serializer">
                    <action method="initSerializerBlock">
                        <grid_block_name>catalog.product.edit.tab.custom</grid_block_name>
                        <data_callback>getSelectedCustomProducts</data_callback>
                        <hidden_input_name>links[custom]</hidden_input_name>
                        <reload_param_name>products_custom</reload_param_name>
                    </action>
                    <action method="addColumnInputName">
                        <input_name>position</input_name>
                    </action>
                </reference>
            </block>
        </block>
    </adminhtml_catalog_product_custom>
 
    <adminhtml_catalog_product_customgrid>
        <block type="core/text_list" name="root" output="toHtml">
            <block type="inchoo_customlinkedproducts/adminhtml_catalog_product_edit_tab_custom" name="catalog.product.edit.tab.custom"/>
        </block>
    </adminhtml_catalog_product_customgrid>
 
</layout>

Next thing, we need to create grid to be hosted inside our newly created Custom Linked Products tab. There’s a lot if code for this task, but much of it is pretty generic grid code. The one thing you’ll notice is call to useCustomLinks() inside _prepareCollection() function. Here’s the excerpt from our grid class:

app/code/community/Inchoo/CustomLinkedProducts/Block/Adminhtml/Catalog/Product/Edit/Tab/Custom.php

<?php
$collection = Mage::getModel('catalog/product_link')->useCustomLinks()
    ->getProductCollection()
    ->setProduct($this->_getProduct())
    ->addAttributeToSelect('*');

So this is how interface for managing Custom Linked Products looks like inside Magento admin:

Inchoo_Customlinkedproducts admin

Backend supporting code

As you might have noticed, function useCustomLinks() doesn’t exist inside catalog/product_link model, thus we need to rewrite this model to include our custom product link specific functionality:

app/code/community/Inchoo/CustomLinkedProducts/Model/Catalog/Product/Link.php

<?php
 
class Inchoo_CustomLinkedProducts_Model_Catalog_Product_Link extends Mage_Catalog_Model_Product_Link
{
    const LINK_TYPE_CUSTOM   = 6;
 
    /**
     * @return Mage_Catalog_Model_Product_Link
     */
    public function useCustomLinks()
    {
        $this->setLinkTypeId(self::LINK_TYPE_CUSTOM);
        return $this;
    }
 
    /**
     * Save data for product relations
     *
     * @param   Mage_Catalog_Model_Product $product
     * @return  Mage_Catalog_Model_Product_Link
     */
    public function saveProductRelations($product)
    {
        parent::saveProductRelations($product);
 
        $data = $product->getCustomLinkData();
        if (!is_null($data)) {
            $this->_getResource()->saveProductLinks($product, $data, self::LINK_TYPE_CUSTOM);
        }
 
    }
}

If you were to add another custom relation to same Magento installation, you would need to increase LINK_TYPE_CUSTOM class constant to avoid conflicts. Now you might notice that our catalog/product model doesn’t have getCustomLinkData() function. Fear not, another rewrite to the rescue:

app/code/community/Inchoo/CustomLinkedProducts/Model/Catalog/Product.php

<?php
 
class Inchoo_CustomLinkedProducts_Model_Catalog_Product extends Mage_Catalog_Model_Product
{
    /**
     * Retrieve array of custom products
     *
     * @return array
     */
    public function getCustomProducts()
    {
        if (!$this->hasCustomProducts()) {
            $products = array();
            $collection = $this->getCustomProductCollection();
            foreach ($collection as $product) {
                $products[] = $product;
            }
            $this->setCustomProducts($products);
        }
        return $this->getData('custom_products');
    }
 
    /**
     * Retrieve custom products identifiers
     *
     * @return array
     */
    public function getCustomProductIds()
    {
        if (!$this->hasCustomProductIds()) {
            $ids = array();
            foreach ($this->getCustomProducts() as $product) {
                $ids[] = $product->getId();
            }
            $this->setCustomProductIds($ids);
        }
        return $this->getData('custom_product_ids');
    }
 
    /**
     * Retrieve collection custom product
     *
     * @return Mage_Catalog_Model_Resource_Product_Link_Product_Collection
     */
    public function getCustomProductCollection()
    {
        $collection = $this->getLinkInstance()->useCustomLinks()
            ->getProductCollection()
            ->setIsStrongMode();
        $collection->setProduct($this);
        return $collection;
    }
 
    /**
     * Retrieve collection custom link
     *
     * @return Mage_Catalog_Model_Resource_Product_Link_Collection
     */
    public function getCustomLinkCollection()
    {
        $collection = $this->getLinkInstance()->useCustomLinks()
            ->getLinkCollection();
        $collection->setProduct($this);
        $collection->addLinkTypeIdFilter();
        $collection->addProductIdFilter();
        $collection->joinAttributes();
        return $collection;
    }
 
}

There’s one more crucial thing left to do. To enable our product relations save and duplicate functionality on catalog product, we must attach to catalog_product_prepare_save and catalog_model_product_duplicate events. Here’s the observer class with callbacks for these events:

<?php
 
class Inchoo_CustomLinkedProducts_Model_Observer extends Varien_Object
{
    public function catalogProductPrepareSave($observer)
    {
        $event = $observer->getEvent();
 
        $product = $event->getProduct();
        $request = $event->getRequest();
 
        $links = $request->getPost('links');
        if (isset($links['custom']) && !$product->getCustomReadonly()) {
            $product->setCustomLinkData(Mage::helper('adminhtml/js')->decodeGridSerializedInput($links['custom']));
        }
    }
 
    public function catalogModelProductDuplicate($observer)
    {
        $event = $observer->getEvent();
 
        $currentProduct = $event->getCurrentProduct();
        $newProduct = $event->getNewProduct();
 
        $data = array();
        $currentProduct->getLinkInstance()->useCustomLinks();
        $attributes = array();
        foreach ($currentProduct->getLinkInstance()->getAttributes() as $_attribute) {
            if (isset($_attribute['code'])) {
                $attributes[] = $_attribute['code'];
            }
        }
        foreach ($currentProduct->getCustomLinkCollection() as $_link) {
            $data[$_link->getLinkedProductId()] = $_link->toArray($attributes);
        }
        $newProduct->setCustomLinkData($data);
    }
 
}

Frontend interface

To demonstrate our custom product relation on Magento frontend, I’ve cloned Magento’s related products block inside inchoo_customrelatedproducts/catalog_product_list_custom block together with related template file. Our Related Products block clone will use our custom product relations instead of builtin Related Products relations. This is how it looks like in frontend:

Inchoo_Customlinkedproducts frontend

I hope you’ll find some use for this code inside your own projects. Like always if you have any questions please leave your comment here and I’ll respond as soon as possible. If you’ve noticed some bug or wish to improve this code in any way, feel free to fork Inchoo_CustomLinkedProducts at GitHub.

Interested in hiring us?

Have a chat with us. You would be surprised how small changes can make your business even more successful.


About Marko Martinovic

Team Leader/Backend Developer

If you ask him – “Marko, how do you relax in your free time?”, he would most probably say: – “I write some code.” Let’s cut to the chase, he is one passionate programmer who currently lives his dream by working for Inchoo.

Read more posts by Marko / Visit Marko's profile

33 comments

  1. Hi,

    I’ve installed this module and its working file but I’ve two issues.
    1. This “Custom Linked Products” is only available for already created products but it is not available while creating a new product.
    2. In “Related Products” Tab, grid is not displaying the products even the grid is not getting displayed.
    Please help me on this.
    Thanks in advance.

  2. Hi
    I installed this module and its working fine for me but
    requirement is now to replicate this module (same functionality) and i m replicating by changing name of module and class name etc but it not working it trough
    404 in ajax request in admin section when i click on tab.

    Please help me to replicate this module as i am not experience in magento.
    thanks in advance.

  3. Hey,

    I’ve solved the block issue. I’m now having a problem as the custom products aren’t being added to cart when checked.

    Any ideas?

    Thanks

  4. Hi
    I installed this module and its working fine for me but
    requirement is now to replicate this module (same functionality) and i m replicating by changing name of module and class name etc but it not working it trough
    404 in ajax request in admin section when i click on tab.

    Please help me to replicate this module as i am not experience in magento.
    thanks in advance.

  5. Thanks for the great tutorial; perfect to a T! Adding an additional set of related products isn’t trivial, thanks for the step-by-step…

  6. Iam beginner to magento . I want to build a multi-seller Magento site in which customer can pay direct payment to the seller PayPal account. I searched for some extensions, but in most of them are not free to use. So now Iam trying to build a custom module to override the exist payment system . Any tuitorial or tips ? help me..

  7. I am experiencing a issue: when I save in admin a custom linked product, it does save… nothing! :(

    so it display nothing in frontend, because there is always nothing to display

  8. I downloaded the customlinkedproducts extension , i am not able to add the linked products to cart. please help.

  9. Hi,

    I downloaded this module from github and it works well with regular products but I need it to work for downloadable products. Is there a way we could do that?

    Thanks!

  10. Thanks for this tutorial!

    I’ve got the module installed, works smoothly in the admin… but I’m unsure how to get the block to show up in my product details (view.phtml) template. Can you show the snippet of code from view.phtml that invokes the custom related products?

    thanks again

  11. I have one problem when I try make second relation. first model rewrites product model and second module can’t. Do you have any idea.

  12. Thanks Marko. :) And one more question. How can I hide from search result product who has any custom linked products?

  13. Hi. It’s a great module. Can I make one more relation with this module. And if yes, how can I do it?

    1. Hello Felix, I’m glad you find this useful. For adding another link you need to basically clone existing functionality but using another link type ID. This code is using link type ID of 6 (const LINK_TYPE_CUSTOM = 6;), and for another relation you can define class constant for link type ID of 7 inside Inchoo_CustomLinkedProducts_Model_Catalog_Product_Link, or even better create separate module for second product link.

      Good luck!

  14. Hey, is there really no better way than overwriting the ProductController class ? This could cause incompatibility with other modules.

    By the way, at the moment I’m dealing with a custom product type which has to extend functionality from the configurable product type. Maybe someone can tell me, why I can’t retrieve the next step after I choose the configurable attributes when creating a new instance of my product type ?
    I also have to overwrite the ProductController because of the part checking for “product type id” is “configurable” for the additional layout parts.

  15. I added the above module and after adding product in the custom list when we save the product the I get following sql error

    SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`sonicsense2`.`catalog_product_link`, CONSTRAINT `FK_CAT_PRD_LNK_LNK_TYPE_ID_CAT_PRD_LNK_TYPE_LNK_TYPE_ID` FOREIGN KEY (`link_type_id`) REFERENCES `catalog_product_link_type` (`link_type_id`) )

    1. @Satyendra:

      Hi, default Magento installation comes with 5 product link type id’s occupied. This code uses product link type id of 6, and on your Magento installation some code is already occupying this id.

      First a little disclaimer, you can mess up your DB if following process goes bad.

      Now that we took care of that, you could open catalog_product_link_type table in your DB, find first available link_type_id, edit app/code/community/Inchoo/CustomLinkedProducts/Model/Catalog/Product/Link.php following file with this integer (const LINK_TYPE_CUSTOM = 6) and then remove inchoo_customlinkedproducts_setup from core_resource to allow this extension to install it self again.

      Good luck!

  16. I tried to move this block to the “product.info” column just by changing reference name to “product.info”. It does not seem to work.

  17. I have to add product list in multiple select attribute in admin. But I have not idea how can I do this? Can you please help me for this?

  18. Very useful! I managed to change the first column into a radio button by editing custom.php:

    changing

            if (!$this->isReadonly()) {
                $this->addColumn('in_products', array(
                    'header_css_class'  => 'a-center',
                    'type'              => 'checkbox',
                    'name'              => 'in_products',
                    'values'            => $this->_getSelectedProducts(),
                    'align'             => 'center',
                    'index'             => 'entity_id'
                ));
            }

    into:

            if (!$this->isReadonly()) {
                $this->addColumn('in_products', array(
                    'header_css_class'  => 'a-center',
                    'type'              => 'radio',
    				'html_name'       => 'in_products[]',
                    'value'				=> array('1'),
                    'align'             => 'center'
                ));
            }

    but then the selected item is not saved. I guess something is missing in defining the checked status and onclick event. Can anyone help me out?

  19. This is quite nice, but the rewrite of the Mage_Adminhtml_Block_Catalog_Product_Edit_Tabs is unnecessary. You can add Custom Tabs to your Product Edit View by layout.xml

    Just add this to your module layout file:

        <adminhtml_catalog_product_edit>
            <reference name="product_tabs">
                <block type="Inchoo_CustomLinkedProducts/adminhtml_catalog_product_edit_tabs_custom" name="custom"/>
                <action method="addTab">
                    <name>Custom Linked Product</name>
                    <block>custom_tab</block>
                </action>
            </reference>
        </adminhtml_catalog_product_edit>

    And you have to add a custom tab block named Inchoo_CustomLinkedProducts_Adminhtml_Catalog_Product_Edit_Tabs_Custom which extends Mage_Adminhtml_Block_Widget and implements Mage_Adminhtml_Block_Widget_Tab_Interface

    Regards

  20. Hello,
    I really can’t confirm this right now but like other attributes used by Up-sells and Cross-sells, position is also not required. For example, not including:

    app/code/community/Inchoo/CustomLinkedProducts/Block/Adminhtml/Catalog/Product/Edit/Tab/Custom.php

    $this->addColumn('position', array(
        'header' => Mage::helper('catalog')->__('Position'),
        'name' => 'position',
        'type' => 'number',
        'validate_class' => 'validate-number',
        'index' => 'position',
        'width' => 60,
        'editable' => !$this->_getProduct()->getCustomReadonly(),
        'edit_only' => !$this->_getProduct()->getId()
    ));

    and removing:

    app/code/community/Inchoo/CustomLinkedProducts/Block/Adminhtml/Catalog/Product/Edit/Tab/Custom.php

    /**
    * install product link attributes
    */
    $data = array(
        array(
            'link_type_id' => Inchoo_CustomLinkedProducts_Model_Catalog_Product_Link::LINK_TYPE_CUSTOM,
            'product_link_attribute_code' => 'position',
            'data_type' => 'int'
        )
    );
    
    $installer->getConnection()->insertMultiple($installer->getTable('catalog/product_link_attribute'), $data);

    and replacing:

    app/code/community/Inchoo/CustomLinkedProducts/Block/Catalog/Product/List/Custom.php

    $this->_itemCollection = $product->getCustomProductCollection()
        ->addAttributeToSelect('required_options')
        ->setPositionOrder()
        ->addStoreFilter()
    ;

    with:

    $this->_itemCollection = $product->getCustomProductCollection()
        ->addAttributeToSelect('required_options')
        ->addStoreFilter()
    ;

    and removing:

    app/design/adminhtml/default/default/layout/inchoo_customlinkedproducts.xml

    <action method="addColumnInputName">
        <input_name>position</input_name>
    </action>

    should give you the same results but in this case you wouldn’t be able to maintain order (position) of linked products.

    Regards

  21. What I have noticed in this kinda serialized grid is you can’t make it work without the input field called position.

    Have anyone tried to make it work without the position input field?

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <blockquote cite=""> <code> <del datetime=""> <em> <strike> <strong>. You may use following syntax for source code: <pre><code>$current = "Inchoo";</code></pre>.