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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…