0

I have a many to one related entities and everytime I create a new comment which is related to Project, I want to automatically save the realted project_id.

 comment
    id
    comment
 manyToOne
    project:
        targetEntity: Project
        cascade: {  }
        mappedBy: null
        inversedBy: comments
        joinColumn:
            name:  project_id
            referencedColumnName: id
        orphanRemoval: false

  project
      id
      projectName
  oneToMany:
    comments:
        targetEntity: Comment
        mappedBy: project  

When using Annotation, this can be done easily using the ParamConverter, but in this case I am using Yaml format.I am using the Symfony nice Crud command to automatically generate forms and templates as well as the controllers.

I tried in controller this way

public function createAction(Request $request, Project $project)//Project
{
    $entity = new Comment();
    $form = $this->createCreateForm($entity);
    $form->handleRequest($request);


    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
       // $entity->setProject($projectName->getProject());
        $entity->setProject($project);
        $em->persist($entity);
        $em->flush();

        return $this->redirect($this->generateUrl('comment_show', array('id' => $entity->getId())));
    }

Then in form,

   {{ form(form) }}

The problem with this is it will generate a form with a dropdown with hundreds of project_id in comment project_id field

Then when submitted

Unable to guess how to get a Doctrine instance from the request information.

I am thinking of writing a jquery autocomplete to solve this but if there is more shortcut way of doing this, like the annotation Paramconverter, I am glad to use it

How would you do it so that the related project_id will be automatically saved?

Update

This is exactly the code when running Symfony2 nice crud command in console

<?php

namespace EdgeWeb\Project\EmployeeBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use EdgeWeb\Project\EmployeeBundle\Entity\Comment;
use EdgeWeb\Project\EmployeeBundle\Form\CommentType;

/**
* Comment controller.
*
*/
class CommentController extends Controller
{

/**
 * Lists all Comment entities.
 *
 */
public function indexAction()
{
    $em = $this->getDoctrine()->getManager();

    $entities = $em->getRepository('EmployeeBundle:Comment')->findAll();

    return $this->render('EmployeeBundle:Comment:index.html.twig', array(
        'entities' => $entities,
    ));
}
/**
 * Creates a new Comment entity.
 *
 */
public function createAction(Request $request)
{
    $entity = new Comment();
    $form = $this->createCreateForm($entity);
    $form->handleRequest($request);

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($entity);
        $em->flush();

        return $this->redirect($this->generateUrl('comment_show', array('id' => $entity->getId())));
    }

    return $this->render('EmployeeBundle:Comment:new.html.twig', array(
        'entity' => $entity,
        'form'   => $form->createView(),
    ));
}

/**
 * Creates a form to create a Comment entity.
 *
 * @param Comment $entity The entity
 *
 * @return \Symfony\Component\Form\Form The form
 */
private function createCreateForm(Comment $entity)
{
    $form = $this->createForm(new CommentType(), $entity, array(
        'action' => $this->generateUrl('comment_create'),
        'method' => 'POST',
    ));

    $form->add('submit', 'submit', array('label' => 'Create'));

    return $form;
}

/**
 * Displays a form to create a new Comment entity.
 *
 */
public function newAction()
{
    $entity = new Comment();
    $form   = $this->createCreateForm($entity);

    return $this->render('EmployeeBundle:Comment:new.html.twig', array(
        'entity' => $entity,
        'form'   => $form->createView(),
    ));
}

/**
 * Finds and displays a Comment entity.
 *
 */
public function showAction($id)
{
    $em = $this->getDoctrine()->getManager();

    $entity = $em->getRepository('EmployeeBundle:Comment')->find($id);

    if (!$entity) {
        throw $this->createNotFoundException('Unable to find Comment entity.');
    }

    $deleteForm = $this->createDeleteForm($id);

    return $this->render('EmployeeBundle:Comment:show.html.twig', array(
        'entity'      => $entity,
        'delete_form' => $deleteForm->createView(),
    ));
}

/**
 * Displays a form to edit an existing Comment entity.
 *
 */
public function editAction($id)
{
    $em = $this->getDoctrine()->getManager();

    $entity = $em->getRepository('EmployeeBundle:Comment')->find($id);

    if (!$entity) {
        throw $this->createNotFoundException('Unable to find Comment entity.');
    }

    $editForm = $this->createEditForm($entity);
    $deleteForm = $this->createDeleteForm($id);

    return $this->render('EmployeeBundle:Comment:edit.html.twig', array(
        'entity'      => $entity,
        'edit_form'   => $editForm->createView(),
        'delete_form' => $deleteForm->createView(),
    ));
}

/**
* Creates a form to edit a Comment entity.
*
* @param Comment $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createEditForm(Comment $entity)
{
    $form = $this->createForm(new CommentType(), $entity, array(
        'action' => $this->generateUrl('comment_update', array('id' => $entity->getId())),
        'method' => 'PUT',
    ));

    $form->add('submit', 'submit', array('label' => 'Update'));

    return $form;
}
/**
 * Edits an existing Comment entity.
 *
 */
public function updateAction(Request $request, $id)
{
    $em = $this->getDoctrine()->getManager();

    $entity = $em->getRepository('EmployeeBundle:Comment')->find($id);

    if (!$entity) {
        throw $this->createNotFoundException('Unable to find Comment entity.');
    }

    $deleteForm = $this->createDeleteForm($id);
    $editForm = $this->createEditForm($entity);
    $editForm->handleRequest($request);

    if ($editForm->isValid()) {
        $em->flush();

        return $this->redirect($this->generateUrl('comment_edit', array('id' => $id)));
    }

    return $this->render('EmployeeBundle:Comment:edit.html.twig', array(
        'entity'      => $entity,
        'edit_form'   => $editForm->createView(),
        'delete_form' => $deleteForm->createView(),
    ));
}
/**
 * Deletes a Comment entity.
 *
 */
public function deleteAction(Request $request, $id)
{
    $form = $this->createDeleteForm($id);
    $form->handleRequest($request);

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $entity = $em->getRepository('EmployeeBundle:Comment')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Comment entity.');
        }

        $em->remove($entity);
        $em->flush();
    }

    return $this->redirect($this->generateUrl('comment'));
}

/**
 * Creates a form to delete a Comment entity by id.
 *
 * @param mixed $id The entity id
 *
 * @return \Symfony\Component\Form\Form The form
 */
private function createDeleteForm($id)
{
    return $this->createFormBuilder()
        ->setAction($this->generateUrl('comment_delete', array('id' => $id)))
        ->setMethod('DELETE')
        ->add('submit', 'submit', array('label' => 'Delete'))
        ->getForm()
    ;
  }
}

Then in FormType

 $builder
        ->add('comment')
        ->add('createdby')
        ->add('updatedby')
        ->add('datecreated')
        ->add('dateupdated')
        ->add('project')//related entity
    ;
Danielle Rose Mabunga
  • 1,676
  • 4
  • 25
  • 48

1 Answers1

0

I see at least 3 questions in your question...

For the error :

Unable to guess how to get a Doctrine instance from the request information,

I don't know why it's happening, but it doesn't seem related directly to the relationship question... Maybe try to suppress fields 'createdby', 'updatedby', 'datecreated', 'dateupdated'from the form builder, as they are not in your mapping yaml file (or maybe you just didn't show them) - whatever, you should probably not display them in the form, but complete these fields in the controller or via prePersist actions, as the user doesn't have to know about them.

Then for the problem that the project field of the form displays a dropdown with project ids : you can specify in the form builder which property of the comment entity you want to display, via the choice_label option, like this :

$builder
    ->add('comment')
    ->add('project', 'entity', array(
        'class' => 'YourBundle:Project',
        'choice_label' => 'projectName',
));

This way, you still will have a dropdown, but with project names displayed instead of ids. The 'entity' file field type has many other options, see the documentation.

For your last question, which is you would like to have a text field with autocomplete instead of a dropdown, you can manage it with a data transformer + a JS autocompleter. See this answer for more information.

Community
  • 1
  • 1
scandel
  • 1,692
  • 3
  • 20
  • 39