Symfony buildForm将日期时间转换为本地并返回utc [英] Symfony buildForm convert datetime to local and back to utc

查看:57
本文介绍了Symfony buildForm将日期时间转换为本地并返回utc的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我想显示一些选项以设置活动在本地时间的日期,但将其保存为UTC作为symfony的标准.我有5个不同的用户细分,其中有5个不同的时区值.用户可以在表单中设置新活动.每个用户实体都有自己的时区设置.我的问题是在哪里设置转换?我的用户实体处于登录的用户会话状态.

So I want to show options to set a date for an activity in local time but save it in UTC as symfony standard. I have 5 different User segments with 5 different Timezones values. A user can set a new activity in a form. Each user entity has it's own timezone set. My question is where do I set the conversion? I have the user entity in a logged in user session state.

在ControllerAction中我调用formBuilder的地方吗?

In the ControllerAction where I invoke the formBuilder?

在formBuilder中?

In the formBuilder?

对于我来说,formbuilder还是有点模糊,我知道其中有很多事情发生.

The formbuilder is still a little fuzzy for me and I know there's alot happening in it.

formBuilder,简化了:

The formBuilder, simplified:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    //...
    $builder->add('name');
    $builder->add('startDate', DateTimeType::class, array(
        'widget' => 'single_text',
        'format' => 'yyyy-MM-dd HH:mm',
        )
    );
    $builder->add('endDate', DateTimeType::class, array(
        'widget' => 'single_text',
        'format' => 'yyyy-MM-dd HH:mm',
        )
    );

    //...

    $builder->add('submit', SubmitType::class, array('attr' => array('class' => 'button')));
}

ControllerAction:

The ControllerAction:

public function activityAction(Request $request, Activity $activity){
    $variables = array();
    /**
    * TODO Determine User Local timezone and store as UTC
    *
    */

    $user = $this->get('security.token_storage')->getToken()->getUser();
    $timezone = $user->getTimezone();

    $activity = new Activity();

    $form = $this->createForm(ActivityType::class, $activity);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {

        $activity->setName($form->get('name')->getData());

        /**
        *
        * Maybe here, (I've just realized)
        * Because earlier, the form just handled the datetime without conversion
        * And just stored them in the DB as they where
        *
        */

        // Example: $timezone = 'Europe/London';
        $date = new DateTime();
        $date->setTimestamp( $form->get('startDate')->getData() );
        $date->setTimezone(new DateTimeZone($timezone));   
        $activity->setStartDate($date->format("Y-m-d H:i:s"));

        $date = new DateTime();
        $date->setTimestamp( $form->get('endDate')->getData() );
        $date->setTimezone(new DateTimeZone($timezone));   
        $activity->setEndDate($date->format("Y-m-d H:i:s"));


        $em = $this->getDoctrine()->getManager();
        $em->persist($activity);
        $em->flush();
    }
    elseif ($form->isSubmitted() && !$form->isValid() ) {
        $variables['message'] = 'Something went wrong!';

    }

    $variables["title"] = "Create Activty";
    $variables["form"] = $form->createView();
    return $this->render('AcmeBundle:SomeViews:activity.html.twig', $variables);
}

所以我相信,我已经回答了我自己的问题,这迫使我问.这是惯例/最佳实践吗?

So I believe, I've just answered my own question, which forces me to ask; Is this the convention/best practice how you do it?

推荐答案

您为此过于复杂了.Symfony2表单已经很好地涵盖了这一点.

You're overcomplicating this. Symfony2 forms already covers this nicely.

请参阅:

模型时区: http://symfony.com/doc/current/reference/forms/types/date.html#model-timezone

查看时区: http://symfony.com/doc/current/reference/forms/types/date.html#view-timezone

正确使用这些可以解决您的问题,而无需任何其他代码.

Used correctly these solve your issue without any extra code needed.

您可以将用户细分(或用于推断正确时区的任何数据)注入表单中,并使用该用户细分中的时区在日期字段中设置view_timezone.无论如何,沿着这些路线:)

You could inject your user segment (or whatever data you use to deduce which is the correct time zone) into your form and use the timezone on that user segment to set view_timezone on your date field. Something along those lines anyway :)

这篇关于Symfony buildForm将日期时间转换为本地并返回utc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆