Custom query symfony2 - php

I am looking to display a list of students that have the same course ID as the current user (tutor).
http://snag.gy/VOHJ3.jpg Here is my database design.
<?php
namespace Simple\ProfileBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\HttpFoundation\Request;
class SecurityController extends Controller
{
public function loginAction(Request $request)
{
$session = $request->getSession();
// get the login error if there is one
if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
$error = $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
} else {
$error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
$session->remove(SecurityContext::AUTHENTICATION_ERROR);
}
return $this->render('SimpleProfileBundle:Security:login.html.twig', array(
// last username entered by the user
'last_username' => $session->get(SecurityContext::LAST_USERNAME),
'error' => $error,
));
}
public function dumpStringAction()
{
$findStudents = $this->getUser()->getCourses();
$results = $this->_em
->createQuery("SELECT * FROM user where")
->getResult();
return $results;
}
return $this->render('SimpleProfileBundle:Security:dumpString.html.twig', array(
'findstudents'=> $findStudents));
}
}
Anyone have any idea how i can do this ? I was thinking of a custom query however i am unsure how to do so?
Cheers

First of all if you want to use custom queries, you should do that by creating entities' repository.
Example:
Entity:
<?php
namespace YourName\YourBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* YourClass
*
* #ORM\Entity(repositoryClass="YourName\YourBundle\Entity\Repository\YourClassRepository")
* #ORM\Table(name="your_class")
*/
class YourClass
{
// your entity definition
}
Then you have to create entity repository class:
<?php
namespace YourName\YourBundle\Entity\Repository;
use Doctrine\ORM\EntityRepository;
/**
* YourClassRepository
*/
class YourClassRepository extends EntityRepository
{
public function getStudentsByCourseID($courseId)
{
$qb = $this->_em->createQueryBuilder();
$qb
->select('student')
->from('YourNameYourBundle:YourClass', 'student')
->leftJoin('YourNameYourBundle:Course', 'course')
->where('course.id == :courseId');
$qb->setParameter('courseId', $courseId);
return $qb->getQuery()->getArrayResult();
}
Then you can call your custom query in your controller:
<?php
namespace Simple\ProfileBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\HttpFoundation\Request;
class SecurityController extends Controller
{
public function loginAction(Request $request)
{
// your code here...
}
public function yourAction($courseID)
{
$repo = $this->getDoctrine()->getRepository('YourNameYourBundle:YourClass');
$students = $repo->getStudentsByCourseID($courseID);
return [
'students' => $students
];
}
}
I think that's what you need.

Related

Class "illuminate\Support\Facades\Storage" not found

I am developing an application in laravel and when I perform the test with insomnia (post), it presents the following "Class illuminate\Support\Facades\Storage" not found .
follow my code below
WarningController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use illuminate\Support\Facades\Storage;
use illuminate\Support\Facades\Validator;
use App\Models\Warning;
use App\Models\Unit;
class WarningController extends Controller
{
public function addWarningFile(Request $request)
{
$array = ['error' => ''];
$validator = validator::make($request->all(), [
'photo' => 'required|file|mimes:jpg,png'
]);
if (!$validator->fails()) {
$file = $request->file('photo')->store('public');
$array['photo'] = asset(Storage::url($file));
} else {
$array['error'] = $validator->errors()->first();
return $array;
}
return $array;
}
}
Validator.php
<?php
namespace Illuminate\Support\Facades;
class Validator extends Facade
{
/**
* Get the registered name of the component.
*
* #return string
*/
protected static function getFacadeAccessor()
{
return 'validator';
}
}

Symfony login form — Fatal error: Call to a member function get() on null

I'm trying to load some method (which creates a login form for me) from one source controller into another one.
Here is my source SecurityController:
namespace ImmoBundle\Controller\Security;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use ImmoBundle\Entity\User;
use ImmoBundle\Form\Type\LoginType;
class SecurityController extends Controller
{
/**
* #Route("/login", name="login")
*/
public function loginAction(Request $request)
{
$parametersArray = $this->loadForm($request);
return $this->render(
'ImmoBundle::Security/login.html.twig',
array(
'login_form' => $parametersArray['form']->createView(),
'error' => $parametersArray['error'],
'last_email' => $parametersArray['lastEmail'],
)
);
}
public function loadForm($request)
{
$user = new User();
$form = $this->createForm(LoginType::class, $user);
$form->handleRequest($request);
$authenticationUtils = $this->get('security.authentication_utils');
$error = $authenticationUtils->getLastAuthenticationError();
$lastEmail = $authenticationUtils->getLastUsername();
$parametersArray['form'] = $form;
$parametersArray['error'] = $error;
$parametersArray['lastEmail'] = $lastEmail;
return $parametersArray;
}
}
Then I've defined my source controller as a Service in services.yml:
login_form_service:
class: ImmoBundle\Controller\Security\SecurityController
My target controller looks like this:
namespace ImmoBundle\Controller\Pages;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
class ListingPageController extends Controller
{
/**
* #Route("/id/{listingId}", name="idPage", requirements={
* "listingId": "\d+"
* })
*/
public function loadIdAction($listingId, Request $request)
{
$yourController = $this->get('login_form_service');
print_r($yourController->loadForm($request));
return $this->render(
'ImmoBundle::page.html.twig',
array()
);
}
}
But instead of an object in line
print_r($yourController->loadForm($request))
I've got this error: Fatal error: Call to a member function get() on null
What am I doing wrong?
You SecurityController registered as service "login_form_service" don't know about service_container
Try:
login_form_service:
class: ImmoBundle\Controller\Security\SecurityController
calls:
- [setContainer, [#service_container]]

Class App\Repositories does not exist

I'm trying to use a Repository, but I'm getting this error:
Class App\Repositories\CategoryRepository does not exist
This is my CategoryRepository.php
<?php
namespace App\Repositories;
class SubCate
{
/**
* Get all of the tasks for a given user.
*
* #param User $user
* #return Collection
*/
public function getCategories(){
$categories=\App\category::where('parent_id',0)->get();//united
$categories=$this->addRelation($categories);
return $categories;
}
}
?>
And this is my controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
use App\Product;
use App\Category;
use App\Repositories\CategoryRepository;
class ProductController extends Controller
{
//
public function __construct(CategoryRepository $categoryRepository)
{
$this->categoryRepository = $categoryRepository;
}
public function index(Request $request)
{
$subcate = new SubCate;
try {
$allSubCategories=$subcate->getCategories();
} catch (Exception $e) {
//no parent category found
}
return view('welcome', [
'allSubCategories' => $allSubCategories,
]);
}
}
What is wrong?
Your category repository class name is
class SubCate
but you are using
use App\Repositories\CategoryRepository; .
So, change your class name to CategoryRepository

Symfony 2: Error: Call to a member function has() on a non-object from Controller

Here's my Controller A:
<?php
namespace MonitoringBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Doctrine\ORM\Query\ResultSetMapping;
use MonitoringBundle\Entity\MarketplaceShop;
use MonitoringBundle\Controller\BController;
class AController extends Controller
{
/**
* #Route("/A")
* #Template()
*/
public function AAction()
{
$B = new BController;
$response = $B->BAction();
return $this->render('MonitoringBundle:Default:index.html.twig', array('BVar' => $response));
}
}
?>
And thats Controller B:
<?php
namespace MonitoringBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Doctrine\ORM\Query\ResultSetMapping;
use MonitoringBundle\Entity\MarketplaceShop;
class BController extends Controller
{
/**
* #Route("/B")
* #Template()
*/
public function BAction()
{
$id = 'A2WPX7PK44TEBQ';
$em = $this->getDoctrine()->getManager();
$shop = $em->getRepository('MonitoringBundle:MarketplaceShop')
->findOneByUniqueShopId($id);
if (!$shop) {
// do something
return new Response('Shop does not exist.');
} else {
// do something else
return new Response('Shop exists!');
}
}
}
?>
When I call http://example.com/B, all is fine and I get a response:
Shop does not exist.
But when I call http://example.com/A, I get an error:
Error: Call to a member function has() on a non-object
500 Internal Server Error - FatalErrorException
Stack Trace:
in vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Controller/Controller.php at line 291
public function getDoctrine()
{
if (!$this->container->has('doctrine')) {
throw new \LogicException('The DoctrineBundle is not registered in your application.');
}
Why does it work with /B/ but not with /A/?
A solution is to declare your B controller as service and call it in A controller through $this->container->get('controllerB');
In services.yml:
controllerB:
class: MonitoringBundle\Controller\BController
arguments:
entity_manager: "#doctrine.orm.entity_manager"
class AController extends Controller
{
/**
* #Route("/A")
* #Template()
*/
public function AAction()
{
$B = $this->container->get('BController');
$response = $B->BAction();
return $this->render('MonitoringBundle:Default:index.html.twig', array('BVar' => $response));
}
}
class BController extends Controller {
/**
* #var EntityManager
*/
protected $entityManager;
/**
* Constructor
* #param $entityManager
*/
public function __construct($entityManager)
{
$this->entityManager = $entityManager;
}
/**
* #Route("/B")
* #Template()
*/
public function BAction()
{
$id = 'A2WPX7PK44TEBQ';
$shop = $this->entityManager->getRepository('MonitoringBundle:MarketplaceShop')
->findOneByUniqueShopId($id);
if (!$shop) {
// do something
return new Response('Shop does not exist.');
} else {
// do something else
return new Response('Shop exists!');
}
}
}
In addition to the #Christian Bujoreau answer, you can use forward method: http://symfony.com/doc/current/book/controller.html#forwarding-to-another-controller
public function AAction()
{
$response = $this->forward('MonitoringBundle:BController:BAction', array(
// 'some_variable' => $some_variable,
));
...
return $response;
}

SymBlog: Undefined method. The method name must start with either findBy or findOneBy

I am currently working with Symfony2's Part 4 OF The SymBlog project
I am getting this ERROR message:
Undefined method 'getLatestPosts'. The method name must start with either findBy
or findOneBy!500 Internal Server Error - BadMethodCallException
This is my PostRepository Class:
<?php
namespace BLog\BlogBundle\Entity; use Doctrine\ORM\EntityRepository;
class PostRepository extends EntityRepository {
public function getLatestPosts($limit = null) {
$qp = $this->createQueryBuilder('p')
->select('p')
->addOrderBy('p.created', 'DESC');
if (false === is_null($limit)) {
$qp->setMaxResults($limit);
}
return $qp->getQuery()
->getResult();
}
}
This is the Controller's page Action method:
<?php
namespace Blog\BlogBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class DefaultController extends Controller {
public function indexAction() {
$em = $this->getDoctrine()
->getEntityManager();
$posts = $em->getRepository('BlogBundle:Post')
->getLatestPosts();
return $this->render('BlogBundle:Default:home.html.twig', > >array(
'posts' => $posts
));
}
...
}
This is a sample of my ../../../Entity/Post code:
<?php
namespace Blog\BlogBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity(repositoryClass="Blog\BlogBundle\Entity\PostRepository")
* #ORM\Table(name="post")
* #ORM\HasLifecycleCallbacks
*/
class Post {
....
...
..
/**
* #ORM\Column(type="text")
*/
protected $post;
...
...
I also tried all solutions in this post by ScoRpion
What is THE PROBLEM here ???
No need to use repository here. If you are fetching data directly by refering entity then you should use findBy or findOneBy posted by your database field name.
Please Try to do following way:
namespace Blog\BlogBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class DefaultController extends Controller {
public function indexAction() {
$posts = this->forward('BlogBundle:Post:getLatestPosts', array(), array());
return $this->render('BlogBundle:Default:home.html.twig', > >array(
'posts' => $posts
));
}
...
}

Categories