S
S
symnoob2021-05-05 10:43:03
symfony
symnoob, 2021-05-05 10:43:03

How to prefill form fields?

Good afternoon,

is it possible to prefill a new form before submitting it to the user?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
BoShurik, 2021-05-05
@symnoob

You need to fill the object that you pass to the form with the necessary data:

$post = new Post();
// Заполняем поля, которые присутствуют в форме
$post->setPublishedAt(new \DateTime());
$post->setTitle('New title');

// Если объекты не используются, то заполнять надо массив
// $post = [];
// $post['publishedAt'] = new \DateTime();
// $post['title'] = 'New title';

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

// ...

return $this->render('post.html.twig', [
    'form' => $form->createView(),
])

If suddenly there is no (why?) possibility to transfer the filled data, then you can initialize them inside the FormType:
$builder->get('publishedAt')->setData(new \DateTime());
$builder->get('title')->setData('New title');

or
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
    $data = $event->getData();
    if ($data !== null) {
        return;
    }
    $event->setData([
        'title' => 'New title',
        'publishedAt' => new \DateTime(),
    ]);
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question