0

I have to check which is the current store view. In order to do that I was using the Object Manager to get the store code like this:

$storeCode = \Magento\Framework\App\ObjectManager::getInstance()
    ->get(\Magento\Store\Model\StoreManagerInterface::class)
    ->getStore()
    ->getCode();

if ($storeCode === "en") {
   ...
};
if ($storeCode === "it") {
   ...
};

but doing this way in no more recommended, instead I should use the dependency injection technique...

how should I use it?

7
  • where you added above code ?
    – Pawan
    Oct 9, 2020 at 16:01
  • @Pawan I added it on my theme template file app/design/frontend/MyTheme/MyDefault/Magento_Catalog/templates/my-template.phtml
    – KaMZaTa
    Oct 9, 2020 at 16:08
  • please have a look at github.com/pawankparmar/Siteinfo/blob/master/Vendor/Siteinfo/…
    – Pawan
    Oct 9, 2020 at 16:15
  • you can use same block class and get $block->getStoreCode(); in your phtml file
    – Pawan
    Oct 9, 2020 at 16:20
  • Thanks but I cannot understand how I can use it inside the theme. I just added Block/Siteinfo.php and correct accordingly the namespace path. Then in my template file Magento_Theme/templates/my-template.phtml I added echo $block->getStoreCode(); but it didn't work.
    – KaMZaTa
    Oct 9, 2020 at 16:43

1 Answer 1

0

In your block file constructor, add StoreManager dependency like shown in code below :

 public function __construct(
        \Magento\Framework\Model\Context $context,
        \Magento\Framework\Registry $registry,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        array $data = []
    ) {
            
        $this->storeManager = $storeManager;      
        parent::__construct($context, $registry, $data);
    }

Then you can get any value related to store like this:

$currentStoreId = $this->storeManager->getStore()->getId();

I think in place of getId() you can write getCode(). Happy Coding.

2
  • Can I also get the current product?
    – KaMZaTa
    Oct 12, 2020 at 12:15
  • That's another question pls open a new thread. and if my answer helped you pls accept it as a solution. thanks. Oct 13, 2020 at 5:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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