Drake Drake - 6 months ago 35
PHP Question

Symfony2 - How can you append to a form field?

So, my question would be, that I have a comment form field in my Symfony2 project, like this:

->add('comment', 'textarea', array('label' => "Add a comment", 'required' => false))

Before this I also handle some other data and would like to be able to append that data into the comment field, and store it like that. Like the guy enters a comment, and then I also append some other data before or after it. I can't modify form data, because they are in the request variable. Do I need a helper variable, that I can store the comment I put together and flush that helper into my database?

Answer Source

You can do it using the POST_SUBMIT form event (http://symfony.com/doc/current/form/events.html#c-the-formevents-post-submit-event) or anywhere after the data was submitted:

if ($form->isSubmitted() && $form->isValid()) {
    $entity = $form->getData();
    $entity->setComment($entity->getComment . ' appended content')

    $em = $this->getDoctrine()->getManager();