Magento 2 supports multiple store views and the admin can manage the features and functionalities based on store views. It can be even easier with the below method to add store view control in admin form in Magento 2.
For example, if you have multiple store views based on the locations or languages. Now, a customer has added an FAQ or your developer has implemented a location-based feature. Such things need to be enabled only for a specific store view.
In such a scenario, you can add store view control in Magento 2 admin form as shown here:
You can even enable a custom extension for a particular store view only with the below method:
Steps to Add Store View Control in Admin Form in Magento 2:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
|
<?php
namespace Vendor\Extension\Block\Adminhtml\Questions\Edit\Tab;
use Magento\Backend\Block\Store\Switcher\Form\Renderer\Fieldset\Element;
use Magento\Backend\Block\Template\Context;
use Magento\Backend\Block\Widget\Form\Generic;
use Magento\Framework\Data\FormFactory;
use Magento\Framework\Registry;
use Magento\Store\Model\System\Store;
class Questions extends Generic
{
protected $systemStore;
public function __construct(
Store $systemStore,
Context $context,
Registry $registry,
FormFactory $formFactory,
array $data = []
) {
parent::__construct($context, $registry, $formFactory, $data);
$this->systemStore = $systemStore;
}
protected function _prepareForm()
{
$model = $this->_coreRegistry->registry(‘row_data’);
$form = $this->_formFactory->create();
$fieldset = $form->addFieldset(
‘field_set_id’,
[‘legend’ => __(‘form title’)]
);
$field = $fieldset->addField(
‘store_id’,
‘select’,
[
‘label’ => __(‘Store View’),
‘title’ => __(‘Store View’),
‘name’ => ‘store_id’,
‘value’ => $model->getStoreId(),
‘values’ => $this->systemStore->getStoreValuesForForm(false, true)
// set first argument true and second to false to add blank option which value is blank
// set second argument true to add “All Store Views” option which value is 0
]
);
$renderer = $this->getLayout()->createBlock(
Element::class
);
$field->setRenderer($renderer);
$form->setValues($model->getData());
$this->setForm($form);
return parent::_prepareForm();
}
}
|
That’s it to control the features and functions of the Magento 2 store based on the store view.
Any doubts about the solution? Feel free to mention them in the Comments section below. I’d be glad to help.
Also, do not forget to share this method with Magento 2 store admins via social media who are managing multiple store views.
Thank you.