top of page
Writer's pictureVishesh Dwivedi

Custom Linked Product Types Magento2

Updated: May 21, 2022

Let’s suppose we need to add a product collection on the product view page and we want the admin to add those products on the basis of some specifications, so for that, we can use custom linked product types like Related products.


Today we are going to see how can we create a custom product link in Magento 2. So, first of all, create basic module files like module.xml and registration.php to register the module.


Now, to create a custom product link type, we need to add its entry in catalog_product_link_type and catalog_product_link_attribute tables, then create modifier (to add it on product edit page), model (to get linked product collection from catalog product model), and ui_component.



Develop Data Patch for Custom Linked Product Types

So let’s begin with schema patch, create a file –


Vishesh/CustomLink/Setup/Patch/Data/CreateLink.php

The schema patch file will make an entry for our custom linked product type in the database.



<?php
namespace Vishesh\CustomLink\Setup\Patch\Data;

use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\Patch\DataPatchInterface;

class CreateLink implements DataPatchInterface
{
    /**
     * @param ModuleDataSetupInterface $moduleDataSetup
     */
    public function __construct(
        ModuleDataSetupInterface $moduleDataSetup
    ) {
        $this->moduleDataSetup = $moduleDataSetup;
    }

    public function apply()
    {
        $setup = $this->moduleDataSetup;

        $data = [
            [
                'link_type_id' => \Vishesh\CustomLink\Model\Product\Link::LINK_TYPE_CUSTOMLINK,
                'code' => 'customlink'
            ],
        ];

        foreach ($data as $bind) {
            $setup->getConnection()
                ->insertForce($setup->getTable('catalog_product_link_type'), $bind);
        }
        $data = [
            [
                'link_type_id' => \Vishesh\CustomLink\Model\Product\Link::LINK_TYPE_CUSTOMLINK,
                'product_link_attribute_code' => 'position',
                'data_type' => 'int',
            ]
        ];
        $setup->getConnection()
            ->insertMultiple($setup->getTable('catalog_product_link_attribute'), $data);
    }

    /**
     * {@inheritdoc}
     */
    public static function getDependencies()
    {
        return [];
    }

    /**
     * {@inheritdoc}
     */
    public function getAliases()
    {
        return [];
    }
}


Create Custom Linked Product Types Model

Inject LinkProvider Dependencies

Create Injected Model files

Create UI grid for Custom Linked Product Type



留言


bottom of page