Skip to content

Magento2.4.2: How to add product to a given position in given category?

I’m trying to add a product in a given category in given position
like in my csv file im giving SKU,Position,CategoryId and i want to add that product in that category in given position
Here is my code

public function readCsv(): bool
    {
        $pubMediaDir = $this->directoryList->getPath(DirectoryList::MEDIA);
        $fieName = $this->getConfigFileName();
        $ds = DIRECTORY_SEPARATOR;
        $dirTest = '/csvsortoptions';

        $file = $pubMediaDir . $dirTest . $ds . $fieName;

        if (!empty($file)) {
            $csvData = $this->csvProccesor->getData($file);
            if (!$this->validateCsv($csvData)) {
                return false;
            }

            $csvDataProcessed = [];
            unset($csvData[0]);
            list($csvDataProcessed) = $this->csvProcessValues($csvData, $csvDataProcessed);

            foreach ($csvDataProcessed as $dataRow) {

                $sku = $dataRow['sku'];
                $position = $dataRow['position'];
                $categoryId = $dataRow['category_id'];

                $adapter = $this->getConnection;
                if ($sku) {
                    $productId = $this->productRepositoryInterface->get($sku)->getId();
                    if ($productId) {
                        $where = array(
                            'category_id = ?' => (int)$categoryId,
                            'product_id = ?' => (int)$productId
                        );
                        $bind = array('position' => (int)$position);
                        $adapter->update($this->categoryProductTable, $bind, $where);
                        $this->messageManager->addSuccessMessage(__(' %1  Position Updated Successfully.', $sku));
                    } else {
                        $this->messageManager->addErrorMessage(__("%1 is not available", $sku));
                    }
                } else {
                    $this->messageManager->addErrorMessage(__("sku is not available"));
                }
            }
        }
        return true;
    }

and it should add that product to given position and one thing important here to note is
it shouldn’t replace the existing product in that position but move other products position down/decrease accordingly

enter image description here