Question

MageStackDay bonus question for 500pts Bounty AND a the possibility of winning a free Z-Ray license for a year. More info can be found >> here <<

The questions are provided by Magento 2 core developer Anton Kril.

Question:

I want to add a new product type to Magento. How would I go about doing this in Magento 2 dev beta

Was it helpful?

Solution

For adding a new product type in Magento 2 you need to create a etc/product_types.xml in your module. In this file you specify:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../Catalog/etc/product_types.xsd">
    <type name="demoproduct" label="Demo Product" modelInstance="Genmato\DemoProduct\Model\Product\Type\Demo" indexPriority="25" sortOrder="25">
        <customAttributes>
            <attribute name="refundable" value="true"/>
        </customAttributes>
    </type>
</config>

Then create the modelInstance:

/**
 * @category    Genmato
 * @package     Genmato_MageStackProduct
 * @copyright   Copyright (c) 2015 Genmato BV (https://genmato.com)
 */

namespace Genmato\DemoProduct\Model\Product\Type;

class Demo extends \Magento\Catalog\Model\Product\Type\AbstractType
{
    /**
     * Delete data specific for Simple product type
     *
     * @param \Magento\Catalog\Model\Product $product
     * @return void
     */
    public function deleteTypeSpecificData(\Magento\Catalog\Model\Product $product)
    {
    }
}

This will add the new product type and now you can select this when creating a new product in the backend.

Demo Product option

In the product_type.xml it is also possible to specify your own indexer or price calculation method, for more examples see the code for the product types Bundle, ConfigureProduct, Downloadable and GroupedProduct.

For the complete demo product extension see: https://github.com/Genmato/DemoProduct

EDIT:

As requested by Anton a little bit extra functionality for the new product type (If I have a little bit more time this week I will try to at some extra modifications).

For now I updated the Demo Product type with a price input field for the cost attribute: Cost price attribute

This cost attribute is used to calculate the price when it is displayed in the frontend (price attribute is not available and isn't used). For this example I used cost*1.25 (in Genmato\DemoProduct\Model\Product\Type\Demo\Price): Price calculation

The result on the frontend: Frontend result

The complete updated code is available on: https://github.com/Genmato/DemoProduct

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top