如何手动添加数据到表单/请求

How to manually add data to form / request

我想在表单或请求中添加自定义数据 - 例如 author_id,同时将我的 Post 保存到数据库。

我试过使用:

$request->request->set('author_id', '5');
$request->request->set('post.author_id', '5');
$request->request->set('post[author_id]', '5');

但问题是,当我 dd($request) 我看到以下数据时:

所以我应该以某种方式进入 post 数组,然后放入 author_id。如何实现?

在laravel我会这样做$request['post']['author_id'] = id;

我在控制器中的实际功能如下:

$post = new Post();
$form = $this->createForm(PostType::class, $post);

$form->handleRequest($request);

$request->request->set('author_id', '5');

if ($form->isSubmitted() && $form->isValid()) {

     $entityManager = $this->getDoctrine()->getManager();
     $entityManager->persist($post);
     $entityManager->flush();

        ...
 }

添加一些自定义数据的最佳方法是什么 - 在视图中不可见(例如传递用户 ID)到请求或直接到表单而不显示它(我不是在谈论 display:none 属性)?

作为概念的请求应该用作用户传递的值的只读包。

如果你想操作数据以将它们保存到你的数据库中,你应该在你的模型操作代码中进行

根据以上评论,在您验证并检查提交的表单后,您应该执行类似

的操作
$post = $form->getData();
$post->setAuthor($authorId);
$post->setCreatedDate(Carbon::now());
$entityManager->persist($post);
$entityManager->flush();

您也可以将创建的日期设置直接移动到您的实体构造函数,以避免每次都自己设置(不需要 Carbon,您显然可以只传递一个普通的数据时间)