Symfony 5:如何使用 ajax 和不使用表单创建(在数据库中)

Symfony 5 : how to create (in a database) with ajax and without form

我有这个按钮,我想制作它,所以当我点击它时,有一个 ajax 直接进入我在 symfony 中的创建函数,但不显示任何形式(在这个点我已经有了我需要的信息)。但是我不知道如何以这种方式获取表格。

我曾经做过

$livre = new Livre();
$livre->setUuid(Uuid::v4());

$form = $this->createForm(LivreType::class, $livre);
$form->handleRequest($request);

但显然我不能再使用 LivreType::class 因为我不需要表格。 我一直在搜索有关此的信息,但找不到任何信息

有什么想法吗?

您将有多种实现方式。 我将向您展示一种简单的方法,并尝试适应或找到更好的方法!


LivreController.php

    /**
     * @Route(path="/livre/create", methods={POST})
     */
    public function createNewLivre(Request $request, EntityManagerInterface $em)
    {
        $json       = $this->getJSON($request);
        $newLivre   = new Livre();

        // Set to your new entity parameters...
        $em->persist($newLivre);
        $em->flush();

        return $this->json([
            'message' => 'A new Livre has been added.' // It could also be empty if you don't want to manage anything
        ]);
    }

    private function getJSON(Request $request)
    {
        $data = json_decode($request->getContent(), true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new HttpException(400, 'json invalid');
        }

        return $data;
    }

script.js

let button = document.getElementById('livreCreatorButton');

button.addEventListener("click", e => {
    e.preventDefault();

    fetch('http://127.0.0.1:8000/livre/create', {
        method: 'POST', // or 'PUT'
        headers: {
            'Content-Type': 'application/json',
        },
        body: '{}',
    })
});