0

I would like to create a download link to the uploaded file on a downloadable product.

All downloadables do not have price and customers do not need to purchase them

Replace Add To Cart button with Download(clicking on download button will download file directly)

1

On top of the advice provided above, here are 2 approaches to load downloadable files data for a product instance:

1- Using LinkRepositoryInterface

public function __construct(
    \Magento\Downloadable\Api\LinkRepositoryInterface $linkRepository,
    \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
) {
    $this->linkRepository = $linkRepository;
    $this->productRepository = $productRepository;
}

public function getLinks($productId) {
    // Load the product from id
    $product = $this->productRepository->getById($productId);

    // Output array
    $output = [];

    // Get the product downloadable links
    $links = $this->linkRepository->getList($product->getSku());

    // Add each link data to the output array
    foreach ($links as $item) {
        $output[] = $item->getData();
    }

    return $output;
}

2- Using directly the product instance

public function __construct(
    \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
) {
    $this->productRepository = $productRepository;
}

public function getLinks($productId) {
    // Load the product from id
    $product = $this->productRepository->getById($productId);

    // Output array
    $output = [];

    // Get the product downloadable links
    $extensionAttributes = $product->getExtensionAttributes();
    $links = $extensionAttributes->getDownloadableProductLinks();

    // Add each link data to the output array
    foreach ($links as $item) {
        $output[] = $item->getData();
    }

    return $output;
}
0

You may need to write a custom module to achieve what you are trying to do.

Below is a rough approach to doing that.

  • Override the product template file and check whether the product type is downloadable and the price is 0. Based on the condition, hide the add to cart button and add a custom button labeling "Download" or whatever you like.
  • On clicking on the custom button, send an ajax request to your custom controller action.
  • In the custom controller action, place order programmatically, so that you can get the downloadable link for the purchase in the response.
  • Redirect user to the response link to allow the user to download the product.

Note: Above steps are required because, in Magento, there is no direct provision to allow product download directly.

Update: Similar programmatic solution for Magento 1.x was posted here

0

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.