2

I want to assign product problematically to category. Magento\Catalog\Api\CategoryLinkManagementInterface using DI. below is snippet of code.

    protected $categoryLinkManagement;

    public function __construct(
    \Magento\Framework\Stdlib\DateTime\Timezone $_stdTimezone,
    \Magento\Framework\Stdlib\DateTime\DateTime $stdlibDateTime,
    \Kensium\Newproduct\Model\CategoryLink $categoryLinkManagement,
    \Magento\Backend\Block\Template\Context $context,
    \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
    array $data = []
    ) {
        $this->_stdTimezone = $_stdTimezone;
        $this->stdlibDateTime = $stdlibDateTime;
        $this->categoryLinkManagement = $categoryLinkManagement;
        $this->_productCollectionFactory = $productCollectionFactory;
        parent::__construct($context, $data);
    }

    /**
     * Method executed when cron runs in server
     */
    public function execute() {
    $pid = array();

    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $newCategoryId = $objectManager->create('\Magento\Framework\App\Config\ScopeConfigInterface')->getValue('productlabels/newtodays/newcategoryid');
$saleCategoryId = $objectManager->create('\Magento\Framework\App\Config\ScopeConfigInterface')->getValue('productlabels/newtodays/salecategoryid');

    $collection = $this->_productCollectionFactory->create();
    $this->NewProducts($collection,$newCategoryId);
    $this->SaleProducts($collection,$saleCategoryId);


    }

    private function getCategoryLinkManagement()
    {
        if (null === $this->categoryLinkManagement) {
        $this->categoryLinkManagement = \Magento\Framework\App\ObjectManager::getInstance()
            ->get('\Kensium\Newproduct\Model\CategoryLink');
        }
        return $this->categoryLinkManagement;
    }
public function NewProducts($collection,$newCategoryId)
        {
        $today = $this->_stdTimezone->date()->format('Y-m-d H:i:s');
        $lastday = date('Y-m-d h:m:s', strtotime($today."+90 days"));
            $collection->addAttributeToSelect('*')             
                   ->addFieldToFilter('new_to', ['lteq' => $lastday]);

        foreach($collection as $col):
            if($col->getSku()):
                $this->getCategoryLinkManagement()->assignProductToCategories(
                    $col->getSku(),
                    array($newCategoryId)
                );


            endif;
        endforeach;
        }

This work when product is assign to another category. but there is 2 problem

1)Product should assign to other category otherwise i will get error category doesn't contain product due to below code in

$this->getCategoryLinkRepository()->deleteByIds($categoryId, $productSku);

on Magento\Catalog\Model\CategoryLinkManagement :: assignProductToCategories()

2) This will remove product from other categories.

Is there any other option to achieve this?

2

You can find the following code , It will assign product to the category

     protected $productLinkFactory;

     /**
     * @var \Magento\Catalog\Api\CategoryLinkRepositoryInterface
     */
    protected $categoryLinkRepository;

       public function __construct( 
      \Magento\Catalog\Api\Data\CategoryProductLinkInterfaceFactory 
      $productLinkFactory)
      {
        $this->productLinkFactory = $productLinkFactory;
      }

   public function assignProduct()
   {
     $sku=234;
     $categoryId=23;
    $this-> getCategoryLinkManagement($sku, $categoryId);
   }

   public function getCategoryLinkManagement($sku, $categoryId)
    {

        $categoryProductLink = $this->productLinkFactory->create();
        $categoryProductLink->setSku($sku);
        $categoryProductLink->setCategoryId($categoryId);
        $categoryProductLink->setPosition(0);
        $this->getCategoryLinkRepository()->save($categoryProductLink);

        return true;


    }


    private function getCategoryLinkRepository()
    {
        if (null === $this->categoryLinkRepository) {
            $this->categoryLinkRepository = \Magento\Framework\App\ObjectManager::getInstance()
                ->get(\Magento\Catalog\Api\CategoryLinkRepositoryInterface::class);
        }
        return $this->categoryLinkRepository;
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.