0

I am trying to save HTML content with the Symfony2 form system but I am facing issues with escaping.

My addPost action looks like this

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

$post = new Post();
$postForm = $this->createForm(new PostFormType(), $post);

if ($request->getMethod() == 'POST') {
   $postForm->bindRequest($request);

   if($postForm->isValid()){
      $em->persist($post);
      $em->flush();
   }
}

The problem is that the post form has a content textarea that allows the user to enter html. When the form is submitted with html like <a href="#">test</a> the content gets saved to the database as <a href=\"#\">test</a>. And then on each subsequent save the backslashes escape themselves again and again...

What is the proper way to store HTML with the Symfony2 form component?

2 Answers 2

1

You should remove the backslashes from the string before sending it to the user to edit. You should be able to get the content from the $post object and then strip its slashes and set it back to the post content like so.

$post = new Post();
$post->setContent(stripslashes($post->getContent()));
$postForm = $this->createForm(new PostFormType(), $post);

Now when the form renders it will not have the escape characters.

However, I have found that if you return a response to the same page you will still see the backslashes. To avoid this you can return a RedirectResponse like this

if($postForm->isValid()){
   $em->flush();
   return new RedirectResponse('route', array('postId' => $postId)));
}
Sign up to request clarification or add additional context in comments.

Comments

0

Those slashes are placed there so that the mysql engine doesn't confuse those quotes with sql syntax. I suggest you use a rejex to get rid of all the slashes when you retrieve the field from the database, but before you post it to the client. let me see if I can find the rejex for you, maybe someone will beat me to it :)

1 Comment

even better than the rejex, try using php's trim command --- string trim ( string $str [, string $charlist ] ) just make that second argument this: "\\" , Like this: trim($html, "\\");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.