How can I transmit the $exercise parameter without overriding it? - php

Here is the function that find the first exercise with the certain lessonid
public function exerciseAction($lessonid, $exercise)
{
$em = $this->getDoctrine()->getEntityManager();
$exercise = $em->getRepository('PrezentariPrezentariBundle:Exercise')->findOneByLesson($lessonid);
return $this->render('PrezentariPrezentariBundle:Page:exercise.html.twig', array(
'exercise' => $exercise,
'lessonid' => $lessonid,
));
}
Here I try to implement a function to al the exercises one by one
public function exercisePagerAction($exercise)
{
$em = $this->getDoctrine()->getEntityManager();
$nextExercise= $em->getRepository('PrezentariPrezentariBundle:Exercise')->getNext($exercise);
return $this->render('PrezentariPrezentariBundle:Page:exercise.html.twig', array(
'exercise' => $nextExercise,
));
}

Your problem is here:
$nextExercise= $em->getRepository('PrezentariPrezentariBundle:Exercise')->getNext($exercise);
You need to find sth.
$nextExercise= $em->getRepository('PrezentariPrezentariBundle:Exercise')->findOneById($exercise)->getNext();

Related

Symfony controller code

Hi I just started a project with Symfony and I think I am doing something wrong. Right now I want to a create simple page with table and filters so I created controller for it.
/**
* #Route("/")
*/
class HomeController extends Controller {
public function index(Request $request) {
//Form to add new documents
$form = $this->newForm();
$form->handleRequest($request);
$user = $this->getDoctrine()->getRepository(User::class)->find($this->getUser());
//Gets all user documents
$files = $user->getDocuments();
//Gets all categories
$categories = $this->getDoctrine()->getRepository(Category::class)->findAll();
//Adds new document to database
if($form->isSubmitted() && $form->isValid()) {
$article = $form->getData();
$article->setUser($this->getUser());
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($article);
$entityManager->flush();
return $this->redirectToRoute('index');
}
return $this->render('home/home.html.twig', [
'files' => $files,
'categories' => $categories,
'form' => $form->createView(),
]);
}
}
This controller just displays documents in table and categories in navigaton. So then to add category filters I just made new function:
/**
* #Route("/{categoryId}")
*/
public function categories(request $request, $categoryId)
{
$form = $this->newForm();
$form->handleRequest($request);
$user = $this->getDoctrine()->getRepository(User::class)->find($this->getUser());
$categories = $this->getDoctrine()->getRepository(Category::class)->findAll();
$category = $this->getDoctrine()->getRepository(Category::class)->findOneBy(["id" => $categoryId]);
$categoryFiles = $this->getDoctrine()->getRepository(Document::class)->categoryFiles($category, $user);
if($form->isSubmitted() && $form->isValid()) {
$article = $form->getData();
$article->setUser($this->getUser());
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($article);
$entityManager->flush();
return $this->redirectToRoute('index');
}
return $this->render('home/home.html.twig', [
'files' => $categoryFiles,
'categories' => $categories,
'form' => $form->createView(),
]);
}
Everything works, but I have to repeat same code for categories and forms in all of my functions. Thank you for your help.
I suggest you use services, a Service can be (Business Rules, Helpers, MicroServices, etc.), the most import is the Business Rules, generally should exists a service by entity
$user = $this->getUser();
$info = $this->get(HomeService::class)->getInfo($user, null);
// TODO FORM
return $this->render('home/home.html.twig', [
'files' => $info['files'],
'categories' => $info['categories'],
'form' => $form->createView()
]);
Second Action
$user = $this->getUser();
$info = $this->get(HomeService::class)->getInfo($user, $categoryId);
// TODO FORM
return $this->render('home/home.html.twig', [
'files' => $info['category_files'],
'categories' => $info['categories'],
'form' => $form->createView()
]);
HomeService->info(), it will process all
Symfony Service
Create abstract class, then extend from child controllers. You can read also: http://php.net/manual/en/language.oop5.late-static-bindings.php
It's just one way, can be more ways!

symfony setData() error

I'm trying to put a value in form created by formbuilder, i took the value from another twig file by the request, and i'm trying to use $form->setData(array('field'=>value));
Code controller:
public function ModifierGestionMatchAction(Request $request)
{
$id = $request->get('id');
$idmatch = $request->get('idm');
$em = $this->getDoctrine()->getManager();
$type = $em->getRepository("MainBundle:ReservationGestionStock")
->find($id);
$match = $em->getRepository("MainBundle:Match")
->findOneByid($idmatch);
$form = $this->createForm(ReservationGestionStockType::class, $type);
$form->setData(array('hotel'=>null));
$form->setData(array('match'=>$match));
$form->handleRequest($request);
if($form->isValid()){
$em->persist($type);
$em->flush();
return $this->redirectToRoute("ReservationGestionStockAfficher");
}
return $this->render('MainBundle:GestionStock:GestionStockModifierMatch.html.twig',
array(
"form" => $form->createView(),
"match" => $match
));
}
my form code:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('hotel',HiddenType::class)
->add('match',HiddenType::class)
->add('nb')
->add('nbr')
->add('Valider', SubmitType::class)
->add('Reset', ResetType::class);
}
Notice: the hotel and match are 2 entitys, i'm having problem with setData() for match, i tried to setdata of idmatch but its the same problem," the form isnt valid "
$form->get('hotel')->setData('John');
$form->get('match')->setData($match);
After submission just do that,
$type = $form->getData(); $type->setHotel($hotel); $type->setMatch($match); then persist and flush $type
i did this and its working, but i think it's so weird ... anyway thanks everyone for replying me.
if ($form->isSubmitted()) {
$gestion= new ReservationGestionStock();
$gestion->setMatch(null);
$gestion->setNb($form->getData()->getNb('nb'));
$gestion->setNbr($form->getData()->getNbr('nbr'));
$gestion->setHotel($hotel);
$em->persist($hotel);
$em->flush();
return $this->redirectToRoute("ReservationGestionStockAfficher");
}

Symfony2, How do I perform a database retrieve in Doctrine with a drop down list form?

I have a form that will perform a search action with a drop down list of choices of category to search. The drop down list are subjects to search by. So:
Search by:
1) Invoice #
2) Tracking #
3) BL #
Then enter in the value and submit to search.
I have my form:
// src Bundle\Form\Type\SearchType.php
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('kind', 'choice', array(
'choices' => array(
'invoice' => 'Invoice #',
'trackingno' => 'Tracking Number'
'blno' => 'BL #',
),
'label' => 'Search by: '
))
->add('value', 'text', array(
'label' => false
))
->add('Submit','submit');
}
With this function in the controller:
public function getForm() {
$form = $this->createForm(new SearchType(), array(
'action' => $this->generateUrl('search_view'),
'method' => 'POST'
) );
return $form;
}
With the action going to 'search_view' function:
/**
* #param Request $request
* #Route("/results/", name="search_view")
*/
public function searchAction(Request $request) {
$kind = $request->get('kind');
$value = $request->get('value');
$em = $this->getDoctrine()->getManager();
$findCfs = $em->getRepository("CFSBundle:Cfs")
->searchCfs($kind, $value);
return $this->render("CFSBundle:Search:index.html.twig", array(
'results' => $findCfs
));
}
My problem is I do not where to go to perform the database retrieval base on the category. This is what I have in the repository:
public function searchCfs($kind, $value) {
$query = $this->getEntityManager()
->createQuery('
SELECT
c.blno, m.ctrno, c.carrier, m.refno
FROM
CFSBundle:Cfs c
LEFT JOIN
cfs.refno m
WHERE
:kind LIKE :value
')->setParameter("kind", $kind)
->setParameter("value", $value);
try {
return $query->getResult();
} catch(\Doctrine\ORM\NoResultException $e) {
return null;
}
}
Of course this isn't working. I thought about creating different queries for each category and have the conditions submit according to its category, but I was wondering if there was one simple solution to this?
I'd advise using the QueryBuilder class when writing a query such as this, rather than writing DQL directly.
You could then do something like the following in your repository:
const KIND_INVOICE_NO = 'invoice';
const KIND_TRACKING_NO = 'tracking';
const KIND_BL_NO = 'blno';
public function searchCfs($kind, $value) {
$queryBuilder = $this->createQueryBuilder('c')
->select('c.blno, m.ctrno, c.carrier, m.refno')
->leftJoin('cfs.refno', 'm');
if ($kind === self::KIND_INVOICE_NO) {
$queryBuilder->where('c.invoiceno = :queryValue');
} elseif ($kind === self::KIND_TRACKING_NO) {
$queryBuilder->where('m.ctrno = :queryValue')
} elseif ($kind === self::KIND_BL_NO) {
$queryBuilder->where('c.blno = :queryValue')
}
$queryBuilder->setParameter('queryValue', $value);
$query = $queryBuilder->getQuery();
try {
return $query->getResult();
} catch(\Doctrine\ORM\NoResultException $e) {
return null;
}
}

how to get single result using mongo odm?

i make a setting action in which i used doctrine query for getting single result but it returns null while data exist in database,how i get single result?here is my code:
public function settingsAction()
{
$id = (int) $this->params()->fromRoute('id', 0);
if (!$id) {
return $this->redirect()->toRoute('calendar', array(
'action' => 'create'
));
}
//echo $id;
//$calendar = $id;//$this->getCalendarTable()->getCalendar($id);
$calendar = $documentManager->getRepository('Calendar\Document\Calendar')->find($id);
$form = new CalendarForm();
$form->bind($calendar);
$form->get('submit')->setAttribute('value', 'Save');
$request = $this->getRequest();
if ($request->isPost()) {
$form->setInputFilter($calendar->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
//$this->getCalendarTable()->saveCalendar($form->getData());
return $this->redirect()->toRoute('calendar', array('action' => 'show', 'id' => $id));
}
}
return array(
'id' => $id,
'form' => $form,
);
}
You don't need to create a query to fetch by id as the DocumentRepository already provides this via it's find($id) method.
Just use the document manager to fetch the repository
$document = $documentManager->getRepository('FooDocument')->find($id);
You can also use the convenience method find($documentName, $id) directly on the document manager.
$document = $documentManager->find('FooDocument', $id);

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!

Categories