symfony - 在 Symfony 中转换表单字段值

标签 symfony

我使用表列以 Unix 时间戳格式(基本上是长度为 11 的整数)存储“date_of_creation”(或created_at)。

同时,我想在我的创建/编辑网络表单(Bootstrap Datepicker)中使用日期时间格式“d-m-Y”处理该值。

这是问题:

在希望接收整数的表列上转换和保留以 DateTime 格式传递的值的最佳方法是什么,反之亦然,用相应的 DateTime 格式覆盖表单字段默认值“时间戳格式”(以使它可以被 DatePicker 识别)吗?

我正在使用 Symfony 3.3.5 和 Twig。

这是一个示例:

我已经使用了一种解决方法来达到范围,但我不能 100% 确定这是一个好的做法......

FormType.php 添加一个带有类的文本字段来 Hook DatePicker 小部件:

->add('createdAt', TextType::class, [
            'attr' => [
                'class' => 'js-datepicker'
            ],
        ])

实体 setter 如下所示:

/**
 * @param mixed $createdAt
 */
public function setCreatedAt($createdAt, $stringToTime = true)
{
    $this->createdAt = ($stringToTime) ? strtotime($createdAt) : $createdAt;
}

这里真正的技巧是额外的 $stringToTime 参数。

最后是 Controller 操作:

/**
 * @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);

这就是我所做的,它很有魅力。 但我不知道这是否是正确的方法,或者是否有更好的解决方案。

预先感谢您的欢迎致辞:)

============= 基于 Alain Tiemblo 建议的新解决方案

在阅读了一些有关数据转换器的文档后,我终于弄清楚了如何使用我的“日期”值

我通过使用 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;
        }
      ));

最佳答案

好消息,Symfony Data Transformers正是为此而生!

创建表单时,您可以添加:

use Symfony\Component\Form\CallbackTransformer;

// (...)

$builder->get('createdAt')
    ->addModelTransformer(new CallbackTransformer(
        function ($dateModelToView) {
            $date = new \DateTime();
            $date->setTimestamp($dateModelToView);
            return $date;
        },
        function ($dateViewToModel) {
            return $dateViewToModel->getTimestamp();
        }
   ));

并且转换将是全自动的。

关于symfony - 在 Symfony 中转换表单字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45443413/

相关文章:

php - 如何将模型转换器应用于 Symfony2 表单中的集合项?

javascript - Symfony2 Ajax 和 Jquery

symfony - 如何通过 Twig 模板在 Silex 2 中使用 CSRF token ?

javascript - Angular2 - Symfony3应用程序如何在客户端和服务器之间发送 session ?

mongodb - 在 symfony2 中使用 doctrine 扩展在 doctrine2 odm 和 orm 之间共享对象

php - 使用关联的实体字段设置 slug

Symfony 2.7 : asset component not working with imagine_filter

symfony - 通过 Composer 更新时不是 git 存储库错误

symfony - 教义 createNativeQuery 不返回结果

symfony - FOSRestBundle:未触发 ExceptionController