Timezone and locale dropdown in custom form frontend
-
15-04-2021 - |
Soluzione
You can get your result by following code:
<?php $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); ?>
<?php $localeLists = $objectManager->create('Magento\Framework\Locale\ListsInterface'); ?>
<?php $timezones = $localeLists->getOptionTimezones(); ?>
<?php $locales = $localeLists->getOptionLocales(); ?>
<?php if(count($timezones) > 0): ?>
<label><?= __('Timezone') ?></label>
<select name="timezone" id="timezone">
<?php foreach($timezones as $timezone): ?>
<option value="<?= $timezone['value'] ?>"><?= $timezone['label'] ?></option>
<?php endforeach; ?>
</select>
<?php endif; ?>
<?php if(count($locales) > 0): ?>
<label><?= __('Locale') ?></label>
<select name="locale" id="locale">
<?php foreach($locales as $locale): ?>
<option value="<?= $locale['value'] ?>"><?= $locale['label'] ?></option>
<?php endforeach; ?>
</select>
<?php endif; ?>
Don't use objectmanager in your phtml file. Inject the ListsInterface class to your block construct method like below code:
public function __construct(
...
\Magento\Framework\Locale\ListsInterface $localeLists,
...
) {
...
$this->localeLists = $localeLists;
...
}
public function getTimezones()
{
return $this->localeLists->getOptionTimezones();
}
public function getLocales()
{
return $this->localeLists->getOptionLocales();
}
Now call it in phtml like below:
<?php $timezones = $block->getTimezones(); ?>
<?php $locales = $block->getLocales(); ?>
<?php if(count($timezones) > 0): ?>
<label><?= __('Timezone') ?></label>
<select name="timezone" id="timezone">
<?php foreach($timezones as $timezone): ?>
<option value="<?= $timezone['value'] ?>"><?= $timezone['label'] ?></option>
<?php endforeach; ?>
</select>
<?php endif; ?>
<?php if(count($locales) > 0): ?>
<label><?= __('Locale') ?></label>
<select name="locale" id="locale">
<?php foreach($locales as $locale): ?>
<option value="<?= $locale['value'] ?>"><?= $locale['label'] ?></option>
<?php endforeach; ?>
</select>
<?php endif; ?>
Hope this helps!
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a magento.stackexchange