Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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:
* 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