-
-
Save Invis1ble/837045e324f2cbb44adb40f68ee02975 to your computer and use it in GitHub Desktop.
A modified Symfony Forms "timezone" type that also displays the timezone offset
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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