Reputation: 531
A quick question about saving data in symfony 2. I have this method (just for testing):
protected function createProduct()
{
$product = new Product();
$product->setName('My product');
$product->setDescription('Lorem ipsum dolor sit amet');
$product->setIsPublished(1);
$product->setPosition(1);
$em = $this->getDoctrine()->getEntityManager();
$em->persist($product);
$em->flush();
}
Then i have the action (just for testing also):
public function indexAction()
{
$this->createCategory();
...
render ...
}
My problem is that when i execut the index action, the product is save twice in my database. Does anyone had similar problems ? Any way to solve it ?
Update: - full controller test class:
namespace Test\CategoryBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Test\CategoryBundle\Entity\Category;
use Symfony\Component\HttpFoundation\Response;
class CategoryController extends Controller
{
public function createAction()
{
$c = new Category();
$c->setName('Category');
$c->setDescription('Lorem ipsum dolor sit amet');
$c->setIsPublished(1);
$c->setPosition(1);
$em = $this->getDoctrine()->getEntityManager();
$em->persist($c);
$em->flush();
return new Response('Created category id '.$c->getId());
}
}
Routing in src/Test/CategoryBundle/Resources/config/routing.yml:
TestCategoryBundle_create:
pattern: /category/create
defaults: { _controller: TestCategoryBundle:Category:create }
Routing in app/config/routing.yml:
TestCategoryBundle:
resource: "@TestCategoryBundle/Resources/config/routing.yml"
prefix: /
Upvotes: 0
Views: 4429
Reputation: 2424
I had similar problem in Symfony 1.4.
I found a
<img src="">
(without src atributte), It causes the page load itself. Its not a symfony problem, its a browser feature :P
Maybe you have one too.
Upvotes: 0
Reputation: 531
I found the problem. I don't know yet if it's normal, but at least the data is not duplicated anymore.
The problem was solved by adding redirection to the createAction method. If you are not using a redirect, the data is duplicated. It's normal ??? Anyway, this is the solution that worked for me.
public function createAction()
{
$c = new Category();
$c->setName('My Category');
$c->setDescription('Lorem ipsum dolor sit amet');
$c->setIsPublished(1);
$c->setPosition(1);
$em = $this->getDoctrine()->getEntityManager();
$em->persist($c);
$em->flush();
return $this->redirect($this->generateUrl('your_routing_name_to_redirect'));
}
Upvotes: 2