Magento CE 1.7.0.2
Magento offers an excellent store view selector which is easy to hook into for custom module development. I wrote an article on that over here.
However, today I needed to add a store view selector to a custom script for Magento that interfaces with the store database. Don’t ask. So I wrote a little function to easily build a store view selector for your own custom module. There’s probably a built-in method for this; please let me know if you find it!
First, get the store data array from Mage. There’s a few ways to set this up, here’s a quick n dirty:
1 2 3 4 5 6 | require_once('app/Mage.php'); umask(0); Mage::app(); // get stores $_stores = Mage::getSingleton('adminhtml/system_store')->getStoreValuesForForm(false, true); |
The function that builds the HTML for us: (note that I am pre-selecting the store view with id 8. You will probably want to remove this, or customise it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | function getAllStoreViews($storesArray, $fieldId, $fieldName = 'stores[]', $fieldClass){ $html = '<select name="' . $fieldName . '" id="' . $fieldId . '" class="' . $fieldClass . '">'; foreach ($storesArray as $siteId => $site){ $html .= '<optgroup label=" ' .$site["label"] . '">'; if (is_array($site["value"])) { foreach ($site["value"] as $view){ $html .= '<option value="' . $view["value"] . '" ' . ($view["value"] == "8" ? " selected="selected"" : "") . '>' . $view['label'] . '</option>'; } } else { $html .= '<option value="' . $site["value"] . '">' . $site['label'] . '</option>'; } $html .= '</optgroup>'; } $html .= '</select>'; return $html; } |
Now we have everything we need to build our form element with a single call. I’ve added simple parameters to pass in a custom name for our field, as well as optional id and class attributes. We call our function like this:
1 2 3 4 |
That’s all there is to it. Enjoy 🙂