Skip to content

Instantly share code, notes, and snippets.

@Invis1ble
Forked from mylk/TimezoneType.php
Last active March 25, 2017 21:47
Show Gist options
  • Save Invis1ble/837045e324f2cbb44adb40f68ee02975 to your computer and use it in GitHub Desktop.
Save Invis1ble/837045e324f2cbb44adb40f68ee02975 to your computer and use it in GitHub Desktop.
A modified Symfony Forms "timezone" type that also displays the timezone offset
<?php
/**
* A modified version of the original symfony form type that adds the timezone offset.
*
* Original version at:
* https://github.com/symfony/symfony/blob/2.7/src/Symfony/Component/Form/Extension/Core/Type/TimezoneType.php
*/
/*
* Installation:
* =============
* # services.yml
* services:
* # ...
* acme.form.timezone_with_offset:
* class: Acme\AcmeBundle\Form\Extension\TimezoneWithOffsetType
* tags:
* - { name: form.type, alias: acme.form.timezone_with_offset }
*
* Usage:
* ======
* $builder
* ->add("timezone", \Acme\AcmeBundle\Form\Extension\TimezoneWithOffsetType::class)
* // ...
*/
namespace Acme\AcmeBundle\Form\Extension;
use Symfony\Component\Form\ChoiceList\ArrayChoiceList;
use Symfony\Component\Form\Extension\Core\Type\TimezoneType;
/**
* Class TimezoneWithOffsetType
*/
class TimezoneWithOffsetType extends TimezoneType
{
/**
* Timezone loaded choice list.
*
* The choices are generated from the ICU function \DateTimeZone::listIdentifiers().
*
* @var ArrayChoiceList
*/
private $choiceList;
/**
* {@inheritdoc}
*/
public function loadChoiceList($value = null)
{
if (null !== $this->choiceList) {
return $this->choiceList;
}
return $this->choiceList = new ArrayChoiceList($this->getTimezones(), $value);
}
/**
* Returns a normalized array of timezone choices.
*
* @return array The timezone choices
*/
private static function getTimezones()
{
$timezones = array();
foreach (\DateTimeZone::listIdentifiers() as $timezone) {
$parts = explode('/', $timezone);
if (count($parts) > 2) {
$region = $parts[0];
$name = $parts[1].' - '.$parts[2];
} elseif (count($parts) > 1) {
$region = $parts[0];
$name = $parts[1];
} else {
$region = 'Other';
$name = $parts[0];
}
$dateTime = new \DateTime('now', new \DateTimeZone($timezone));
$timezones[$region][str_replace('_', ' ', $name) . ' (GMT ' . $dateTime->format('P') . ')'] = $timezone;
}
return $timezones;
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return 'timezone_with_offset';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment