Search code examples
phpsymfonysymfony4

How to manually add data to form / request


I want to add custom data to the form or request - for example author_id while saving my Post to database.

I've tried to do that by using:

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

But the problem is that when I dd($request) I see the following data:

enter image description here

So I should get inside the post array somehow and then put the author_id. How to achieve that?

In laravel I would do it like so $request['post']['author_id'] = id;

My actual function in controller looks like:

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

        ...
 }

What is the best way to add some custom data - not visible in the view (for example pass the user id) to the request or to directly to the form without displaying it (I am not talking about display:none attribute)?


Solution

  • The request as a notion is supposed to be used as a read only bag of values passed by the user.

    If you want to manipulate the data to save them to your database, you should do it in your model manipulation code

    Based on the comments above, after you validate and check the form as submitted, you should do something like

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

    You can also move the created date setting directly to your entity constructor to avoid setting it yourself every time (Carbon is not necessary, you can obviously just pass it a plain datatime)