Symfony2 return value of flush metode - php

Ok i got stuck and no info in documentation about this (correct me if i am wrong)
Example: i have update metod in controller, some form and if forim is valid i use flush method to make changes. How can i check if changes were made in DB so i can send flash message if changes were made "Success" or if query is not executed if there is some error i send flash message "Failed to make changes to DB"
Here is example of my code but i think that flush returns void or null so this is not the way to go, maybe it returns some exceptions on failure i dont know..
/**
* #Route("createpost", name="createpost")
*/
public function createPostAction(Request $request) {
if (!$this->get('security.authorization_checker')->isGranted('ROLE_ADMIN')) {
throw $this->createAccessDeniedException();
}
$post = new Post();
$form = $this->createForm(new PostForm(), $post);
$form->handleRequest($request);
if($form->isValid()) {
$user = $this->getUser();
$author = $user->getUsername();
//$post->setPublishDate(new \DateTime);
$post->setAuthor($author);
$em = $this->getDoctrine()->getManager();
$em->persist($post);
$pom = $em->flush();
return $this->render('success/success.html.twig', array(
'test' => var_dump($pom)
));
if($pom) {
$this->addFlash(
'notice',
'You have successfully created post'
);
}
return $this->redirectToRoute('home', array(), 301);
}
return $this->render(
'create/post.html.twig', array(
'form' => $form->createView()
));
}

You can do it like this:
...
if($form->isValid()) {
$user = $this->getUser();
$author = $user->getUsername();
//$post->setPublishDate(new \DateTime);
$post->setAuthor($author);
$em = $this->getDoctrine()->getManager();
$em->persist($post);
$em->flush();
if(null != $post->getId()) {
$this->addFlash(
'notice',
'You have successfully created post'
);
return $this->render('success/success.html.twig', array(
'test' => var_dump($pom)
));
}
// This line never be called
return $this->redirectToRoute('home', array(), 301);
}
...
However, you don't need to check if flush worked properly or not, it throws an exception if something goes wrong..
Update for the comment:
if($form->isValid()) {
try {
$user = $this->getUser();
$author = $user->getUsername();
//$post->setPublishDate(new \DateTime);
$post->setAuthor($author);
$em = $this->getDoctrine()->getManager();
$em->persist($post);
$em->flush();
if(null != $post->getId()) {
$this->addFlash(
'notice',
'You have successfully created post'
);
return $this->render('success/success.html.twig', array(
'test' => var_dump($pom)
));
}
} catch (SOMEEXCEPTION $e) {
return $this->redirectToRoute('home', array(), 301);
}
}

Change
return $this->render('success/success.html.twig', array(
'test' => var_dump($pom)
));
if($pom) {
$this->addFlash(
'notice',
'You have successfully created post'
);
}
To
if($pom) {
$this->addFlash(
'notice',
'You have successfully created post'
);
}
return $this->render('success/success.html.twig', array(
'test' => var_dump($pom)
));
You need to add flash before returning the response

Related

The file "prueba.jpeg" was not uploaded due to an unknown error

I have set up uploading images correctly in the admin and I followed this documentation: https://symfony.com/doc/current/bundles/EasyAdminBundle/integration/vichuploaderbundle.html
Now in another part of the system that does not use EasyAdminBundle I need to upload images, in the controller I have this:
public function crearequiposAction(Request $request) {
$equipo = new Equipos();
$form = $this->createForm(EquiposType::class, $equipo);
$form->handleRequest($request);
if ($form->isSubmitted()) {
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$fecha=new \DateTime('now');
$ruta = $equipo->getImageFile();
$nombrep = $equipo->getLogo();
$nombre = $nombrep.'.'.$ruta->guessExtension();
$fileDir = $this->container->getParameter('kernel.root_dir').'/../web/uploads/images/equipos';
$ruta->move(
$fileDir,
$nombre
);
$equipo->setLogo($nombre);
$equipo->setUpdatedAt($fecha);
$em->persist($equipo);
$flush = $em->flush();
if ($flush == null) {
$status = "Documento registrado correctamente";
$this->session->getFlashBag()->add("status", $status);
return $this->redirectToRoute("listado-torneos");
} else {
$status = "No se registro equipo";
}
} else {
$status = "No se registro equipo";
}
$this->session->getFlashBag()->add("status", $status);
}
return $this->render('AppBundle:Equipos:informacionequipos.html.twig', array(
"form" => $form->createView()
));
}
The image uploads correctly but it shows me this error:
The file "prueba.jpeg" was not uploaded due to an unknown error.
And I do not know how to solve this problem, any ideas?
regards
This is the solution, the problem was in two parts.
First in the form it is necessary to change the form to this:
use Vich\UploaderBundle\Form\Type\VichFileType;
use Symfony\Component\HttpFoundation\File\File;
$builder
->add('nombre')
->add('grupo')
->add('numero')
->add('imageFile', VichFileType::class)
->add('torneos')
->add('save', SubmitType::class, array(
"attr" => array(
"class" => "save"
)));
The second change is in the controller, when using the bundle it is no longer necessary to use the move, that is only used when images are uploaded natively
This is the code of the controller:
public function crearequiposAction(Request $request) {
$equipo = new Equipos();
$form = $this->createForm(EquiposType::class, $equipo);
$form->handleRequest($request);
if ($form->isSubmitted()) {
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($equipo);
$flush = $em->flush();
if ($flush == null) {
$status = "Equipo registrado correctamente";
$this->session->getFlashBag()->add("status", $status);
return $this->redirectToRoute("listado-torneos");
} else {
$status = "No se registro equipo";
}
} else {
$status = "No se registro equipo";
}
$this->session->getFlashBag()->add("status", $status);
}
return $this->render('AppBundle:Equipos:informacionequipos.html.twig', array(
"form" => $form->createView()
));
}
Regards

Symfony2: Inserting a collection of files

While trying to insert a collection of entities which have a file field, i couldn't figure out if there's is a better way to create the UploadedFile Object being cast by the Document::document annotation. Here's my code, any help on improving it is very appreciated :)
public function createAction(Request $request) {
$em = $this->getDoctrine()->getManager();
$user = $this->get('security.context')->getToken()->getUser();
$entity = new Paper();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$entity->setAuthor($user);
$em->persist($entity);
// chotest foreach in the universe
if (isset($_FILES) && array_key_exists('arkad1a_cfpbundle_paper', $_FILES)) {
foreach ($_FILES['arkad1a_cfpbundle_paper']['name']['documents'] as $k => $v) {
$document = new UploadedFile(
$_FILES['arkad1a_cfpbundle_paper']['tmp_name']['documents'][$k]['document'],
$_FILES['arkad1a_cfpbundle_paper']['name']['documents'][$k]['document'],
$_FILES['arkad1a_cfpbundle_paper']['type']['documents'][$k]['document'],
$_FILES['arkad1a_cfpbundle_paper']['size']['documents'][$k]['document'],
$_FILES['arkad1a_cfpbundle_paper']['error']['documents'][$k]['document'],
false
);
$Document = new \Arkad1a\CFPBundle\Entity\Document();
$Document->setAuthor($user)
->setDocument($document)
->setPaper($entity)
->upload();
$em->persist($Document);
}
}
$em->flush();
return $this->redirect($this->generateUrl('paper_show', array('id' => $entity->getId())));
} else {
die('invalid');
}
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}

how i save data in zf2 using mongoDB with Doctrine 2 ODM?

i make a controller in zf2 for save data in mongodb but it not save any record in event table,how i save data?here is my code:
public function createAction()
{
$calendar_id = (int) $this->params()->fromRoute('id', 0);
if ($calendar_id == 0) {
return $this->redirect()->toRoute('calendar', array(
'action' => 'index'
));
}
//echo $calendar_id;
$dm = $this->getServiceLocator()->get('doctrine.documentmanager.odm_default');
$form = new EventForm();
$update=false;
$message='';
$form->get('calendar_id')->setValue($id);
$form->get('submit')->setValue('Add');
if ($this->getRequest()->isPost()) {
$post = $this->getRequest()->getPost();
$form->setInputFilter($form->getInputFilter());
$form->setData($post);
if ($form->isValid()) {
$formData=$form->getData();
$s = new Event();
$s->setProperty('calendar_id',$calendar_id);
$s->setProperty('title',$post['title']);
$s->setProperty('description',$post['description']);
$s->setProperty('startdate',$post['begin']);
$s->setProperty('enddate',$post['end']);
$dm->persist($s);
$dm->flush();
$update=1;
$message='calendar Added Successfully.';
//$form = new CalendarForm();
//$this->redirect()->toRoute('calendar');
}
}
return array('form' => $form, 'add_message' => $message, 'update' => $update, 'calendar'=>$this->calendar);
}
I set code and save data using mongoodm,here is my code:
public function createAction()
{
$dm = $this->getServiceLocator()->get('doctrine.documentmanager.odm_default');
$calendar_id = (int) $this->params()->fromRoute('id', 0);
if ($calendar_id == 0) {
return $this->redirect()->toRoute('calendar', array(
'action' => 'index'
));
}
$form = new EventForm();
$update=false;
$message='';
$form->get('calendar_id')->setValue($calendar_id);
$form->get('submit')->setValue('Add');
if ($this->getRequest()->isPost()) {
$post = $this->getRequest()->getPost();
$form->setInputFilter($form->getInputFilter());
$form->setData($post);
if ($form->isValid()) {
$formData=$form->getData();
$s = new Event();
$s->setProperty('calendar_id',$post['calendar_id']);
$s->setProperty('title',$post['title']);
$s->setProperty('description',$post['description']);
$s->setProperty('startdate',$post['begin']);
$s->setProperty('enddate',$post['end']);
$dm->persist($s);
$dm->flush();
$update=1;
$message='calendar Added Successfully.';
$form = new EventForm();
$this->redirect()->toRoute('calendar');
}
}
return array('form' => $form, 'add_message' => $message, 'update' => $update, 'calendar'=>$this->calendar);
}

How to get last inserted id in zf2?

I am new in zf2. I make a create action and want to get last inserted id but calender_id always equal to zero. How can I get the last insert id in create action ?
Here is my code:
public function createAction()
{
if ($this->zfcUserAuthentication()->hasIdentity())
{
$form = new CalendarForm();
$form->get('user_id')->setValue($this->zfcUserAuthentication()->getIdentity()->getId());
$form->get('submit')->setValue('Add');
$request = $this->getRequest();
if ($request->isPost()) {
$calendar = new Calendar();
$form->setInputFilter($calendar->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$calendar->exchangeArray($form->getData());
$this->getCalendarTable()->saveCalendar($calendar);
if($request->isXmlHttpRequest()) {
//$dm = $this->getServiceLocator()->get('doctrine.documentmanager.odm_default');
//$calender = new \Calendar\Model\Calendar($dm);
$response = new Response();
$calender_id = $calendar->calendar_id;
$userid =$calendar->user_id;
$title=$calendar->title;
$description=$calendar->description;
$output = array('success' => true, 'calendar_id' => $calender_id, 'user_id' => $userid, 'title' => $title, 'description' => $description);
//$response->headers->set('Content-Type', 'application/json');
$response->setContent(json_encode($output));
return $response;
}
return $this->redirect()->toRoute('calendar');
}
}
return array('form' => $form);
}
else
{
$this->redirect()->toRoute('zfcuser/login');
}
}
how i get last inserted id?
If your calendarTable extends TableGateway you can use $calendarTable->getLastInsertValue() to get the last insert id. You can also use this method in your saveCalendar method.

Symfony2 How to process dynamic embed forms collection?

I try this cookbook about embed form:
http://symfony.com/doc/current/cookbook/form/form_collections.html
But the embed foreign key (task_id field in Tag table) is not save, always NULL
Here the complete code: https://gist.github.com/1755140
Do you know why?
Thank
Edit::
My trouble was in process form action. Like the tag form is embed dynamically, so i don't know how many tag(s) i will have. If i add in createAction
$tag1 = new Tag();
$task->addTags($tag1);
only the first embed form was correctly save! How to save the other tags?
public function createAction(Request $request)
{
$task = new Task();
$tag1 = new Tag();
$task->addTags($tag1);
$form = $this->createForm(new TaskType(), $task);
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($task);
$em->flush();
return $this->redirect($this->generateUrl('new_task', array('id' => $task->getId())));
}
return array(
'form' => $form->createView()
);
}
Edit2:
My solution which resolve the trouble, what do you think about it? Better?
public function createAction(Request $request)
{
$task = new Task();
$tasks = $request->request->get('task', array());
if (isset($tasks['tags'])) {
$tags = $tasks['tags'];
foreach($tags as $tag) {
$tag = new Tag();
$task->addTags($tag);
}
}
$form = $this->createForm(new TaskType(), $task);
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($task);
$em->flush();
return $this->redirect($this->generateUrl('new_task', array('id' => $task->getId())));
}
return array(
'form' => $form->createView()
);
}
Edit3:
A much better alternative (not tested again)
http://www.siteduzero.com/tutoriel-3-523899-creer-des-formulaires-avec-symfony2.html#ss_part_2
public function createAction(Request $request)
{
$task = new Task();
$form = $this->createForm(new TaskType(), $task);
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($task);
foreach($task->getTags() as $tag) {
$em->persist($tag);
}
$em->flush();
return $this->redirect($this->generateUrl('new_task', array('id' => $task->getId())));
}
return array(
'form' => $form->createView()
);
}
In TaskController on line 29 try to use $task->addTags($tag1); instead of $task->getTags()->add($tag1);
I don't understand. Is this solution wrong?
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
foreach($task->getTags() as $tag) {
$tag->setTask($task);
}
$em->persist($task);
$em->flush();
return $this->redirect($this->generateUrl('new_task', array('id' => $task->getId())));
}
It works and it seems simpler.

Categories