Call an entity method in a controller - symfony

i have three entities: Invoice,Payment and Result
the relationships between entities are:
Result(1,1)-------------(1,n)Invoice(1,n)---------------(1,1)Payment
here's my problem :I would like in my PaymentController when I create a new payement ,I retrieve Invoice entity and in the same PaymentController I create a new Result.
here's my PaymentController code:
use MyApp\AccountBundle\Entity\Result;
class PaymentController extends Controller
public function createAction()
{
$entity = new Payment();
$request = $this->getRequest();
$form = $this->createForm(new PaymentType(), $entity);
$form->bindRequest($request);
$amount=$form->get('amountreceived')->getData();
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$invoice = em->getRepository('MyAppAccountBundle:Invoice')->find($entity->getInvoice()->getId())
if (!$invoice) {
throw $this->createNotFoundException('Unable to find Invoice entity.');
}
$result=new Result();
$result=setDebitAmount($amount);
$result=setCreditAmount(0);
$result=setInvoice($invoice);
$em->persist($result);
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('payment_show', array('id' => $entity->getId())));
}
return $this->render('MyAppAccountBundle:Payment:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView()
));
when a execute PaymentController (in view) i get error:
Fatal error: Call to undefined function MyApp\AccountBundle\Controller\setDebitAmount() in C:\wamp\www\account\src\ MyApp\AccountBundle\Controller\PaymentController.php on line...
thank in advance

Change = to ->
$result=setDebitAmount($amount);
must be
$result->setDebitAmount($amount);

Related

Automatically set related entity id in one to many relationship Symfony

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
;
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.

how to remove unable to find entity error?

i make an update function of controller but when i insert values in fields and the submit the exception return,i make an update function of controller but when i insert values in fields and the submit the exception return,
"Unable to find Sections entity"
here is my controller code:
public function updateAction(Request $request, $id)
{
if(isset($_SESSION['id'])) {
$proposalid=$_SESSION['id'];
}
$user = $this->get('security.context')->getToken()->getUser();
$userId = $user->getId();
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ProposalsProposalsBundle:Sections')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Sections entity.');
}
$deleteForm = $this->createDeleteForm($id);
$editForm = $this->createForm(new SectionsType(), $entity);
$editForm->bind($request);
$sectioncounter = $request->request->get('sectioncounter');
$date= new \DateTime();
$query = $em->createQuery("Delete from ProposalsProposalsBundle:Sections s where s.proposalID='".$proposalid."'");
$ids = $query->getResult();
if($request->isXmlHttpRequest()) {
$response = new Response();
for($i=0; $i<$sectioncounter; $i++){
$sectionname = $_POST['sectionName'.$i];
$description=$_POST['description'.$i];
$entity->setSectionName($sectionname);
$entity->setDescription($description);
$entity->setProposalID($proposalid);
$entity->setCreatedBy($userId);
$entity->setUpdatedBy($userId);
$entity->setCreatedDatetime($date);
$entity->setUpdatedDatetime($date);
$em->persist($entity);
$em->flush();
$em->clear();
}
return $response;
}
return $this->render('ProposalsProposalsBundle:Sections:edit.html.twig', array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
how to remove this exception?
Symfony2 has its own session handler. To set a session variable:
$session = $this->getRequest()->getSession();
$session->set('member', $member);
To get a session variable:
$session = $this->getRequest()->getSession();
$member = $session->get('member');

symfony doctrine update from form

I'm stuck since this morning with the update of an entity.
Don't know what I'm missing, pretty sure this is a newbie mistake.
I'm just trying to update something via a form.
The controller:
public function editAction($pid, $plid, Request $request)
{
$plan = new Plan();
$form = $this->createForm(new PlanType(), $plan);
$plan = $this->getDoctrine()->getRepository('QArthFrameworkBundle:Plan')->findOneByPlid($plid);
$project = $this->getDoctrine()->getRepository('QArthFrameworkBundle:Project')->findOneByPid($pid);
$form->handleRequest($request);
if ($request->getMethod() == 'POST') {
$em = $this->getDoctrine()->getManager();
$em->flush();
return $this->redirect($this->generateUrl('qarth_framework_plan_edit', array('pid' => $pid, 'plid' => $plid)));
}
return $this->render('QArthFrameworkBundle:Pages:plan_edit.html.twig', array(
'plan' => $plan,
'project' => $project,
'form' => $form->createView(),
));
}
The form:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('name');
$builder->add('description', 'textarea');
}
The Entity : http://pastebin.com/bTqKehyQ
With the profiler I can see that my post parameters are well posted
plan {"name":"fsggsfgsf","description":"gsfgsfgsf","_token":"7d089aca0203c60fe1e617488e532ac966101440"}
But I can't see any trace of an update query or something else.
If you have an idea, it will be great!
Many thanks,
Ben
Need to pass the queried plan to the form.
public function editAction($pid, $plid, Request $request)
{
$plan = $this->getDoctrine()->getRepository('QArthFrameworkBundle:Plan')->findOneByPlid($plid);
$project = $this->getDoctrine()->getRepository('QArthFrameworkBundle:Project')->findOneByPid($pid);
// Create a new one if not found
if (!$plan) $plan = new Plan();
// Build your form using queried or new plan
$form = $this->createForm(new PlanType(), $plan);
$form->handleRequest($request);
// Checks for POST as well as validity
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($plan); // To handle new plans, no impact for existting plans
$em->flush();
// Rest is the same

Symfony2 persist correlated objects

This my issue:
Entity AddressBook 1-N Entity Number
The controller displays the edit form with AddressBook and its number, but when I save the form, I get this error:
Fatal error: Call to a member function setTipo() on a non-object
Strangely, however, the data is saved correctly
This my code:
/**
* Modifica dati Anagrafica
* #Route("/contatto/{id}/modifica", name="_anagrafica_modifica")
* #Template()
*/
public function modificaAction($id)
{
$em = $this->getDoctrine()->getManager();
$anagrafica = $em->getRepository('MercurioInterfaceBundle:Anagrafica')->find($id);
if (!$anagrafica) {
throw $this->createNotFoundException('No anagrafica found for id '.$id);
}
$form = $this->createForm(new \Mercurio\InterfaceBundle\Form\Anagrafica\FormAnagrafica(), $anagrafica);
$request = $this->getRequest();
if ($request->getMethod() == 'POST')
{
$form->bind($request);
if ($form->isValid())
{
$chiave = $request->request->get('anagrafica');
$em = $this->getDoctrine()->getManager();
$anagrafica = $em->getRepository('MercurioInterfaceBundle:Anagrafica')->find($id);
$anagrafica->setNominativo($chiave['nominativo']);
$anagrafica->setIndirizzo($chiave['indirizzo']);
$anagrafica->setCap($chiave['cap']);
$anagrafica->setCitta($chiave['citta']);
$anagrafica->setNote($chiave['note']);
$em->flush();
$dettaglio = $em->getRepository('MercurioInterfaceBundle:AnagDettaglio')->findBy(array('anagrafica_id' => $id,));
foreach ($chiave['anag_dettagli'] as $d)
{
$dettaglio->setTipo($d['tipo']);
$dettaglio->setValore($d['valore']);
$dettaglio->setRiferimento($d['riferimento']);
}
$em->flush();
return $this->redirect($this->generateUrl('_anagrafica_contatto', array('id' => $id)));
}
}
return array(
'form' => $form->createView(),
'id' => $id
);
}
Solved:
$form = $this->createForm(new \Mercurio\InterfaceBundle\Form\Anagrafica\FormAnagrafica(),$anagrafica);
if ($request->isMethod('POST')){
$form->bind($request);
if ($form->isValid()) {
$em->persist($anagrafica);
$em->flush();
return $this->redirect(....)
}
}

Can I invalidate a Symfony2 form?

I have an issue in that a Symfony2 form can pass validation but still generate a Doctrine2 exception caused by a unique constraint when the form is submitted. I can catch this PDOException, but what I want to do is invalidate the form and set a form error indicating that a particular attribute of the entity is a duplicate. The code I have is:
$entity = new Tag();
$request = $this->getRequest();
$form = $this->createForm(new \Acme\AdminBundle\Form\Tag(), $entity);
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
try {
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('tag_edit', array('id' => $entity->getTagId())));
} catch( ORM\PDOException $e) {
if ($e->getCode() === '23000') {
// What do I do here??
}
}
}
return array(
'entity' => $entity,
'form' => $form->createView()
);
I think you are looking for the UniqueEntity annotation.
If you use it, you won't need the try/catch block, because a check will be performed before an insert is even attempted.

Resources