【问题标题】:Symfony TimezoneType FormSymfony 时区类型表单
【发布时间】:2018-07-09 03:06:41
【问题描述】:

在我的 symfony 3 应用程序中,用户可以在表单中选择他们的时区。

所以我把它放在我的表格中:

    $builder
    ->add('timezone', TimezoneType::class)

它正在工作,但我想个性化用户可以在列表中选择的内容。 实际上,我按大陆看到了所有国家。列表太大,城市太多。

我想要一个只有主要城市的较短列表,并将 UTC 放在每个城市之前。 类似于 Twitter。

例子:

  • (UTC) 伦敦
  • (UTC+01:00) 巴黎
  • (UTC+02:00) 雅典
  • (UTC+03:00) 莫斯科
  • 等等……

有人可以帮助我吗?

谢谢

【问题讨论】:

  • 您可能必须使用ChoiceType 并制作您自己的列表。来自文档:You can specify the option manually, but then you should just use the ChoiceType directly.symfony.com/doc/current/reference/forms/types/timezone.html
  • 你需要一个例子吗?我已经看到你过去对ChoiceType 有问题,如果你仍然这样做,我可以举个例子。一旦你知道怎么做就很容易了。
  • 不,没关系,我在想时区有一个选项可以直接通过制作选择类型手册来获得不同的列表

标签: php forms symfony time timezone


【解决方案1】:

正如您在 Timezone Type 中看到的,Symfony 以这种方式获取时区:

private static function getFlippedTimezones()
{
    if (null === self::$timezones) {
        self::$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];
            }

            self::$timezones[$region][str_replace('_', ' ', $name)] = $timezone;
        }
    }

    return self::$timezones;
}

您可以创建自己的类型或在表单中使用它,例如

 $choices = self::getCustomFlippedTimezones();
 $builder
        ->add('timeZone', ChoiceType::class, array(
                'choices' => $choices
            ))

为了可重用性:

// src/AppBundle/Form/Type/CustomTimeZoneType.php
namespace AppBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;

class CustomTimeZoneType extends AbstractType
{
    private static function getFlippedTimezones() { /*[...]*/}

    public function configureOptions(OptionsResolver $resolver)
    {

        $resolver->setDefaults(array(
            'choices' => self::getCustomFlippedTimezones(),
            'choices_as_values' => true,
        ));
    }

    public function getParent()
    {
        return ChoiceType::class;
    }
}

【讨论】:

  • 嘿,太好了,我需要在哪里创建 getCustomFlippedTimezones() 函数?在我的实体文件中?或者我需要直接从供应商那里更改时区存储库?
  • 因为我想以其他形式使用此功能。
  • 为了可重用性,您必须创建自己的 formType。很简单,不用担心:symfony.com/doc/current/form/create_custom_field_type.html 永远不要更改供应商目录中的任何东西,你会在以后付出代价;)
猜你喜欢
  • 1970-01-01
  • 2016-06-26
  • 2013-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-07
相关资源
最近更新 更多