Search code examples
phpsymfonydatetimemodel-view-controllerutc

Symfony buildForm convert datetime to local and back to utc


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.

In the ControllerAction where I invoke the formBuilder?

In the formBuilder?

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

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

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?


Solution

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

    Please see:

    Model timezone: http://symfony.com/doc/current/reference/forms/types/date.html#model-timezone

    View timezone: http://symfony.com/doc/current/reference/forms/types/date.html#view-timezone

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

    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 :)