1

I'm building rest API to clear compare items list

here is code I'm using

  /**
* @api
* 
* @return int
*/
public function clearItems(){
    $userType = $this->userContext->getUserType();
    $id = $this->userContext->getUserId();

    if($userType === UserContextInterface::USER_TYPE_CUSTOMER){
        $this->collection->setCustomerId($id);
    }
    else if($userType === UserContextInterface::USER_TYPE_GUEST){
        $this->collection->setVisitorId($id);
    }
    $this->collection->setCustomerId($id);

    $this->collection->clear();

    return $id;
}

but it's deleted only from database and stay in the store. and when open the compare list from the store it returned again to database and returned id is differ from the logged in user id

1

Please update your function like below.

public function __construct(
  -------
  \Magento\Catalog\Helper\Product\Compare $compareHelper,
  -------
) {
     -----
     $this->compareHelper = $compareHelper;
     -----
 }
public function clearItems(){
$userType = $this->userContext->getUserType();
$id = $this->userContext->getUserId();

if($userType === UserContextInterface::USER_TYPE_CUSTOMER){
    $this->collection->setCustomerId($id);
}
else if($userType === UserContextInterface::USER_TYPE_GUEST){
    $this->collection->setVisitorId($id);
}
$this->collection->setCustomerId($id);

$this->collection->clear();
$this->compareHelper->calculate();
return $id;
}

I hope it'll work for you.

3
  • what does this line do $this->compareHelper->calculate();? I've checked this function but didn't understand why to use it – Yomna Mansour Nov 25 '18 at 16:07
  • it'll update update compare product collection which is in section or customer data. – Ramkishan Suthar Nov 25 '18 at 16:09
  • that's working for only one customer. it keeps seeing the id of the first logged in customer only – Yomna Mansour Nov 26 '18 at 9:27

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.