DateTimePicker and Datatransformer, the form render doesnt take the string into account

I got somme issue with Symfony to convert a DateTime into string. I use a DataTransformer to format my Datetime but in the form, there is an error that say : “This value should be of type string”.

Here is my code:
My Entity : Shift.php (only the necessary)

/**
 * @ORMId()
 * @ORMGeneratedValue()
 * @ORMColumn(type="integer")
 */
private $id;
/**
 * @ORMColumn(type="datetime")
 * @AssertDateTime(message="La date de début doit être au format DateTime")
 */
private $start_at;

My ShiftType :

$builder
    ->add('start_at', TextType::class, ['attr' => [ 'class' => 'dateTimePicker']])
    ->add('end_at', TextType::class, ['attr' => [ 'class' => 'dateTimePicker']])
    ->add('has_eat')
    ->add('break_duration')
    ->add('comment')
    ;
$builder->get('start_at')->addModelTransformer($this->transformer);
$builder->get('end_at')->addModelTransformer($this->transformer);

And my DataTransformer :

/**
 * @param DateTime|null $datetime
 * @return string
 */
public function transform($datetime)
{
    if ($datetime === null) 
    {
        return '';
    }
    return $datetime->format('Y-m-d H:i');
}
/**
 * @param string $dateString
 * @return Datetime|null
 */
public function reverseTransform($dateString)
{
    if (!$dateString) 
    {
        throw new TransformationFailedException('Pas de date(string) passé');
        return;
    }
    $date = Datetime::createFromFormat('Y-m-d H:i', $dateString);
    if($date === false){
        throw new TransformationFailedException("Le format n'est pas le bon (fonction reverseTransform)" . "$dateString");
    }
    return $date;
}

As i said, when i want submit the form, there are errors with the form.
It said “This value should be of type string.” and it’s caused by :

SymfonyComponentValidatorConstraintViolation {#1107 ▼
  root: SymfonyComponentFormForm {#678 …}
  path: "data.start_at"
  value: DateTime @1578465000 {#745 ▶}
}

Something weard, when i want to edit a shift, Symfony get the date from the db and transform it into string with no error message. But as i want to save the edit, i got the same issue

Could you help me please ?
Thanks

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *