Last active
November 9, 2018 18:04
-
-
Save mylk/9ec40c49e88d6251e41c26c2c732e704 to your computer and use it in GitHub Desktop.
A modified Symfony Forms "timezone" type that also displays the timezone offset
This file contains hidden or 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: | |
* class: Acme\AcmeBundle\Form\Extension\TimezoneType | |
* tags: | |
* - { name: form.type, alias: acme.form.timezone } | |
* | |
* Usage: | |
* ====== | |
* $builder | |
* ->add("timezone", "acme.form.timezone") | |
* // ... | |
*/ | |
namespace Acme\AcmeBundle\Form\Extension; | |
use Symfony\Component\Form\AbstractType; | |
use Symfony\Component\OptionsResolver\OptionsResolver; | |
class TimezoneType extends AbstractType | |
{ | |
/** | |
* Stores the available timezone choices | |
* @var array | |
*/ | |
private static $timezones; | |
/** | |
* {@inheritdoc} | |
*/ | |
public function configureOptions(OptionsResolver $resolver) | |
{ | |
$resolver->setDefaults(array( | |
"choices" => self::getTimezones(), | |
"choices_as_values" => true | |
)); | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function getParent() | |
{ | |
return "choice"; | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function getName() | |
{ | |
return "acme.form.timezone"; | |
} | |
/** | |
* Returns the timezone choices. | |
* | |
* The choices are generated from the ICU function | |
* \DateTimeZone::listIdentifiers(). They are cached during a single request, | |
* so multiple timezone fields on the same page don"t lead to unnecessary | |
* overhead. | |
* | |
* @return array The timezone choices | |
*/ | |
public static function getTimezones() | |
{ | |
if (null === static::$timezones) { | |
static::$timezones = array(); | |
foreach (\DateTimeZone::listIdentifiers() as $timezone) { | |
$parts = \explode("/", $timezone); | |
$dateTimeZone = new \DateTimeZone($timezone); | |
$dateTime = new \DateTime("now", $dateTimeZone); | |
$offset = "GMT " . $dateTime->format("P"); | |
if (\count($parts) > 1) { | |
$name = \sprintf("%s (%s)", $timezone, $offset); | |
} else { | |
$name = \sprintf("%s (%s)", "Other", $offset); | |
} | |
static::$timezones[\str_replace("_", " ", $name)] = $timezone; | |
} | |
} | |
return static::$timezones; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment