Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the default Store code within the Magento backend

Tags:

php

magento

I am trying to find out the default store code from within Magento's backend. While this sounds rather simple, I just couldn't find any solution.

The snippets I found are either

Mage::app()->getStore()->getCode()

(although this doesn't correspond to the default but the current store) or

Mage::app()->getStore(Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID)->getCode();

But from within the backend these will only return "admin" (since the backend is treated as some kind of special store with store ID 0 - which is the value of DEFAULT_STORE_ID). Could anyone please point me to a way to get the actual default store code from anywhere? (That store code that is set by Magento if both "Add Store Code to URLs" and "Auto-redirect to Base URL" options are activated)

Just a little background why I need this: I need to generate a URL within the Magento configuration that still works if "Add Store Code to URLs" is activated. I can set any store code, so if I'm within the configuration scope of one of them, I can just use that one. But since it also has to work if the configuration scope is set to default or website, I want to use the default store code in that case.

I found a solution with:

$websites = Mage::app()->getWebsites();
$code = $websites[1]->getDefaultStore()->getCode();

However, this leaves me with some follow-up questions.

Why does Mage::app()->getWebsite() return a special website object that only includes the special admin store, while Mage::app()->getWebsites() will return an array that only includes the usual frontend website, but not the object returned by getWebsite()?

Why does the frontend website object occupy index 1 in the array, while index 0 is unused? I would really like to know the reason for having to use a magic number there (if I have to).

like image 583
Martin Ender Avatar asked Aug 29 '12 12:08

Martin Ender


1 Answers

There is no such thing as a default store in Magento. The only special store is the admin one; all other stores have the same rights in Magento.

[...] while Mage::app()->getWebsites() will return an array that only includes the usual frontend website, but not the object returned by getWebsite()?

You should look at Mage_Core_Model_App::getWebsites()'s source code:

public function getWebsites($withDefault = false, $codeKey = false)
{
    $websites = array();
    if (is_array($this->_websites)) {
        foreach ($this->_websites as $website) {
            if (!$withDefault && $website->getId() == 0) {
                continue;
            }
            //...
        }
    }

    return $websites;
}

If you call $websites = Mage::app()->getWebsites(true);, you will get an array of websites, with the admin one at index 0.

like image 135
Dmytro Zavalkin Avatar answered Sep 27 '22 22:09

Dmytro Zavalkin