How to do edit function in symfony2 - php

I have written a function for edit in symfony2, my problem is i can fetch the previous values from the database but after submitting the form the values were notr created instead a new form is creating
Here is the controller
public function editAction($id){
$request = $this->getRequest();
$em = $this->getDoctrine()->getEntityManager();
$profile= $em->getRepository('TcprofileBundle:TcProfiles')
->find($id);
$profile_form = $this->createForm(new ProfileType(), $profile);
$response = new JsonResponse();
$response->setData(array('content' => $this->renderView('TcprofileBundle:Default:create.html.twig',array('form' => $profile_form->createView()))));
return $response;
}
Html.twig file
<div class="edit01"> Edit Profile </div>
I'm fetching the old values, so i put if loop for condition check like this
controller
public function editAction($id){
$request = $this->getRequest();
$em = $this->getDoctrine()->getEntityManager();
$profile= $em->getRepository('TcprofileBundle:TcProfiles')
->find($id);
if(!$id){
$profile_form = $this->createForm(new ProfileType(), $profile);
$response = new JsonResponse();
$response->setData(array('content' => $this->renderView('TcprofileBundle:Default:create.html.twig',array('form' => $profile_form->createView()))));
return $response;
}else{
$profile->upload();
$em->persist($profile);
$em->flush();
$response = new JsonResponse();
$response->setData(array('content' => $this->renderView('TcprofileBundle:Default:create.html.twig',array('form' => $profile_form->createView()))));
return $response;
}
}
Its not getting output Pls help me if i gone wrong somewhere

You can use $em->merge($profile) instead of $em->persist($profile) when updating an entity. Please this stack overflow post

Related

How to explain this issue and what should be the best solution about Symfony serializer/csv decoder

I am trying to make a simple CSV uploader with contacts and make them as array using Symfony serializer/CSV encoder. The problem is that when i get data from csv and i dump it i get everything fine i think. But when i want to loop over the array to echo email field or try to create new Objects and save them to database i get an error that index 'Email Address' is undefined. How that can be possible, if when i var_dump in a loop and die after first array on the list i see that 'Email Address' field exists.
Link to image - https://imgur.com/a/7bSJT0z
/**
* #Route("/upload-csv", name="upload")
*/
public function uploadCsv(Request $request)
{
$form = $this->createForm(ContactType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid())
{
$em = $this->getDoctrine()->getManager();
$data = $form->getData();
$file = $data->getCsv();
//dump($file);
$serializer = $this->container->get('serializer');
$cons = $serializer->decode(file_get_contents($file), 'csv');
foreach ($cons as $con)
{
$contact = new Contact();
$contact->setEmail($con['Email Address']);
$contact->setFirstName($con['First Name']);
$contact->setLastName($con['Last Name']);
$contact->setCountry($data->getCountry());
$em->persist($contact);
}
$em->flush();
}
return $this->render('base.html.twig', [
'form' => $form->createView()
]);
}

How to save data from Postman in Symfony?

I try to send data from Postman to this function
public function new(Request $request): Response
{
$tag = new Tag();
$form = $this->createForm(TagType::class, $tag);
$form->submit($request->request->all());
if ($form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($tag);
$entityManager->flush();
$message = "Tag was successfully added";
return new JsonResponse(array("message: $message"));
}
$errors = $form->getErrors();
return new JsonResponse(array("message:$errors"));
}
If i send data as 'form-data' i can save it to database.
But i can't understand how to accept 'raw' Json 'application/json'
I can only manually take value from Request with
$tagTitle = $request->query->get('title');
And i can't do it with some FOSUserBundle etc.
I can use only jms/serializer. If i will need it.
You need to fetch the json from $request->getContent() first:
public function new(Request $request): Response
{
$tag = new Tag();
$form = $this->createForm(TagType::class, $tag);
$form->submit(json_decode($request->getContent(), true));
if ($form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($tag);
$entityManager->flush();
$message = "Tag was successfully added";
return new JsonResponse(array("message: $message"));
}
$errors = $form->getErrors();
return new JsonResponse(array("message:$errors"));
}

Entity persists even when form has error

I have an issue where I have a form type that persists the associated entity even when the form is not valid.
I have confirmed that the form indeed has errors via $form->getErrorsAsString(). I have also confirmed that the logical if statement that checks if the form is valid or not comes out false. The entity still persists despite the fact that the form is never valid.
I'm not sure what I'm doing wrong here as I have no other spot that I can find that either persists the entity or flushes the entity manager. Here's my controller:
/**
* #Route("/settings/profile", name="settings_profile")
* #Template();
*/
public function profileAction()
{
$user = $this->getUser();
$profile = $user->getUserProfile();
if (null === $profile) {
$profile = new UserProfile();
$profile->setUser($user);
$profileDataModel = $profile;
} else {
$profileDataModel = $this->getDoctrine()->getManager()->find('MyAppBundle:UserProfile',$profile->getId());
}
$form = $this->createForm(new ProfileType(),$profileDataModel);
$request = $this->getRequest();
if ($request->getMethod() === 'POST') {
$form->bind($request);
if ($form->isValid()) {
// This logic never gets executed!
$em = $this->getDoctrine()->getManager();
$profile = $form->getData();
$em->persist($profile);
$em->flush();
$this->get('session')->setFlash('profile_saved', 'Your profile was saved.');
return $this->redirect($this->generateUrl('settings_profile'));
}
}
return array(
'form' => $form->createView(),
);
}
I must have a listener or something somewhere that is persisting the user.
My work around for this temporarily is to do:
$em = $this->getDoctrine()->getManager()
if ($form->isValid()) {
// persist
} else {
$em->clear();
}
Until I can ferret out what listener or other data transformer is causing this.

Var filled with object suddenly null, what happened?

I am building this form in symfony 2.0 and for some reason when I retrieve a object from the db and put it into an object it is gone when I want to save it so I get the following error:
Catchable Fatal Error: Argument 1 passed to MelvinLoos\CMS\CoreBundle\Entity\Page::setParent()
must be an instance of MelvinLoos\CMS\CoreBundle\Entity\Page, null given,
called in vendor\symfony\src\Symfony\Component\Form\Util\PropertyPath.php on line 347
and defined in src\MelvinLoos\CMS\CoreBundle\Entity\Page.php line 233
My code:
public function popupChildAction($parentid)
{
$entity = new Page();
$entity->setWebsite($this->getWebsite());
$parent = $this->getDoctrine()
->getRepository('MelvinLoosCMSCoreBundle:Page')
->findOneById($parentid);
if (!$parent)
{
throw $this->createNotFoundException('No parent found with given id: "' . $parentid . '"');
}
$entity->setParent($parent);
$entity->setCreatedBy($this->getUser());
//$entity->setPageType();
$form = $this->createForm(new PageChildType(), $entity);
$request = $this->getRequest();
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('page_show', array('id' => $entity->getId())));
}
return $this->render('MelvinLoosCMSCoreBundle:Page:new_popup.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
'parent' => $parent
));
}
As you can see I put in a if statement to check if $parent is filled and I also tried a var_dump to double check, it is defiantly filled with an object. But for some reason when I call the setParent() function of the entity object it fills it with null.
Melvin you have the check if the form is submitted and to get your entity from the form.
Can you try like this?
$form = $this->createForm(new PageChildType(), $entity);
$request = $this->getRequest();
if ($request->getMethod() == 'POST') {
$form->bindRequest($request);
if ($form->isValid()) {
$entity = $form->getData();
$em = $this->getDoctrine()->getEntityManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('page_show', array('id' => $entity->getId())));
}
}
Totally forgot that I had this question still floating around... Anyway I got around my problem, still don't know why I got the error but I solved it with quite a easy solution.
Instead of setting the parent for the child, I did the reverse and set the child for the parent. My code is the following (There is also new code in there that's irrelevant because I fixed it some time ago).
public function popupChildAction($parentid)
{
$parent = $this->getDoctrine()
->getRepository('MelvinLoosCMSCoreBundle:Page')
->findOneById($parentid);
if (!$parent)
{
throw $this->createNotFoundException('No parent found with given id: "' . $parentid . '"');
}
$entity = new Page();
$entity->setWebsite($this->getWebsite());
$entity->setCreatedBy($this->getUser());
$form = $this->createForm(new PageChildType(), $entity);
$request = $this->getRequest();
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$parent->setChildren($entity);
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('page_show', array('id' => $entity->getId())));
}
return $this->render('MelvinLoosCMSCoreBundle:Page:new_popup.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
'parent' => $parent
));
}
Like I said there is newer code that is irrelevant but what it's all about is the part with
$parent->setChildren($entity); and now it works... hope this helps someone!
Thanks for everyone that gave input!

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