How to load product by SKU in magento 2
It's pretty basic, but I can’t find a working example on Stackexchange or google. I want to load a product from a helper or block. I already tried some things like:
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$product = $objectManager->create('MagentoCatalogApiDataProductInterface');
$product->get('<SKU>');
$product->getName();
This returns nothing. I also tried loading any available models and API’s, but nothing seems to work with SKU’s.
magento2 product
add a comment |
It's pretty basic, but I can’t find a working example on Stackexchange or google. I want to load a product from a helper or block. I already tried some things like:
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$product = $objectManager->create('MagentoCatalogApiDataProductInterface');
$product->get('<SKU>');
$product->getName();
This returns nothing. I also tried loading any available models and API’s, but nothing seems to work with SKU’s.
magento2 product
add a comment |
It's pretty basic, but I can’t find a working example on Stackexchange or google. I want to load a product from a helper or block. I already tried some things like:
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$product = $objectManager->create('MagentoCatalogApiDataProductInterface');
$product->get('<SKU>');
$product->getName();
This returns nothing. I also tried loading any available models and API’s, but nothing seems to work with SKU’s.
magento2 product
It's pretty basic, but I can’t find a working example on Stackexchange or google. I want to load a product from a helper or block. I already tried some things like:
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$product = $objectManager->create('MagentoCatalogApiDataProductInterface');
$product->get('<SKU>');
$product->getName();
This returns nothing. I also tried loading any available models and API’s, but nothing seems to work with SKU’s.
magento2 product
magento2 product
asked Apr 17 '16 at 20:07
Dennis van SchaikDennis van Schaik
5031318
5031318
add a comment |
add a comment |
7 Answers
7
active
oldest
votes
The correct way, according to Magento 2 service contracts, is using repositories:
$product = $this->productRepositoryInterface->get($sku);
Use MagentoCatalogApiProductRepositoryInterface
to get it in your constructor.
Full example:
...
private $productRepository;
...
public function __construct(
...
MagentoCatalogApiProductRepositoryInterface $productRepository
...
) {
...
$this->productRepository = $productRepository;
...
}
public function loadMyProduct($sku)
{
return $this->productRepository->get($sku);
}
...
Note:
If the product does not exists, this method triggers a NoSuchEntityException
error as it would be in the best Magento2 practice.
So, if you need to handle somehow, wrap it in a try/catch block.
9
This method gives an error when no product is found. So for checking if an product exists, It seems @fschmengler's solution might be the better way to go.
– Dennis van Schaik
Apr 20 '16 at 11:00
1
can you pls add more details aboutUse MagentoCatalogApiProductRepositoryInterface to get it in your constructor.
? What shall I do? Thanks a lot
– davideghz
Dec 16 '16 at 17:17
See my updated post
– Phoenix128_RiccardoT
Dec 16 '16 at 17:25
The actual proper Magento 2 way to use service contracts is more complicated. Repository->get() is still a model call which shouldn't be used. The correct way is to use repository->getList() with SearchCriteriaBuilder. See my answer on Orders (pretty much the same method): magento.stackexchange.com/questions/140374/…
– Jacco Amersfoort
Apr 10 '17 at 10:08
1
@JaccoAmersfoort, I confirm "get" is the right way. In your example it has been suggested because "get" in order repository requires "order id" and that user was looking for "increment id". In that case a getList is the best option, but if you can use "get" you should use it.
– Phoenix128_RiccardoT
Apr 10 '17 at 10:57
|
show 8 more comments
Instead of using the object manager directly, inject the ProductFactory:
public function __construct(MagentoCatalogModelProductFactory $productFactory)
{
$this->productFactory = $productFactory;
}
Then use it like this:
$product = $this->productFactory->create();
$product->loadByAttribute('sku', $sku);
or to do a full load (the above loads it using a collection):
$product = $this->productFactory->create();
$product->load($product->getIdBySku($sku));
6
Actually while this is still working, usingload()
and collections is the "Magento 1" way, better use the repository as suggested by @RiccardoT.
– Fabian Schmengler
Apr 17 '16 at 20:46
1
Also, your method will return a Product model, whilst using the Repository will give you a Product data model (Api/Data/Product
), which is a Product model converted into a dumbed-down DTO. Something to consider, as they're quite different.
– nevvermind
Apr 18 '16 at 0:02
@FabianSchmengler: Tried using$product = $this->productFactory->create(); $product->load($product->getIdBySku($sku)); $product->getThumbnailUrl()
to display product thumbnail image, but its not working.
– Slimshadddyyy
Jan 31 '18 at 7:24
@FabianSchmengler yes recommendation of Repository is good as @RiccardoT answer. but what if i entered wrong sku then it will break whole operation & throw exception, so in this case we must have to depend onproductFactory
– Himanshu
Nov 5 '18 at 6:20
@Himanshu catch the exception. And if you need a fresh product instance in that case, you can still create it using the factory
– Fabian Schmengler
Nov 5 '18 at 17:00
|
show 1 more comment
I like @phoenix128-riccardot 's answer, but would add an exception, just in case the product does not exist:
try {
$product = $this->productRepositoryInterface->get($sku);
} catch (MagentoFrameworkExceptionNoSuchEntityException $e){
// insert your error handling here
}
I was not able to add it as a comment (too low reputation), sorry.
add a comment |
Try this:
/** @var MagentoCatalogModelProductFactory $productFactory */
$product = $productFactory->create();
$product->loadByAttribute('sku', 'my sku');
// $product->load($product->getId()); // may need to do this too,
// see MagentoFrameworkApiAttributeValueFactoryAbstractModel::loadByAttribute
I need to get the product_id from sku (column of csv) during csv import and save only the product_id..How to achieve?
– Sushivam
Aug 25 '16 at 9:45
add a comment |
You can try that
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$productRepository = $objectManager->get('MagentoCatalogModelProductRepository');
$productObj = $productRepository->get('<SKU>');
echo $productObj->getId();
add a comment |
Using Dependency Injection (DI)
Here is the example code to get the product information by product Id and SKU in Magento 2 using dependency injection.
In this, we might need to inject the object of the MagentoCatalogModelProductRepository class in the constructor of our module’s block class and access it from the view ( .phtml ) file.
Sample File Path: app/code/YourCompanyName/YourModuleName/Block/YourCustomBlock.php
<?php
namespace YourCompanyNameYourModuleNameBlock;
class YourCustomBlock extends MagentoFrameworkViewElementTemplate
{
protected $_productRepository;
public function __construct(
MagentoFrameworkViewElementTemplateContext $context,
MagentoCatalogModelProductRepository $productRepository,
array $data =
) {
$this->_productRepository = $productRepository;
parent::__construct($context, $data);
}
public function getProductById($id) {
return $this->_productRepository->getById($id);
}
public function getProductBySku($sku) {
return $this->_productRepository->get($sku);
}
}
Now, we can use the functions in our view (.phtml) file as follows.
// get product by id
$product = $block->getProductById(15);
// get product by sku
$product = $block->getProductBySku('MT12');
echo $product->getEntityId() . '<br>';
echo $product->getName() . '<br>';
echo $product->getSKU() . '<br>';
echo $product->getPrice() . '<br>';
echo $product->getSpecialPrice() . '<br>';
echo $product->getTypeId() . '<br>';
echo $product->getProductUrl() . '<br>';
Using Object Manager
Here is the example code to get the product information by product id and SKU in Magento 2 using object manager.
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$productRepository = $objectManager->get('MagentoCatalogModelProductRepository');
// get product by product id
$product = $productRepository->getById(15);
// get product by product sku
$product = $productRepository->get('MT12');
echo $product->getEntityId() . '<br>';
echo $product->getName() . '<br>';
echo $product->getSKU() . '<br>';
echo $product->getPrice() . '<br>';
echo $product->getSpecialPrice() . '<br>';
echo $product->getTypeId() . '<br>';
echo $product->getProductUrl() . '<br>';
add a comment |
<?php
use MagentoFrameworkAppBootstrap;
require __DIR__ . '/app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$obj = $bootstrap->getObjectManager();
$state = $obj->get('MagentoFrameworkAppState');
$state->setAreaCode('frontend');
$sku ='24-MB01';
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$productObject = $objectManager->get('MagentoCatalogModelProduct');
$product = $productObject->loadByAttribute('sku', $sku);
echo $product->getName();
?>
add a comment |
Your Answer
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "479"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f111245%2fhow-to-load-product-by-sku-in-magento-2%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
7 Answers
7
active
oldest
votes
7 Answers
7
active
oldest
votes
active
oldest
votes
active
oldest
votes
The correct way, according to Magento 2 service contracts, is using repositories:
$product = $this->productRepositoryInterface->get($sku);
Use MagentoCatalogApiProductRepositoryInterface
to get it in your constructor.
Full example:
...
private $productRepository;
...
public function __construct(
...
MagentoCatalogApiProductRepositoryInterface $productRepository
...
) {
...
$this->productRepository = $productRepository;
...
}
public function loadMyProduct($sku)
{
return $this->productRepository->get($sku);
}
...
Note:
If the product does not exists, this method triggers a NoSuchEntityException
error as it would be in the best Magento2 practice.
So, if you need to handle somehow, wrap it in a try/catch block.
9
This method gives an error when no product is found. So for checking if an product exists, It seems @fschmengler's solution might be the better way to go.
– Dennis van Schaik
Apr 20 '16 at 11:00
1
can you pls add more details aboutUse MagentoCatalogApiProductRepositoryInterface to get it in your constructor.
? What shall I do? Thanks a lot
– davideghz
Dec 16 '16 at 17:17
See my updated post
– Phoenix128_RiccardoT
Dec 16 '16 at 17:25
The actual proper Magento 2 way to use service contracts is more complicated. Repository->get() is still a model call which shouldn't be used. The correct way is to use repository->getList() with SearchCriteriaBuilder. See my answer on Orders (pretty much the same method): magento.stackexchange.com/questions/140374/…
– Jacco Amersfoort
Apr 10 '17 at 10:08
1
@JaccoAmersfoort, I confirm "get" is the right way. In your example it has been suggested because "get" in order repository requires "order id" and that user was looking for "increment id". In that case a getList is the best option, but if you can use "get" you should use it.
– Phoenix128_RiccardoT
Apr 10 '17 at 10:57
|
show 8 more comments
The correct way, according to Magento 2 service contracts, is using repositories:
$product = $this->productRepositoryInterface->get($sku);
Use MagentoCatalogApiProductRepositoryInterface
to get it in your constructor.
Full example:
...
private $productRepository;
...
public function __construct(
...
MagentoCatalogApiProductRepositoryInterface $productRepository
...
) {
...
$this->productRepository = $productRepository;
...
}
public function loadMyProduct($sku)
{
return $this->productRepository->get($sku);
}
...
Note:
If the product does not exists, this method triggers a NoSuchEntityException
error as it would be in the best Magento2 practice.
So, if you need to handle somehow, wrap it in a try/catch block.
9
This method gives an error when no product is found. So for checking if an product exists, It seems @fschmengler's solution might be the better way to go.
– Dennis van Schaik
Apr 20 '16 at 11:00
1
can you pls add more details aboutUse MagentoCatalogApiProductRepositoryInterface to get it in your constructor.
? What shall I do? Thanks a lot
– davideghz
Dec 16 '16 at 17:17
See my updated post
– Phoenix128_RiccardoT
Dec 16 '16 at 17:25
The actual proper Magento 2 way to use service contracts is more complicated. Repository->get() is still a model call which shouldn't be used. The correct way is to use repository->getList() with SearchCriteriaBuilder. See my answer on Orders (pretty much the same method): magento.stackexchange.com/questions/140374/…
– Jacco Amersfoort
Apr 10 '17 at 10:08
1
@JaccoAmersfoort, I confirm "get" is the right way. In your example it has been suggested because "get" in order repository requires "order id" and that user was looking for "increment id". In that case a getList is the best option, but if you can use "get" you should use it.
– Phoenix128_RiccardoT
Apr 10 '17 at 10:57
|
show 8 more comments
The correct way, according to Magento 2 service contracts, is using repositories:
$product = $this->productRepositoryInterface->get($sku);
Use MagentoCatalogApiProductRepositoryInterface
to get it in your constructor.
Full example:
...
private $productRepository;
...
public function __construct(
...
MagentoCatalogApiProductRepositoryInterface $productRepository
...
) {
...
$this->productRepository = $productRepository;
...
}
public function loadMyProduct($sku)
{
return $this->productRepository->get($sku);
}
...
Note:
If the product does not exists, this method triggers a NoSuchEntityException
error as it would be in the best Magento2 practice.
So, if you need to handle somehow, wrap it in a try/catch block.
The correct way, according to Magento 2 service contracts, is using repositories:
$product = $this->productRepositoryInterface->get($sku);
Use MagentoCatalogApiProductRepositoryInterface
to get it in your constructor.
Full example:
...
private $productRepository;
...
public function __construct(
...
MagentoCatalogApiProductRepositoryInterface $productRepository
...
) {
...
$this->productRepository = $productRepository;
...
}
public function loadMyProduct($sku)
{
return $this->productRepository->get($sku);
}
...
Note:
If the product does not exists, this method triggers a NoSuchEntityException
error as it would be in the best Magento2 practice.
So, if you need to handle somehow, wrap it in a try/catch block.
edited Nov 5 '18 at 11:16
answered Apr 17 '16 at 20:42
Phoenix128_RiccardoTPhoenix128_RiccardoT
5,31021230
5,31021230
9
This method gives an error when no product is found. So for checking if an product exists, It seems @fschmengler's solution might be the better way to go.
– Dennis van Schaik
Apr 20 '16 at 11:00
1
can you pls add more details aboutUse MagentoCatalogApiProductRepositoryInterface to get it in your constructor.
? What shall I do? Thanks a lot
– davideghz
Dec 16 '16 at 17:17
See my updated post
– Phoenix128_RiccardoT
Dec 16 '16 at 17:25
The actual proper Magento 2 way to use service contracts is more complicated. Repository->get() is still a model call which shouldn't be used. The correct way is to use repository->getList() with SearchCriteriaBuilder. See my answer on Orders (pretty much the same method): magento.stackexchange.com/questions/140374/…
– Jacco Amersfoort
Apr 10 '17 at 10:08
1
@JaccoAmersfoort, I confirm "get" is the right way. In your example it has been suggested because "get" in order repository requires "order id" and that user was looking for "increment id". In that case a getList is the best option, but if you can use "get" you should use it.
– Phoenix128_RiccardoT
Apr 10 '17 at 10:57
|
show 8 more comments
9
This method gives an error when no product is found. So for checking if an product exists, It seems @fschmengler's solution might be the better way to go.
– Dennis van Schaik
Apr 20 '16 at 11:00
1
can you pls add more details aboutUse MagentoCatalogApiProductRepositoryInterface to get it in your constructor.
? What shall I do? Thanks a lot
– davideghz
Dec 16 '16 at 17:17
See my updated post
– Phoenix128_RiccardoT
Dec 16 '16 at 17:25
The actual proper Magento 2 way to use service contracts is more complicated. Repository->get() is still a model call which shouldn't be used. The correct way is to use repository->getList() with SearchCriteriaBuilder. See my answer on Orders (pretty much the same method): magento.stackexchange.com/questions/140374/…
– Jacco Amersfoort
Apr 10 '17 at 10:08
1
@JaccoAmersfoort, I confirm "get" is the right way. In your example it has been suggested because "get" in order repository requires "order id" and that user was looking for "increment id". In that case a getList is the best option, but if you can use "get" you should use it.
– Phoenix128_RiccardoT
Apr 10 '17 at 10:57
9
9
This method gives an error when no product is found. So for checking if an product exists, It seems @fschmengler's solution might be the better way to go.
– Dennis van Schaik
Apr 20 '16 at 11:00
This method gives an error when no product is found. So for checking if an product exists, It seems @fschmengler's solution might be the better way to go.
– Dennis van Schaik
Apr 20 '16 at 11:00
1
1
can you pls add more details about
Use MagentoCatalogApiProductRepositoryInterface to get it in your constructor.
? What shall I do? Thanks a lot– davideghz
Dec 16 '16 at 17:17
can you pls add more details about
Use MagentoCatalogApiProductRepositoryInterface to get it in your constructor.
? What shall I do? Thanks a lot– davideghz
Dec 16 '16 at 17:17
See my updated post
– Phoenix128_RiccardoT
Dec 16 '16 at 17:25
See my updated post
– Phoenix128_RiccardoT
Dec 16 '16 at 17:25
The actual proper Magento 2 way to use service contracts is more complicated. Repository->get() is still a model call which shouldn't be used. The correct way is to use repository->getList() with SearchCriteriaBuilder. See my answer on Orders (pretty much the same method): magento.stackexchange.com/questions/140374/…
– Jacco Amersfoort
Apr 10 '17 at 10:08
The actual proper Magento 2 way to use service contracts is more complicated. Repository->get() is still a model call which shouldn't be used. The correct way is to use repository->getList() with SearchCriteriaBuilder. See my answer on Orders (pretty much the same method): magento.stackexchange.com/questions/140374/…
– Jacco Amersfoort
Apr 10 '17 at 10:08
1
1
@JaccoAmersfoort, I confirm "get" is the right way. In your example it has been suggested because "get" in order repository requires "order id" and that user was looking for "increment id". In that case a getList is the best option, but if you can use "get" you should use it.
– Phoenix128_RiccardoT
Apr 10 '17 at 10:57
@JaccoAmersfoort, I confirm "get" is the right way. In your example it has been suggested because "get" in order repository requires "order id" and that user was looking for "increment id". In that case a getList is the best option, but if you can use "get" you should use it.
– Phoenix128_RiccardoT
Apr 10 '17 at 10:57
|
show 8 more comments
Instead of using the object manager directly, inject the ProductFactory:
public function __construct(MagentoCatalogModelProductFactory $productFactory)
{
$this->productFactory = $productFactory;
}
Then use it like this:
$product = $this->productFactory->create();
$product->loadByAttribute('sku', $sku);
or to do a full load (the above loads it using a collection):
$product = $this->productFactory->create();
$product->load($product->getIdBySku($sku));
6
Actually while this is still working, usingload()
and collections is the "Magento 1" way, better use the repository as suggested by @RiccardoT.
– Fabian Schmengler
Apr 17 '16 at 20:46
1
Also, your method will return a Product model, whilst using the Repository will give you a Product data model (Api/Data/Product
), which is a Product model converted into a dumbed-down DTO. Something to consider, as they're quite different.
– nevvermind
Apr 18 '16 at 0:02
@FabianSchmengler: Tried using$product = $this->productFactory->create(); $product->load($product->getIdBySku($sku)); $product->getThumbnailUrl()
to display product thumbnail image, but its not working.
– Slimshadddyyy
Jan 31 '18 at 7:24
@FabianSchmengler yes recommendation of Repository is good as @RiccardoT answer. but what if i entered wrong sku then it will break whole operation & throw exception, so in this case we must have to depend onproductFactory
– Himanshu
Nov 5 '18 at 6:20
@Himanshu catch the exception. And if you need a fresh product instance in that case, you can still create it using the factory
– Fabian Schmengler
Nov 5 '18 at 17:00
|
show 1 more comment
Instead of using the object manager directly, inject the ProductFactory:
public function __construct(MagentoCatalogModelProductFactory $productFactory)
{
$this->productFactory = $productFactory;
}
Then use it like this:
$product = $this->productFactory->create();
$product->loadByAttribute('sku', $sku);
or to do a full load (the above loads it using a collection):
$product = $this->productFactory->create();
$product->load($product->getIdBySku($sku));
6
Actually while this is still working, usingload()
and collections is the "Magento 1" way, better use the repository as suggested by @RiccardoT.
– Fabian Schmengler
Apr 17 '16 at 20:46
1
Also, your method will return a Product model, whilst using the Repository will give you a Product data model (Api/Data/Product
), which is a Product model converted into a dumbed-down DTO. Something to consider, as they're quite different.
– nevvermind
Apr 18 '16 at 0:02
@FabianSchmengler: Tried using$product = $this->productFactory->create(); $product->load($product->getIdBySku($sku)); $product->getThumbnailUrl()
to display product thumbnail image, but its not working.
– Slimshadddyyy
Jan 31 '18 at 7:24
@FabianSchmengler yes recommendation of Repository is good as @RiccardoT answer. but what if i entered wrong sku then it will break whole operation & throw exception, so in this case we must have to depend onproductFactory
– Himanshu
Nov 5 '18 at 6:20
@Himanshu catch the exception. And if you need a fresh product instance in that case, you can still create it using the factory
– Fabian Schmengler
Nov 5 '18 at 17:00
|
show 1 more comment
Instead of using the object manager directly, inject the ProductFactory:
public function __construct(MagentoCatalogModelProductFactory $productFactory)
{
$this->productFactory = $productFactory;
}
Then use it like this:
$product = $this->productFactory->create();
$product->loadByAttribute('sku', $sku);
or to do a full load (the above loads it using a collection):
$product = $this->productFactory->create();
$product->load($product->getIdBySku($sku));
Instead of using the object manager directly, inject the ProductFactory:
public function __construct(MagentoCatalogModelProductFactory $productFactory)
{
$this->productFactory = $productFactory;
}
Then use it like this:
$product = $this->productFactory->create();
$product->loadByAttribute('sku', $sku);
or to do a full load (the above loads it using a collection):
$product = $this->productFactory->create();
$product->load($product->getIdBySku($sku));
answered Apr 17 '16 at 20:41
Fabian SchmenglerFabian Schmengler
54.7k21133346
54.7k21133346
6
Actually while this is still working, usingload()
and collections is the "Magento 1" way, better use the repository as suggested by @RiccardoT.
– Fabian Schmengler
Apr 17 '16 at 20:46
1
Also, your method will return a Product model, whilst using the Repository will give you a Product data model (Api/Data/Product
), which is a Product model converted into a dumbed-down DTO. Something to consider, as they're quite different.
– nevvermind
Apr 18 '16 at 0:02
@FabianSchmengler: Tried using$product = $this->productFactory->create(); $product->load($product->getIdBySku($sku)); $product->getThumbnailUrl()
to display product thumbnail image, but its not working.
– Slimshadddyyy
Jan 31 '18 at 7:24
@FabianSchmengler yes recommendation of Repository is good as @RiccardoT answer. but what if i entered wrong sku then it will break whole operation & throw exception, so in this case we must have to depend onproductFactory
– Himanshu
Nov 5 '18 at 6:20
@Himanshu catch the exception. And if you need a fresh product instance in that case, you can still create it using the factory
– Fabian Schmengler
Nov 5 '18 at 17:00
|
show 1 more comment
6
Actually while this is still working, usingload()
and collections is the "Magento 1" way, better use the repository as suggested by @RiccardoT.
– Fabian Schmengler
Apr 17 '16 at 20:46
1
Also, your method will return a Product model, whilst using the Repository will give you a Product data model (Api/Data/Product
), which is a Product model converted into a dumbed-down DTO. Something to consider, as they're quite different.
– nevvermind
Apr 18 '16 at 0:02
@FabianSchmengler: Tried using$product = $this->productFactory->create(); $product->load($product->getIdBySku($sku)); $product->getThumbnailUrl()
to display product thumbnail image, but its not working.
– Slimshadddyyy
Jan 31 '18 at 7:24
@FabianSchmengler yes recommendation of Repository is good as @RiccardoT answer. but what if i entered wrong sku then it will break whole operation & throw exception, so in this case we must have to depend onproductFactory
– Himanshu
Nov 5 '18 at 6:20
@Himanshu catch the exception. And if you need a fresh product instance in that case, you can still create it using the factory
– Fabian Schmengler
Nov 5 '18 at 17:00
6
6
Actually while this is still working, using
load()
and collections is the "Magento 1" way, better use the repository as suggested by @RiccardoT.– Fabian Schmengler
Apr 17 '16 at 20:46
Actually while this is still working, using
load()
and collections is the "Magento 1" way, better use the repository as suggested by @RiccardoT.– Fabian Schmengler
Apr 17 '16 at 20:46
1
1
Also, your method will return a Product model, whilst using the Repository will give you a Product data model (
Api/Data/Product
), which is a Product model converted into a dumbed-down DTO. Something to consider, as they're quite different.– nevvermind
Apr 18 '16 at 0:02
Also, your method will return a Product model, whilst using the Repository will give you a Product data model (
Api/Data/Product
), which is a Product model converted into a dumbed-down DTO. Something to consider, as they're quite different.– nevvermind
Apr 18 '16 at 0:02
@FabianSchmengler: Tried using
$product = $this->productFactory->create(); $product->load($product->getIdBySku($sku)); $product->getThumbnailUrl()
to display product thumbnail image, but its not working.– Slimshadddyyy
Jan 31 '18 at 7:24
@FabianSchmengler: Tried using
$product = $this->productFactory->create(); $product->load($product->getIdBySku($sku)); $product->getThumbnailUrl()
to display product thumbnail image, but its not working.– Slimshadddyyy
Jan 31 '18 at 7:24
@FabianSchmengler yes recommendation of Repository is good as @RiccardoT answer. but what if i entered wrong sku then it will break whole operation & throw exception, so in this case we must have to depend on
productFactory
– Himanshu
Nov 5 '18 at 6:20
@FabianSchmengler yes recommendation of Repository is good as @RiccardoT answer. but what if i entered wrong sku then it will break whole operation & throw exception, so in this case we must have to depend on
productFactory
– Himanshu
Nov 5 '18 at 6:20
@Himanshu catch the exception. And if you need a fresh product instance in that case, you can still create it using the factory
– Fabian Schmengler
Nov 5 '18 at 17:00
@Himanshu catch the exception. And if you need a fresh product instance in that case, you can still create it using the factory
– Fabian Schmengler
Nov 5 '18 at 17:00
|
show 1 more comment
I like @phoenix128-riccardot 's answer, but would add an exception, just in case the product does not exist:
try {
$product = $this->productRepositoryInterface->get($sku);
} catch (MagentoFrameworkExceptionNoSuchEntityException $e){
// insert your error handling here
}
I was not able to add it as a comment (too low reputation), sorry.
add a comment |
I like @phoenix128-riccardot 's answer, but would add an exception, just in case the product does not exist:
try {
$product = $this->productRepositoryInterface->get($sku);
} catch (MagentoFrameworkExceptionNoSuchEntityException $e){
// insert your error handling here
}
I was not able to add it as a comment (too low reputation), sorry.
add a comment |
I like @phoenix128-riccardot 's answer, but would add an exception, just in case the product does not exist:
try {
$product = $this->productRepositoryInterface->get($sku);
} catch (MagentoFrameworkExceptionNoSuchEntityException $e){
// insert your error handling here
}
I was not able to add it as a comment (too low reputation), sorry.
I like @phoenix128-riccardot 's answer, but would add an exception, just in case the product does not exist:
try {
$product = $this->productRepositoryInterface->get($sku);
} catch (MagentoFrameworkExceptionNoSuchEntityException $e){
// insert your error handling here
}
I was not able to add it as a comment (too low reputation), sorry.
answered May 27 '18 at 21:58
wherewhere
410212
410212
add a comment |
add a comment |
Try this:
/** @var MagentoCatalogModelProductFactory $productFactory */
$product = $productFactory->create();
$product->loadByAttribute('sku', 'my sku');
// $product->load($product->getId()); // may need to do this too,
// see MagentoFrameworkApiAttributeValueFactoryAbstractModel::loadByAttribute
I need to get the product_id from sku (column of csv) during csv import and save only the product_id..How to achieve?
– Sushivam
Aug 25 '16 at 9:45
add a comment |
Try this:
/** @var MagentoCatalogModelProductFactory $productFactory */
$product = $productFactory->create();
$product->loadByAttribute('sku', 'my sku');
// $product->load($product->getId()); // may need to do this too,
// see MagentoFrameworkApiAttributeValueFactoryAbstractModel::loadByAttribute
I need to get the product_id from sku (column of csv) during csv import and save only the product_id..How to achieve?
– Sushivam
Aug 25 '16 at 9:45
add a comment |
Try this:
/** @var MagentoCatalogModelProductFactory $productFactory */
$product = $productFactory->create();
$product->loadByAttribute('sku', 'my sku');
// $product->load($product->getId()); // may need to do this too,
// see MagentoFrameworkApiAttributeValueFactoryAbstractModel::loadByAttribute
Try this:
/** @var MagentoCatalogModelProductFactory $productFactory */
$product = $productFactory->create();
$product->loadByAttribute('sku', 'my sku');
// $product->load($product->getId()); // may need to do this too,
// see MagentoFrameworkApiAttributeValueFactoryAbstractModel::loadByAttribute
answered Apr 17 '16 at 20:16
obscureobscure
2,0721431
2,0721431
I need to get the product_id from sku (column of csv) during csv import and save only the product_id..How to achieve?
– Sushivam
Aug 25 '16 at 9:45
add a comment |
I need to get the product_id from sku (column of csv) during csv import and save only the product_id..How to achieve?
– Sushivam
Aug 25 '16 at 9:45
I need to get the product_id from sku (column of csv) during csv import and save only the product_id..How to achieve?
– Sushivam
Aug 25 '16 at 9:45
I need to get the product_id from sku (column of csv) during csv import and save only the product_id..How to achieve?
– Sushivam
Aug 25 '16 at 9:45
add a comment |
You can try that
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$productRepository = $objectManager->get('MagentoCatalogModelProductRepository');
$productObj = $productRepository->get('<SKU>');
echo $productObj->getId();
add a comment |
You can try that
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$productRepository = $objectManager->get('MagentoCatalogModelProductRepository');
$productObj = $productRepository->get('<SKU>');
echo $productObj->getId();
add a comment |
You can try that
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$productRepository = $objectManager->get('MagentoCatalogModelProductRepository');
$productObj = $productRepository->get('<SKU>');
echo $productObj->getId();
You can try that
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$productRepository = $objectManager->get('MagentoCatalogModelProductRepository');
$productObj = $productRepository->get('<SKU>');
echo $productObj->getId();
answered Mar 2 '18 at 12:25
Nadeem0035Nadeem0035
563410
563410
add a comment |
add a comment |
Using Dependency Injection (DI)
Here is the example code to get the product information by product Id and SKU in Magento 2 using dependency injection.
In this, we might need to inject the object of the MagentoCatalogModelProductRepository class in the constructor of our module’s block class and access it from the view ( .phtml ) file.
Sample File Path: app/code/YourCompanyName/YourModuleName/Block/YourCustomBlock.php
<?php
namespace YourCompanyNameYourModuleNameBlock;
class YourCustomBlock extends MagentoFrameworkViewElementTemplate
{
protected $_productRepository;
public function __construct(
MagentoFrameworkViewElementTemplateContext $context,
MagentoCatalogModelProductRepository $productRepository,
array $data =
) {
$this->_productRepository = $productRepository;
parent::__construct($context, $data);
}
public function getProductById($id) {
return $this->_productRepository->getById($id);
}
public function getProductBySku($sku) {
return $this->_productRepository->get($sku);
}
}
Now, we can use the functions in our view (.phtml) file as follows.
// get product by id
$product = $block->getProductById(15);
// get product by sku
$product = $block->getProductBySku('MT12');
echo $product->getEntityId() . '<br>';
echo $product->getName() . '<br>';
echo $product->getSKU() . '<br>';
echo $product->getPrice() . '<br>';
echo $product->getSpecialPrice() . '<br>';
echo $product->getTypeId() . '<br>';
echo $product->getProductUrl() . '<br>';
Using Object Manager
Here is the example code to get the product information by product id and SKU in Magento 2 using object manager.
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$productRepository = $objectManager->get('MagentoCatalogModelProductRepository');
// get product by product id
$product = $productRepository->getById(15);
// get product by product sku
$product = $productRepository->get('MT12');
echo $product->getEntityId() . '<br>';
echo $product->getName() . '<br>';
echo $product->getSKU() . '<br>';
echo $product->getPrice() . '<br>';
echo $product->getSpecialPrice() . '<br>';
echo $product->getTypeId() . '<br>';
echo $product->getProductUrl() . '<br>';
add a comment |
Using Dependency Injection (DI)
Here is the example code to get the product information by product Id and SKU in Magento 2 using dependency injection.
In this, we might need to inject the object of the MagentoCatalogModelProductRepository class in the constructor of our module’s block class and access it from the view ( .phtml ) file.
Sample File Path: app/code/YourCompanyName/YourModuleName/Block/YourCustomBlock.php
<?php
namespace YourCompanyNameYourModuleNameBlock;
class YourCustomBlock extends MagentoFrameworkViewElementTemplate
{
protected $_productRepository;
public function __construct(
MagentoFrameworkViewElementTemplateContext $context,
MagentoCatalogModelProductRepository $productRepository,
array $data =
) {
$this->_productRepository = $productRepository;
parent::__construct($context, $data);
}
public function getProductById($id) {
return $this->_productRepository->getById($id);
}
public function getProductBySku($sku) {
return $this->_productRepository->get($sku);
}
}
Now, we can use the functions in our view (.phtml) file as follows.
// get product by id
$product = $block->getProductById(15);
// get product by sku
$product = $block->getProductBySku('MT12');
echo $product->getEntityId() . '<br>';
echo $product->getName() . '<br>';
echo $product->getSKU() . '<br>';
echo $product->getPrice() . '<br>';
echo $product->getSpecialPrice() . '<br>';
echo $product->getTypeId() . '<br>';
echo $product->getProductUrl() . '<br>';
Using Object Manager
Here is the example code to get the product information by product id and SKU in Magento 2 using object manager.
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$productRepository = $objectManager->get('MagentoCatalogModelProductRepository');
// get product by product id
$product = $productRepository->getById(15);
// get product by product sku
$product = $productRepository->get('MT12');
echo $product->getEntityId() . '<br>';
echo $product->getName() . '<br>';
echo $product->getSKU() . '<br>';
echo $product->getPrice() . '<br>';
echo $product->getSpecialPrice() . '<br>';
echo $product->getTypeId() . '<br>';
echo $product->getProductUrl() . '<br>';
add a comment |
Using Dependency Injection (DI)
Here is the example code to get the product information by product Id and SKU in Magento 2 using dependency injection.
In this, we might need to inject the object of the MagentoCatalogModelProductRepository class in the constructor of our module’s block class and access it from the view ( .phtml ) file.
Sample File Path: app/code/YourCompanyName/YourModuleName/Block/YourCustomBlock.php
<?php
namespace YourCompanyNameYourModuleNameBlock;
class YourCustomBlock extends MagentoFrameworkViewElementTemplate
{
protected $_productRepository;
public function __construct(
MagentoFrameworkViewElementTemplateContext $context,
MagentoCatalogModelProductRepository $productRepository,
array $data =
) {
$this->_productRepository = $productRepository;
parent::__construct($context, $data);
}
public function getProductById($id) {
return $this->_productRepository->getById($id);
}
public function getProductBySku($sku) {
return $this->_productRepository->get($sku);
}
}
Now, we can use the functions in our view (.phtml) file as follows.
// get product by id
$product = $block->getProductById(15);
// get product by sku
$product = $block->getProductBySku('MT12');
echo $product->getEntityId() . '<br>';
echo $product->getName() . '<br>';
echo $product->getSKU() . '<br>';
echo $product->getPrice() . '<br>';
echo $product->getSpecialPrice() . '<br>';
echo $product->getTypeId() . '<br>';
echo $product->getProductUrl() . '<br>';
Using Object Manager
Here is the example code to get the product information by product id and SKU in Magento 2 using object manager.
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$productRepository = $objectManager->get('MagentoCatalogModelProductRepository');
// get product by product id
$product = $productRepository->getById(15);
// get product by product sku
$product = $productRepository->get('MT12');
echo $product->getEntityId() . '<br>';
echo $product->getName() . '<br>';
echo $product->getSKU() . '<br>';
echo $product->getPrice() . '<br>';
echo $product->getSpecialPrice() . '<br>';
echo $product->getTypeId() . '<br>';
echo $product->getProductUrl() . '<br>';
Using Dependency Injection (DI)
Here is the example code to get the product information by product Id and SKU in Magento 2 using dependency injection.
In this, we might need to inject the object of the MagentoCatalogModelProductRepository class in the constructor of our module’s block class and access it from the view ( .phtml ) file.
Sample File Path: app/code/YourCompanyName/YourModuleName/Block/YourCustomBlock.php
<?php
namespace YourCompanyNameYourModuleNameBlock;
class YourCustomBlock extends MagentoFrameworkViewElementTemplate
{
protected $_productRepository;
public function __construct(
MagentoFrameworkViewElementTemplateContext $context,
MagentoCatalogModelProductRepository $productRepository,
array $data =
) {
$this->_productRepository = $productRepository;
parent::__construct($context, $data);
}
public function getProductById($id) {
return $this->_productRepository->getById($id);
}
public function getProductBySku($sku) {
return $this->_productRepository->get($sku);
}
}
Now, we can use the functions in our view (.phtml) file as follows.
// get product by id
$product = $block->getProductById(15);
// get product by sku
$product = $block->getProductBySku('MT12');
echo $product->getEntityId() . '<br>';
echo $product->getName() . '<br>';
echo $product->getSKU() . '<br>';
echo $product->getPrice() . '<br>';
echo $product->getSpecialPrice() . '<br>';
echo $product->getTypeId() . '<br>';
echo $product->getProductUrl() . '<br>';
Using Object Manager
Here is the example code to get the product information by product id and SKU in Magento 2 using object manager.
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$productRepository = $objectManager->get('MagentoCatalogModelProductRepository');
// get product by product id
$product = $productRepository->getById(15);
// get product by product sku
$product = $productRepository->get('MT12');
echo $product->getEntityId() . '<br>';
echo $product->getName() . '<br>';
echo $product->getSKU() . '<br>';
echo $product->getPrice() . '<br>';
echo $product->getSpecialPrice() . '<br>';
echo $product->getTypeId() . '<br>';
echo $product->getProductUrl() . '<br>';
answered 20 mins ago
Amir HosseinzadehAmir Hosseinzadeh
1013
1013
add a comment |
add a comment |
<?php
use MagentoFrameworkAppBootstrap;
require __DIR__ . '/app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$obj = $bootstrap->getObjectManager();
$state = $obj->get('MagentoFrameworkAppState');
$state->setAreaCode('frontend');
$sku ='24-MB01';
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$productObject = $objectManager->get('MagentoCatalogModelProduct');
$product = $productObject->loadByAttribute('sku', $sku);
echo $product->getName();
?>
add a comment |
<?php
use MagentoFrameworkAppBootstrap;
require __DIR__ . '/app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$obj = $bootstrap->getObjectManager();
$state = $obj->get('MagentoFrameworkAppState');
$state->setAreaCode('frontend');
$sku ='24-MB01';
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$productObject = $objectManager->get('MagentoCatalogModelProduct');
$product = $productObject->loadByAttribute('sku', $sku);
echo $product->getName();
?>
add a comment |
<?php
use MagentoFrameworkAppBootstrap;
require __DIR__ . '/app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$obj = $bootstrap->getObjectManager();
$state = $obj->get('MagentoFrameworkAppState');
$state->setAreaCode('frontend');
$sku ='24-MB01';
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$productObject = $objectManager->get('MagentoCatalogModelProduct');
$product = $productObject->loadByAttribute('sku', $sku);
echo $product->getName();
?>
<?php
use MagentoFrameworkAppBootstrap;
require __DIR__ . '/app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$obj = $bootstrap->getObjectManager();
$state = $obj->get('MagentoFrameworkAppState');
$state->setAreaCode('frontend');
$sku ='24-MB01';
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$productObject = $objectManager->get('MagentoCatalogModelProduct');
$product = $productObject->loadByAttribute('sku', $sku);
echo $product->getName();
?>
answered Jul 28 '17 at 5:44
Nagaraju KasaNagaraju Kasa
2,63721539
2,63721539
add a comment |
add a comment |
Thanks for contributing an answer to Magento Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f111245%2fhow-to-load-product-by-sku-in-magento-2%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown