I want update product position attribute in category through the CSV feed. Anyone have any idea OR sample CSV which can accomplish my requirement.
-
Are u got it ......?– Mahi MJan 17, 2018 at 11:01
1 Answer
In controller file
public function execute()
{
$categoryId = $this->getRequest()->getParam('category');
$fileName = $_FILES["upload-stock-csv"]["name"];
$filetmpName = $_FILES["upload-stock-csv"]["tmp_name"];
if (isset($fileName) && (pathinfo($fileName, PATHINFO_EXTENSION) == 'csv')) {
//Update product position using csv
$positionUpdate = $this->_csvProcessor->getData($filetmpName);
$this->_position->updatePositionUsingsku($categoryId, $positionUpdate);
} else {
$this->messageManager->addError(__("Please select the valid file format"));
}
}
In Model file:
use Magento\Catalog\Model\Category;
use Magento\Catalog\Model\Product;
use Magento\Framework\Message\ManagerInterface;
use Magento\Framework\App\ResourceConnection;
class Position
{
protected $_messageManager;
protected $_productRepository;
protected $_categoryRepository;
public function __construct(Category $categoryRepository, Product $productRepository, ResourceConnection $resourceConnection, ManagerInterface $messageManager)
{
$this->_categoryRepository = $categoryRepository;
$this->_productRepository = $productRepository;
$this->_messageManager = $messageManager;
$this->_getConnection = $resourceConnection->getConnection();
$this->_categoryProductTable = $resourceConnection->getTableName('catalog_category_product');
}
public function updatePositionUsingsku($categoryId, $positionUpdate)
{
$adapter = $this->_getConnection;
foreach ($positionUpdate as $row) {
if ((trim($row[0]) == 'Sku') || (trim($row[0]) == 'SKU') || (trim($row[0]) == 'sku'))
continue;
$sku = trim($row[0]);
$productPosition = trim($row[1]);
//Update product position using csv
if ($sku) {
$productId = $this->_productRepository->getIdBySku($sku);
if ($productId) {
$where = array(
'category_id = ?' => (int) $categoryId,
'product_id = ?' => (int) $productId
);
$position = $productPosition;
$bind = array('position' => (int) $position);
$adapter->update($this->_categoryProductTable, $bind, $where);
$this->_messageManager->addSuccess(__(' %1 Position Updated Successfully.', $sku));
} else {
$this->_messageManager->addError(__("%1 is not available", $sku));
}
} else {
$this->_messageManager->addError(__("sku is not available"));
}
}
}
}