Symfony conversion form field value

I use a table column to store "date_of_creation" (or created_at) in a Unix timestamp format (basically an integer with a length of 11).

At the same time, I would like to process this value in DateTime format "dmY" in my web form create / edit (Bootstrap Datepicker).

Here is the question :

What is the best way to convert and save the value passed in DateTime format to a table column that expects to receive an integer and, conversely, overrides the default value for the form field "timestamp format" with its corresponding DateTime format (DatePicker is recognized to do this)?

I am using Symfony 3.3.5 and Twig.

Here is an example :

I used a workaround to cover the area, but I'm not 100% sure this is a good practice ...

FormType.php adds a text box with a class for binding the DatePicker widget:

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

The Entity configuration item is as follows:

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

The real trick here is the optional $ stringToTime parameter.

And finally, 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()
    ));
}

The key part is the following:

$date = new \DateTime();
$date->setTimestamp($content->getCreatedAt());
$content->setCreatedAt($date->format('d-m-Y'), false);

This is what I did, and it works like a charm. But I don’t know if this is the right approach or if there are better solutions.

Thanks in advance for more than welcome comments :)

============== NEW DECISION ON THE BASIS OF THE OFFER Alena TIEMBOL

After reading a bit of documentation on Data Transformer, I finally figured out how to play with my Date value.

I applied the changes only to my formType type using CallbackTransformer and addModelTranformer objects with closure.

, :)

$builder->get('createdAt')
      ->addModelTransformer(new CallbackTransformer(
        function($dateTime) {
          $date = new \DateTime();
          $date->setTimestamp($dateTime);
          return $date->format('d-m-Y');
        },
        function($timestamp) {
          return $timestamp;
        }
      ));
+4
2

, Symfony " " !

:

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

.

+3

ORM (, doctrine), DateTime , DateTimes (html date picker ).

.

: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/basic-mapping.html

, .

+1

Source: https://habr.com/ru/post/1682783/


All Articles