You can delete Downloadable Links by link id using Magento 2 Programmatic way.
To create a downloadable product, you need to required attached links/files with the Product to download a sample.
Using Link Id, We could delete the link attached with the product by the delete($linkId) method with simple code,
<?php
namespace Jesadiya\DeleteDownloadableLinks\Model;
use Psr\Log\LoggerInterface;
use Magento\Downloadable\Api\LinkRepositoryInterface;
use Magento\Framework\Exception\NoSuchEntityException;
class DeleteLinksByLinkId
{
/**
* @var LinkRepositoryInterface
*/
private $linkRepository;
/**
* @var LoggerInterface
*/
private $logger;
public function __construct(
LinkRepositoryInterface $linkRepository,
LoggerInterface $logger
) {
$this->linkRepository = $linkRepository;
$this->logger = $logger;
}
/**
* Get list of links of Downloadable Product.
*
* @param int $linkId
* @return bool
*/
public function deleteLinks(int $linkId): array
{
$isDownloadableLinkDeleted = false;
try {
$isDownloadableLinkDeleted = $this->linkRepository->delete($linkId);
} catch (NoSuchEntityException $exception) {
$this->logger->error($exception->getMessage());
}
return $isDownloadableLinkDeleted;
}
}
You required downloadable links id to delete from the item,
$linkId = 1; //Downloadable item sku $downloadableLink = $this->deleteLinks($linkId);
If Downloadable links not found, Error will be thrown,
No downloadable link with the provided ID was found. Verify the ID and try again.
Output:
boolean
