我正在使用表列來存儲Unix datetime格式(基本上是一個長度爲11的整數)的「date_of_creation」(或created_at)。在Symfony中轉換表單字段值
在此期間,我想在創建/編輯webform(引導日期選擇器)中用DateTime格式「d-m-Y」處理此值。
這裏的問題:
什麼轉換和堅持DateTime格式傳遞其能接收的整數和,反之亦然表列中的值,覆蓋表單字段默認值的最佳方法「時間戳格式」及其相應的日期時間格式(使其可被DatePicker識別)?
我正在使用Symfony 3.3.5和Twig。
下面是一個例子:我使用了一個解決方法,以達到範圍
,但我不是100%肯定這是一個很好的做法...
的FormType.php添加一個文本字段與類掛鉤的DatePicker控件:
->add('createdAt', TextType::class, [
'attr' => [
'class' => 'js-datepicker'
],
])
實體二傳手看起來像這樣:
/**
* @param mixed $createdAt
*/
public function setCreatedAt($createdAt, $stringToTime = true)
{
$this->createdAt = ($stringToTime) ? strtotime($createdAt) : $createdAt;
}
這裏真正的技巧是額外的$ stringToTime參數。
最後的controllerAction:
/**
* @Route("/content/edit/{id}", name="admin_content_edit")
*/
public function editContentAction(Request $request, Content $content)
{
$date = new \DateTime();
$date->setTimestamp($content->getCreatedAt());
$content->setCreatedAt($date->format('d-m-Y'), false);
$form = $this->createForm(ContentType::class, $content);
$form->handleRequest($request);
if ($form->isSubmitted()){
if ($form->isValid()) {
$content = $form->getData();
$em = $this->getDoctrine()->getManager();
$em->persist($content);
$em->flush();
$this->addFlash('success', 'Content updated');
return $this->redirectToRoute('admin_content_show');
}
}
return $this->render('RootgearBundle:Default:editContent.html.twig', array(
'contentForm' => $form->createView()
));
}
的關鍵部分是這樣的:
$date = new \DateTime();
$date->setTimestamp($content->getCreatedAt());
$content->setCreatedAt($date->format('d-m-Y'), false);
這是我做了什麼,它就像一個魅力。 但我不知道這是正確的方法還是有更好的解決方案。
預先感謝更多的則致歡迎辭:)
=============新的解決方案基於建議下阿蘭Tiembolo
閱讀有關數據位後的文檔變壓器我終於想出瞭如何玩我的「日期」值
我已經通過使用CallbackTransformer和addModelTranformer對象與閉包應用更改僅對我的formType類。
這就是它的工作就像一個魅力以及:)
$builder->get('createdAt')
->addModelTransformer(new CallbackTransformer(
function($dateTime) {
$date = new \DateTime();
$date->setTimestamp($dateTime);
return $date->format('d-m-Y');
},
function($timestamp) {
return $timestamp;
}
));
謝謝阿蘭。我讀了關於這個爐排組件!它看起來正是我需要的! :) –