How to add custom module dropdown in magento 2 luma theme top bar
-
07-02-2021 - |
Question
I want to add a dropdown(i.e select) in the top bar(which contains the welcome message) of magento 2 luma theme as the last item of it or any other theme that contains this block. This dropdown will be of my custom module. What I have tried till now is:
Setup a new module, which is working file.
Created these files and cleared the cache.
Magento mode is set to developer.
Vendor/ModuleName/view/frontend/layout/default.xml
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="3columns" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="top.links">
<block class="Vendor\ModuleName\Block\Html\Dropdown" name="some_name" template="Vendor_ModuleName::html/dropdown.phtml" after="-"/>
</referenceContainer>
</body>
Vendor/ModuleName/view/frontend/template/html/dropdown.phtml
<select>
<?php echo $block->getOptionsHtml(); ?>
</select>
Vendor/ModuleName/Block/Html/Dropdown.phtml
class Dropdown extends Template
{
private $options = [
['value' => 'some value 1', 'selected' => 1],
['value' => 'some value 2', 'selected' => 0],
['value' => 'some value 3', 'selected' => 0]
];
/**
* Dropdown constructor.
*
* @param TemplateContext $context
* @param array $data
*/
public function __construct(TemplateContext $context, array $data = [])
{
parent::__construct($context, $data);
}
public function getOptionsHtml()
{
$optionHtml = '';
foreach ($this->options as $option) {
$optionHtml .= '<option value="' . $option["value"] . '" ' . ($option["selected"] ? "selected" : "") . '>' . $option . '</option>';
}
return $optionHtml;
}
}
Solution
I have found some changes for you:
referenceContainer
to become referenceBlock
and top.links
to be header.links
Now, once you have done all these changes, you will see some minor issues in your block:
below is a code working for me:
class Dropdown extends Template
{
private $options = [
['value' => 'some value 1', 'label' => 'Some Laberl 1', 'selected' => 1],
['value' => 'some value 2', 'label' => 'Some Laberl 2', 'selected' => 0],
['value' => 'some value 3', 'label' => 'Some Laberl 3', 'selected' => 0]
];
public function getOptionsHtml()
{
$optionHtml = '';
foreach ($this->options as $option) {
$optionHtml .= '<option value="' . $option["value"] . '" ' . ($option["selected"] ? "selected" : "") . '>' . $option['label'] . '</option>';
}
return $optionHtml;
}
}
the outcome here is that your dropdown cannot be ordered like most blocks: because top.links, header.links are all having a block that implements \Magento\Framework\View\Element\Html\Links adn that means the children are meant to be li html element.
now, you also may want to use <referenceBlock name="header.panel">
, with this layout selector, the select appears exactly like you describe. good luck