Skip to content
Advertisement

How could I cast to DateTimeInterface from String?? Symfony Ajax

My real problem is that I am sending an Ajax Jquery Request to an API of mine, the server response is ‘Argument #1 of ::setDate() must be DateTimeInterface, string given’

I tried to cast but it was useless.

My Ajax at JQUERY:

    $.ajax({
            type: "PUT",
            url: "/api/distribucion",
            data: JSON.stringify(dist),
            dataType: "json",
            success: function (response) {
                console.log("mesa " + response.id + " actualizada");
            }
        });

My API at PHP (Symfony’s controller):

    public function putDistribucion(ManagerRegistry $mr, Request $request): Response
    {
        $datos = json_decode($request->getContent());
        $datos = $datos->distribucion;
        // Cogemos el ID de el Distribucion a editar
        $id = $datos->id;
        // Obtenemos el Distribucion
        $distribucion = $mr->getRepository(Distribucion::class)->find($id);
        // Cambiamos todos sus campos
        $distribucion->setPosicionX($datos->pos_x);
        $distribucion->setPosicionY($datos->pos_y);
        $distribucion->setFecha($datos->fecha);
        $distribucion->setMesaId($datos->mesa_id);
        $distribucion->setAlias($datos->alias);
        $distribucion->setReservada($datos->reservada);

        $manager = $mr->getManager();
        try {
            // Lo mandamos a actualizar
            $manager->persist($distribucion);
            $manager->flush();
        } catch (PDOException $e) {
            $this->json(['message' => $e->getMessage(), "Success" => false], 400);
        }

        # Creado con éxito => Devolvemos la ID
        return $this->json(
            [
                "message" => "Éxito al editar la distribucion " . $id,
                "Success" => true
            ],
            202 // Aceptado
        );
    }

The Object I’m sending:

The console.log of the object sended

Advertisement

Answer

Your entity Distribucion probably has a setter that look like this:

public function setFecha(DateTimeInterface $fecha): self
    {
        $this->fecha = $fecha;

        return $this;
    }

The setter is typehinted with DateTimeInterface so you need to use a DateTime object and not a string.

You may create a DateTime easily with DateTime::createFromFormat

So $distribucion->setFecha($datos->fecha); will turn into something like:

$distribucion->setFecha(DateTime::createFromFormat('YYYY-MM-DD HH:ii:ss.u', $datos->fecha));

You may want to verify the date format I used as the first parameter of DateTime::createFromFormat

public static DateTime::createFromFormat(string $format, string $datetime, ?DateTimeZone $timezone = null)

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement