Symfony2 Date and time display with time zone in forms

On my system, database timestamps are written as UTC values.

Each user has a time zone recorded in their profile. Upon entering the system, the time zone value is transferred from your profile to their session ($ session-> set ('timezone', $ tz);).

Most of my codes use the Sonata INTL package, so users see the date and time values ​​displayed correctly for their time zone, except in the form fields.

I recently discovered the model_timezone and view_timezone fields on some types of Symfony2. I can make the fields show the correct values ​​(as shown in the code snippets below), however I would like to understand how can I populate view_timezone from a user session? (I assume I can somehow pass $ options?)

Check box Event controller:

$object = <object loaded>; $form = $this->createForm(new MyEventType(), $object); 

fragment of MyEventType form:

 public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('id', null, array( 'label' => 'Event ID', )); $builder->add('changed', 'datetime', array( 'date_widget' => 'single_text', 'date_format' => \IntlDateFormatter::SHORT, 'time_widget' => 'single_text', 'model_timezone' => 'UTC', 'view_timezone' => 'Pacific/Auckland', )); 
+4
source share
1 answer

The solution to this problem is twofold:

  • Pass an array of createForm methods containing your value for 'view_timezone'
  • Make sure that "view_timezone" is defined in the default settings of the form.

I updated my code snippets to reflect the necessary changes:

Check box Event controller:

 $object = <object loaded>; $form = $this->createForm(new MyEventType(), $object, array( 'view_timezone' => $this->container->get('session')->get('timezone')) ); 

fragment of MyEventType form:

 public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('id', null, array( 'label' => 'Event ID', )); $builder->add('changed', 'datetime', array( 'date_widget' => 'single_text', 'date_format' => \IntlDateFormatter::SHORT, 'time_widget' => 'single_text', 'model_timezone' => 'UTC', 'view_timezone' => $options['view_timezone'], )); ... public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'Stuff\CoreBundle\Entity\MyEvent', 'view_timezone' => 'UTC', )); } 
+5
source

All Articles