Answer the question
In order to leave comments, you need to log in
Where is the correct way to save an entity in symfony2?
You can do everything in the controller, but it seems not recommended. And how is it right and right to take it to the service, or is it done as a method of the entity repository?
It's just that most of the data is not transmitted in the form, but generated. An image is loaded, it has data about height, width, file name, extension (format), alias, and IP address - all this data is not in the form itself, and is provided by the image saving service (Imagine) after processing and saving the image itself.
In the controller it is something like this
$entity = new Upload();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$entity = new Upload();
$form = $this->createForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$saver = $this->getSaver(); // Сервис сохранения, сжимает, сохраняет и предоставляет инфу
$image = $saver->save($entity->getImage());
$entity->setUserId(100); // Кто загрузил
$entity->setIp(ip2long($request->getClientIp())); // IP загрузившего
// достаточно геморно получать IP из сервисов, если правильно понял,
// в сервис для этого нужно передавать request_stack
// Ну и самый сок. Хочется этот кусок куда нибуди вынести,
// либо в репозиторий либо в сервис, но как не знаю
$entity->setFile($saver->getName());
$entity->setWidth($saver->getHeigth());
$entity->setHeight($saver->getWidth());
$entity->setExt($saver->getExt());
$entity->setAlias($saver->getAlias());
// Само сохранение сущности в базу
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
}
}
Answer the question
In order to leave comments, you need to log in
Everything is fine here. It makes no sense to take out this code. Store entity in controller is fine Symfony Best Practices
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question