2016-04-14 62 views
0

所以我想顯示選項以在當地時間爲活動設置一個日期,但將其另存爲UTC作爲symfony標準。我有5個不同的用戶分段和5個不同的時區值。用戶可以在表單中設置新的活動。每個用戶實體都有自己的時區設置。我的問題是我在哪裏設置轉換?我有用戶實體處於登錄用戶會話狀態。Symfony buildForm將datetime轉換爲本地並返回utc

在我調用formBuilder的ControllerAction中?

在formBuilder中?

formbuilder對我來說還是有些模糊,我知道里面有很多東西在發生。

的formBuilder,簡化:

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:

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); 
} 

因此,我相信,我剛纔已經回答我自己的問題,這迫使我問;這是常規/最佳實踐如何做到這一點?

回答

0

你太過於複雜了。 Symfony2形式已經很好地涵蓋了這一點。

請參閱:

型號時區: http://symfony.com/doc/current/reference/forms/types/date.html#model-timezone

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

正確地使用這些解決您的問題,而不需要的任何額外的代碼。

您可以將您的用戶羣(或任何您用來推斷哪個是正確時區的數據)插入到表單中,並使用該用戶羣的時區在日期字段上設置view_timezone。無論如何,沿着這些線:)

+0

謝謝!我拉着頭髮,直到我注意到我的開發機器在UTC的CEST和生產服務器上。但是這個伎倆! – Conjak

相關問題