Skip to content

Magento2 add 2 new field in bundle item option selection

I’m trying to create a module which adds 2 fields in bundle option.
I’ve already managed to add 2 field:
enter image description here
But it doesn’t save values in my database.
Columns are crated but it doesn’t fill with right value.

Here is my code:

PluginUiDataProviderProductFormModifierComposite.php

<?php
declare(strict_types=1);

namespace Es100ManageBundleMaxMinPluginUiDataProviderProductFormModifier;

use MagentoBundleUiDataProviderProductFormModifierComposite as BundleComposite;
use MagentoCatalogModelLocatorLocatorInterface;
use MagentoBundleModelProductType;
use MagentoBundleUiDataProviderProductFormModifierBundlePanel;
use MagentoBundleModelSelection;

class Composite
{
protected $locator;
protected $selection;

/**
 * @param LocatorInterface $locator
 * @param Selection $selection
 */
public function __construct(
    LocatorInterface $locator,
    Selection $selection
) {
    $this->locator = $locator;
    $this->selection = $selection;
}

public function afterModifyData(BundleComposite $subject, array $data)
{
    $product = $this->locator->getProduct();
    $modelId = $product->getId();
    $isBundleProduct = $product->getTypeId() === Type::TYPE_CODE;
    if ($isBundleProduct && $modelId) {
        foreach ($data[$modelId][BundlePanel::CODE_BUNDLE_OPTIONS][BundlePanel::CODE_BUNDLE_OPTIONS] as &$option) {
            foreach ($option['bundle_selections'] as &$selection) {
                $this->selection->load($selection['selection_id']);
                $selection['min_qty'] = $this->selection->getMinQty();
                $selection['max_qty'] = $this->selection->getMaxQty();
            }
        }
    }

    return $data;
}
}

ModelLinkManagement.php

<?php
declare(strict_types=1);

namespace Es100ManageBundleMaxMinModel;

use MagentoBundleApiDataLinkInterface;
use MagentoBundleApiDataLinkInterfaceFactory;
use MagentoBundleModelResourceModelBundle;
use MagentoBundleModelResourceModelBundleFactory;
use MagentoBundleModelResourceModelOptionCollectionFactory;
use MagentoBundleModelSelection;
use MagentoBundleModelSelectionFactory;
use MagentoCatalogApiDataProductInterface;
use MagentoCatalogApiProductRepositoryInterface;
use MagentoFrameworkApiDataObjectHelper;
use MagentoFrameworkEntityManagerMetadataPool;
use MagentoFrameworkExceptionCouldNotSaveException;
use MagentoFrameworkExceptionInputException;
use MagentoFrameworkExceptionNoSuchEntityException;
use MagentoStoreModelStoreManagerInterface;

class LinkManagement extends MagentoBundleModelLinkManagement
{
/**
 * @var StoreManagerInterface
 */
private $storeManager;

/**
 * @var MetadataPool
 */
private $metadataPool;

public function __construct(
    ProductRepositoryInterface $productRepository,
    LinkInterfaceFactory $linkFactory,
    SelectionFactory $bundleSelection,
    BundleFactory $bundleFactory,
    CollectionFactory $optionCollection,
    StoreManagerInterface $storeManager,
    DataObjectHelper $dataObjectHelper,
    MetadataPool $metadataPool
) {
    parent::__construct(
        $productRepository,
        $linkFactory,
        $bundleSelection,
        $bundleFactory,
        $optionCollection,
        $storeManager,
        $dataObjectHelper,
        $metadataPool
    );
    $this->storeManager = $storeManager;
    $this->metadataPool = $metadataPool;
}

/**
 * {@inheritdoc}
 *
 * Mappa i campi min_qty e max_qty durante il salvataggio.
 */
protected function mapProductLinkToSelectionModel(
    Selection $selectionModel,
    LinkInterface $productLink,
    $linkedProductId,
    $parentProductId
): Selection {
    $selectionModel = parent::mapProductLinkToSelectionModel($selectionModel, $productLink, $linkedProductId, $parentProductId);

        $selectionModel->setData('min_qty', $productLink->getMinQty());
        $selectionModel->setData('max_qty', $productLink->getMaxQty());

    return $selectionModel;
  }
}

PluginUiDataProviderProductFormModifierBundleCustomOptions.php

<?php
declare(strict_types=1);

namespace Es100ManageBundleMaxMinPluginUiDataProviderProductFormModifier;

 use MagentoUiComponentFormField;
 use MagentoUiComponentFormElementInput;
 use MagentoUiComponentFormElementDataTypeNumber;
 use MagentoBundleUiDataProviderProductFormModifierBundleCustomOptions as MagentoBundleCustomOptions;

class BundleCustomOptions
{
const FIELD_MIN_QTY = 'min_qty';
const FIELD_MAX_QTY = 'max_qty';

public function afterModifyMeta(MagentoBundleCustomOptions $subject, array $meta)
{
    if (isset($meta['bundle-items']['children']['bundle_options']['children']['record']['children']['product_bundle_container']['children']['bundle_selections']['children']['record']['children'])) {
        $meta['bundle-items']['children']['bundle_options']['children']['record']['children']['product_bundle_container']['children']['bundle_selections']['children']['record']['children'][static::FIELD_MIN_QTY] = $this->getMinQtyFieldConfig(125);
        $meta['bundle-items']['children']['bundle_options']['children']['record']['children']['product_bundle_container']['children']['bundle_selections']['children']['record']['children'][static::FIELD_MAX_QTY] = $this->getMaxQtyFieldConfig(126);

        // Reorder table headings
        $actionDelete = $meta['bundle-items']['children']['bundle_options']['children']['record']['children']['product_bundle_container']['children']['bundle_selections']['children']['record']['children']['action_delete'];
        unset($meta['bundle-items']['children']['bundle_options']['children']['record']['children']['product_bundle_container']['children']['bundle_selections']['children']['record']['children']['action_delete']);
        $meta['bundle-items']['children']['bundle_options']['children']['record']['children']['product_bundle_container']['children']['bundle_selections']['children']['record']['children']['action_delete'] = $actionDelete;
    }

    return $meta;
}

protected function getMinQtyFieldConfig($sortOrder)
{
    return [
        'arguments' => [
            'data' => [
                'config' => [
                    'label' => __('Quantità Minima'),
                    'componentType' => Field::NAME,
                    'formElement' => Input::NAME,
                    'dataScope' => static::FIELD_MIN_QTY,
                    'dataType' => Number::NAME,
                    'sortOrder' => $sortOrder,
                    'validation' => [
                        'validate-number' => true,
                        'validate-zero-or-greater' => true
                    ],
                    'default' => 1,
                ],
            ],
        ],
    ];
}

protected function getMaxQtyFieldConfig($sortOrder)
{
    return [
        'arguments' => [
            'data' => [
                'config' => [
                    'label' => __('Quantità Massima'),
                    'componentType' => Field::NAME,
                    'formElement' => Input::NAME,
                    'dataScope' => static::FIELD_MAX_QTY,
                    'dataType' => Number::NAME,
                    'sortOrder' => $sortOrder,
                    'validation' => [
                        'validate-number' => true,
                        'validate-zero-or-greater' => true
                    ],
                    'default' => 1,
                ],
            ],
        ],
    ];
  }
}

SetupUpgradeSchema.php

<?php
declare(strict_types=1);

namespace Es100ManageBundleMaxMinSetup;

use MagentoFrameworkSetupUpgradeSchemaInterface;
use MagentoFrameworkSetupModuleContextInterface;
use MagentoFrameworkSetupSchemaSetupInterface;
use MagentoFrameworkDBDdlTable;

class UpgradeSchema implements UpgradeSchemaInterface
{
public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $context)
{
    $setup->startSetup();

    if (version_compare($context->getVersion(), '1.0.0', '<')) {
        $connection = $setup->getConnection();
        $tableName = $setup->getTable('catalog_product_bundle_selection');

        if ($connection->isTableExists($tableName)) {
            if (!$connection->tableColumnExists($tableName, 'min_qty')) {
                $connection->addColumn(
                    $tableName,
                    'min_qty',
                    [
                        'type' => Table::TYPE_INTEGER,
                        'nullable' => true,
                        'comment' => 'Quantità minima'
                    ]
                );
            }

            if (!$connection->tableColumnExists($tableName, 'max_qty')) {
                $connection->addColumn(
                    $tableName,
                    'max_qty',
                    [
                        'type' => Table::TYPE_INTEGER,
                        'nullable' => true,
                        'comment' => 'Quantità massima'
                    ]
                );
            }
        }
    }

    $setup->endSetup();
 }
}