how to remove unable to find entity error? - symfony

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');

Related

Binding entities to query parameters only allowed for entities have an identifier

I am using a Symfony 4 project, and I want to change the user password, so I created a method in my repository and called it to the controller, but this error it diplay to me,
Binding entities to query parameters only allowed for entities that have an identifier.
Repository
public function updateU($password,$email): ?Utilisateur
{
$dql = <<<DQL
SELECT u
FROM App\Entity\Utilisateur u
WHERE u.email = :email
AND u.password = :password
DQL;
return $this->getEntityManager()->createQuery($dql)
->setParameters(['email' => $email, 'password' => $password])
->getSingleScalarResult();
}
Controller
/**
* #Route("/Reset", name="Reset")
* Method({"GET"})
*/
public function New(
Request $request,
UtilisateurRepository $URe,
UserPasswordEncoderInterface $userPasswordEncoder,
EntityManagerInterface $entityManager,
MailerInterface $mailer
) {
$o = '';
$Varmail = $_GET['email'];
$user = new Utilisateur($o);
$form = $this->createFormBuilder($user)
->add('password', PasswordType::class)
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$to = $Varmail;
$sujet = 'Password Changed';
$Message = "Bonjour $Varmail Votre email est changé !";
$pass = $user->setPassword(
$userPasswordEncoder->encodePassword(
$user,
$form->get('password')->getData()
)
);
$URe->updateU($pass, $Varmail);
$Mai = new MailerController();
$Mai->sendEmail($mailer, $to, $sujet, $Message);
}
return $this->render('modifier_mdp/index.html.twig', [
'form' => $form->createView(),
]);
}
How can i solve it , And Thanks
In your updateU method, you are making a request to get, not update the data. It's better to use the ObjectManager to save the data, since you still have a updated instance of the Utilisateur object in the $user variable.
$user = $this->getDoctrine()->getManager()->getRepository(Event::class)->findOneBy(['email'=>$Varmail]);
$form = $this->createFormBuilder($user)->add('password', PasswordType::class)->getForm();
if ($form->isSubmitted() && $form->isValid()) {
// ...
$user->setPassword(
$userPasswordEncoder->encodePassword(
$user,
$form->get('password')->getData()
)
);
// save Utilisateur with new password
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
}

How to write unit test in symfony3

I want to know how to write standard unit test code for the below controller. I believe PHPUNIT is installed by default in symfony3 but I'm not sure how to execute it as well. Can someone guide me how to write testcontroller and execution command for symfony3 as well.
class RegistrationController extends Controller
{
/**
* #Route("/register", name="user_registration")
* #Security("has_role('ROLE_SUPER_ADMIN')")
*/
public function userAction(Request $request)
{
$user = new User();
$form = $this->createForm(UserType::class, $user);
$form->handleRequest($request);
if ($request->isMethod('POST') && $form->isValid()) {
$password = $this->get('security.password_encoder')
->encodePassword($user, $user->getPlainPassword());
$user->setPassword($password);
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
$this->get('app.mailer')->sendUserCredentials($user);
$this->addFlash('notice', 'An account is created');
}
return $this->render('masteradmin/account/addUser.html.twig',
array('form' => $form->createView())
);
}
/**
* #Route(
* "/user/edit/{id}",
* requirements={"id" = "\d+"},
* name="user_edit"
* )
*/
public function editUserAction(User $user, Request $request)
{
if (!$this->get('security.authorization_checker')->isGranted('ROLE_SUPER_ADMIN')) {
throw new AccessDeniedException();
}
$em = $this->getDoctrine()->getManager();
$id = $request->attributes->get('id');
if (!$user = $em->getRepository('AppBundle:User')->findOneById($id)) {
throw new NotFoundHttpException('user details not found.');
}
$form = $this->createForm(UserType::class, $user)
->remove('plainPassword');
$form->handleRequest($request);
$data = $form->getData();
if ($form->isValid()) {
$em->persist($user);
$em->flush();
$this->addFlash('notice', 'Account information is updated');
return $this->redirectToRoute('user_list');
}
return $this->render(
'masteradmin/account/editUser.html.twig', ['form' => $form->createView()]
);
}

Array Collection persistence on symfony2

i'm using a event listener on the submit of a form where, i need to catch a xml file, open it and extract his contents, put it on an entity and add that to a collection from other entity.
right now this is works:
$builder->addEventListener(FormEvents::SUBMIT, function(FormEvent $event){
$entity = $event->getData();
if($entity){
$parent = $event->getForm()->getParent()->getData();
$gpx = $entity['gpx'];
if($gpx){
$xmlGpx = simplexml_load_file($gpx);
foreach ($xmlGpx->wpt as $pt) {
$point = new MonitoringPoint();
$point->setPoint(new \CrEOF\Spatial\PHP\Types\Geometry\Point((string) $pt['lat'], (string) $pt['lon']));
$point->setAltitude((float) $pt->ele);
$point->setDate(($pt->time->count() ? new \DateTime((string)$pt->time) : null ));
$point->setAccuracy((float) $pt->hdop);
$parent->addMonitoringPoint($point);
}
$fileName = $gpx->getClientOriginalName();
$directory = __DIR__.'/../../../../web/uploads/';
$date = new \DateTime();
$newFileName = md5($gpx->getClientOriginalName().$date->getTimestamp());
$gpx->move($directory, $fileName);
$fs = new Filesystem();
$fs->rename($directory.$fileName, $directory.$newFileName.'.gpx');
$parent->setGpx($newFileName.'.gpx');
}
}
});
$parent is an instance of Monitoring, if i open $parent i will see that the $point vars has been added on the collection monitoringPoints of the variable, and the gpx too.
but then i go so see the entity right before been persisted, inside newAction
$entity = new Monitoring($params);
$form = $this->createForm(new MonitoringType(), $entity, array(
'action' => $this->generateUrl('my_route'),
'method' => 'POST',
));
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
dump($entity);die;
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
}
and the collection is empty! but the gpx attribute contains the right value.
does the collection gets reseted?
i had to pass the points in to an array within the session, still think that was not the best option, but worked
$array = [];
foreach ($xmlGpx->wpt as $pt) {
$point = new MonitoringPoint();
$point->setPoint(new \CrEOF\Spatial\PHP\Types\Geometry\Point((string) $pt['lat'], (string) $pt['lon']));
$point->setAltitude((float) $pt->ele);
$point->setDate(($pt->time->count() ? new \DateTime((string)$pt->time) : null ));
$point->setAccuracy((float) $pt->hdop);
$point->setMonitoring($parent);
array_push($array, $point);
}
$session = new Session();
$session->getFlashBag()->add('array', $array);
in the newAction:
$em = $this->getDoctrine()->getManager();
$session = new Session();
$array = $session->getFlashBag()->get('array');
foreach($array[0] as $point) {
$point->setMonitoring($entity);
$entity->addMonitoringPoint($point);
}
$em->persist($entity);
$em->flush();
dont know why the array got reseted when it comes to the controller, cause i had setted the points in the entity during the submit

Call an entity method in a controller

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

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(....)
}
}

Resources