I try to use the functions TechParentInsert in the controller I am getting an error:
Attempted to call function "TechParentInsert" from namespace "TestyBundle\Controller".
500 Internal Server Error - UndefinedFunctionException
In controller I have:
"use TestyBundle\Repository\TechParentRepository;" when i've defined "TechParentInsert"
What am I doing wrong?
-----------------------------My CODE
Controller TestyController:
namespace TestyBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\ORM\Query\AST\Functions\ConcatFunction;
use Doctrine\ORM\EntityRepository;
use TestyBundle\Entity\Sort;
use TestyBundle\Form\SortType;
use TestyBundle\Repository\SortRepository;
use TestyBundle\Repository\TechParentRepository;
/**
* #Route("/testy")
*
*/
class TestyController extends Controller
{
/**
* (other actions )
*
*/
/**
* #Route(
* "/parent/{parent}", name="TEST_sort_new"
* )
*
* #Template
*/
public function TechParentNewAction( Request $request, int $parent = 0 )
{
$repo2 = $this->getDoctrine()->getRepository( 'TestyBundle:Sort' );
$sortNew = $repo2->findOneBy( ['zz' => 0]);
$sortNew->setParentString( $sortNew->getParentString( ) . (string) $sortNew->getId() );
$sortNew->setZz( 1 );
$newRecordID = $sortNew->getId();
$op1 = TechParentInsert( $newRecordID );
$em->persist( $sortNew );
$em->flush();
return $this->redirect( $this->generateUrl( 'TEST_sort' ) );
}
return [ 'data1' => $sortNew ];
}
}
Repository: TechParentRepository
<?php
namespace TestyBundle\Repository;
use TestyBundle\Entity\TechParent;
class TechParentRepository extends \Doctrine\ORM\EntityRepository
{
public function TechParentInsert( $idsort)
{
$parent = new TechParent();
$parent->setIdSorty( $idsort);
$parent->setIdParent( $idsort);
$parent->setIsOwn( TRUE);
$em = $this->getDoctrine()->getManager();
$em->persist($parent);
$em->flush();
return 1;
}
}
My entity: TechParent
<?php
namespace TestyBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* TechParent
*
* #ORM\Table(name="tech_parent")
* #ORM\Entity(repositoryClass="TestyBundle\Repository\TechParentRepository")
*/
class TechParent
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var int
*
* #ORM\Column(name="idSorty", type="integer")
*/
private $idSorty;
/**
* #var int
*
* #ORM\Column(name="idParent", type="integer")
*/
private $idParent;
/**
* #var bool
*
* #ORM\Column(name="isOwn", type="boolean")
*/
private $isOwn;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set idSorty
*
* #param integer $idSorty
*
* #return TechParent
*/
public function setIdSorty($idSorty)
{
$this->idSorty = $idSorty;
return $this;
}
/**
* Get idSorty
*
* #return int
*/
public function getIdSorty()
{
return $this->idSorty;
}
/**
* Set idParent
*
* #param integer $idParent
*
* #return TechParent
*/
public function setIdParent($idParent)
{
$this->idParent = $idParent;
return $this;
}
/**
* Get idParent
*
* #return int
*/
public function getIdParent()
{
return $this->idParent;
}
/**
* Set isOwn
*
* #param boolean $isOwn
*
* #return TechParent
*/
public function setIsOwn($isOwn)
{
$this->isOwn = $isOwn;
return $this;
}
/**
* Get isOwn
*
* #return bool
*/
public function getIsOwn()
{
return $this->isOwn;
}
}
When you're accessing a method from different class you have to use ClassName::method(), but in this case the TechParentRepository has dependecies for sure. Because of dependency injection, there's a best practice in Symfony to define repository as a service and then use it this way:
$techParentRepository = $this->get('tech_parent_repository ');
$techParentRepository->TechParentInsert();
Little advice - good practise also is to name classes uppercase, but methods lowercase, so public function techParentInsert($idsort) would be better.
Since autowiring in Symfony 2.8 and moreover Symfony 3.3 (May 2017) there is much cleaner way to pass dependencies to controller.
1. Controller
namespace TestyBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use TestyBundle\Repository\SortRepository;
use TestyBundle\Repository\TechParentRepository;
final class TestyController extends Controller
{
/**
* #var SortRepository
*/
private $sortRepository;
/**
* #var TechParentRepository
*/
private $techParentRepository;
public function __constructor(
SortRepository $sortRepository,
TechParentRepository $techParentRepository,
) {
$this->sortRepository = $sortRepository;
$this->techParentRepository = $techParentRepository;
}
public function TechParentNewAction(int $parent = 0)
{
$sortNew = $this->sortRepository->findOneBy([
'zz' => 0
]);
$sortNew->setParentString($sortNew->getParentString() . (string) $sortNew->getId());
$sortNew->setZz(1);
$newRecordID = $sortNew->getId();
$this->techParentRepository->TechParentInsert($newRecordID);
// redirect etc...
}
}
2. Controller services registration
# app/config/services.yml
services:
_defaults:
autowire: true
# PSR-4 autodiscovery
TestyBundle\:
resource: '../../src/TestyBundle' # located in /src/TestyBundle
And you are ready to go!
You can read about Symfony 3.3 dependency injection (in this case registering services in config and using it in controller) news in these 2 posts:
https://www.tomasvotruba.cz/blog/2017/05/07/how-to-refactor-to-new-dependency-injection-features-in-symfony-3-3/
https://symfony.com/blog/the-new-symfony-3-3-service-configuration-changes-explained
Related
I am using a service within twig like this
{{ count_service.getCount(term.getId) }}
I want the service to use a repository function, repository function
<?php
namespace AppBundle\Repository;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Mapping;
class SynonymRepository extends EntityRepository
{
public function getCount($termId)
{
$qbSynonymType = $this->getEntityManager()->createQueryBuilder();
$synonymTypes = $qbSynonymType->select('synonymType.id, synonymType.type')
->from('AppBundle:SynonymType', 'synonymType')
->getQuery()->getResult();
$qb = $this->getEntityManager()->createQueryBuilder();
$count = [];
$qb->select('count(synonym.synonymId)')
->from('AppBundle:Synonym','synonym');
foreach($synonymTypes as $type) {
$count[$type['type']] = $qb
->where('synonym.term = :termId')
->andWhere('synonym.synonymType = :type')
->setParameter('termId', $termId)
->setParameter('type', $type['id'])
->getQuery()->getSingleScalarResult();
}
$qbTerm = $this->getEntityManager()->createQueryBuilder()->from('AppBundle:Term', 'term');
$count['parent'] = "NaN";
$count['children'] = "NaN";
return $count;
}
}
My service.yml looks like this
synonymrepository:
class: Doctrine\ORM\EntityRepository
factory: ["#doctrine.orm.entity_manager", getRepository]
arguments:
- AppBundle\Entity\SynonymType
term_count:
class: AppBundle\Services\TermCount
arguments:
- "#synonymrepository"
And finally my service looks like this
<?php
namespace AppBundle\Services;
use AppBundle\Repository\SynonymRepository;
class TermCount
{
private $repository;
public function __construct()
{
$this->repository = new SynonymRepository();
}
public function getCount($termId)
{
return $this->repository->getCount($termId);
}
}
When running this I am getting the following error
Type error: Too few arguments to function Doctrine\ORM\EntityRepository::__construct(), 0 passed in /var/www/html/src/AppBundle/Services/TermCount.php on line 15 and exactly 2 expected
I assume this is happening because extending SynonymRepository with the EntityRepository requires EntityManagerInterface $em and Mapping\ClassMetadata $class. But I am not sure how pass them to EntityRepository.
I was using this answer to get me here, lost on how to actually implement the finall bit.
Thanks for helping.
UPDATE
Entity
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Table(name="synonym")
* #ORM\Entity(repositoryClass="AppBundle\Repository\SynonymRepository")
*/
class Synonym
{
/**
* #var int
* #ORM\Id()
* #ORM\Column(name="synonym_id", type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $synonymId;
/**
* #var Term
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Term", inversedBy="synonyms")
*/
protected $term;
/**
* #var SynonymType[]
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\SynonymType", inversedBy="synonyms")
*/
protected $synonymType;
/**
* #var int
* #ORM\Column(name="language_id", type="integer")
*/
protected $languageId;
/**
* #var string
* #ORM\Column(name="synonym", type="string", length=255)
*/
protected $synonym;
public function __construct()
{
// $this->synonymType = new ArrayCollection();
}
/**
* #return int
*/
public function getSynonymId(): int
{
return $this->synonymId;
}
/**
* #return Term
*/
public function getTerm(): Term
{
return $this->term;
}
/**
* #param int $termId
* #return Term
*/
public function setTerm(int $termId): Term
{
$this->term = $termId;
return $this->term;
}
/**
* #return SynonymType[]
*/
public function getSynonymType()
{
return $this->synonymType;
}
/**
* #param SynonymType $synonymType
* #return SynonymType
*/
public function setSynonymType(SynonymType $synonymType): SynonymType
{
$this->synonymType = $synonymType;
return $this->synonymType;
}
/**
* #return int
*/
public function getLanguageId(): int
{
return $this->languageId;
}
/**
* #param int $languageId
* #return Synonym
*/
public function setLanguageId(int $languageId): Synonym
{
$this->languageId = $languageId;
return $this;
}
/**
* #return string
*/
public function getSynonym(): string
{
return $this->synonym;
}
/**
* #param string $synonym
* #return Synonym
*/
public function setSynonym(string $synonym): Synonym
{
$this->synonym = $synonym;
return $this;
}
}
You need to use DI (Dependency injection) in your construct insted of using new cause as i see the erreur your SynonymRepository depends on other services
<?php
namespace AppBundle\Services;
use AppBundle\Repository\SynonymRepository;
class TermCount
{
private $repository;
public function __construct(SynonymRepository $synonymRepository)
{
$this->repository = $synonymRepository;
}
public function getCount($termId)
{
return $this->repository->getCount($termId);
}
}
When trying to get the default repository class for my entity Lesson I keep getting the following error:
Attempted to load class "LessonRepository" from namespace "DrumLessonBookingApp\DrumLessonBookingBundle\Repository".
Did you forget a "use" statement for another namespace?
I use the exact same method as a User entity which works perfectly fine.
The code for my controller is:
namespace DrumLessonBookingApp\DrumLessonBookingBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use DrumLessonBookingApp\DrumLessonBookingBundle\Entity\User;
use DrumLessonBookingApp\DrumLessonBookingBundle\Entity\Lesson;
use DrumLessonBookingApp\DrumLessonBookingBundle\Repository;
class LoginController extends Controller
{
public function displayAction()
{
return $this->render('DrumLessonBookingAppDrumLessonBookingBundle:Default:login.html.twig');
}
public function processloginAction(Request $request)
{
$doctrine = $this->getDoctrine()->getManager();
$email = $request->get('email');
$pwd = $request->get('pwd');
$user = $doctrine->getRepository('DrumLessonBookingAppDrumLessonBookingBundle:User')->findOneBy(array('email' => $email,'password' => $pwd));
if($user->getAdministrator() == 1)
{
$session = $this->get('session');
$session->set('loggedin', true);
$lessons = $doctrine->getRepository('DrumLessonBookingAppDrumLessonBookingBundle:Lesson')->findAll();
return $this->render('DrumLessonBookingAppDrumLessonBookingBundle:Default:dashboard.html.twig', array("lessons" => $lessons));
}
else {
return new Response('doctrine not working');
}
}
}
I am also having difficulty to generate a custom Respository class using doctrine so tried creating one myself for the User entity but symfny doesn't pick it up or recognise the custom method. See below:
namespace DrumLessonBookingApp\DrumLessonBookingBundle\Repository;
use Doctrine\ORM\EntityRepository;
use DrumLessonBookingApp\DrumLessonBookingBundle\Entity\User;
class UserRepository extends EntityRepository
{
public function loginUser($email, $password)
{
$entityM = $this->getEntityManager();
$dql = $entityM->createQuery(
'SELECT u FROM DrumLessonBookingAppDrumLessonBookingBundle:User u
WHERE u.email = :email
AND WHERE u.password = :pwd');
$dql->setParameter('email', $email);
$dql->setParameter('pwd', $password);
$user = $query->getResult();
return $user;
}
}
I have searched similar questions but cannot find a solution, someone please help!
My Lesson Entity
namespace DrumLessonBookingApp\DrumLessonBookingBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="lessons")
* #ORM\Entity(repositoryClass="DrumLessonBookingApp\DrumLessonBookingBundle\Repository\LessonRepository")
* */
class Lesson {
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* */
private $id;
/**
* #ORM\Column(type="date")
* */
private $date;
/**
* #ORM\Column(type="time")
* */
private $time;
/**
* #ORM\ManyToOne(targetEntity="User", inversedBy="lessons")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
* */
private $user;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set date
*
* #param \DateTime $date
*
* #return Lesson
*/
public function setDate($date)
{
$this->date = $date;
return $this;
}
/**
* Get date
*
* #return \DateTime
*/
public function getDate()
{
return $this->date;
}
/**
* Set time
*
* #param \DateTime $time
*
* #return Lesson
*/
public function setTime($time)
{
$this->time = $time;
return $this;
}
/**
* Get time
*
* #return \DateTime
*/
public function getTime()
{
return $this->time;
}
/**
* Set User
*
* #param object
* #return Lesson
* */
public function setUser(User $user)
{
$this->user = $user;
return $this;
}
/**
* Set User
*
*
* #return User
* */
public function getUser($user)
{
return $this->user;
}
}
There is nothing in my custom Lesson Repository but surely it should still find the methods such as findAll() etc from the entityRepository it extends
seems you have multiple questions for one answer
you need to reference the repositoryClass it in your Entity-class :
/**
* USER
*
* #ORM\Table(name="users")
* #ORM\Entity(repositoryClass="DrumLessonBookingApp\DrumLessonBookingBundle\Repository\UserRepository")
*/
class User
{
i guess you missing the same at your Lesson Entity.
You dont have to add a "use" statement then
Symfony is tormenting my head right now. I'm trying to get data from a table where the column associates a relationship with an id from another table. Thats my controller function:
/**
* #Route("/proposta/{id}", defaults={"id"=null})
*/
public function mostraAction($id) {
$model = $this->getDoctrine()->getManager();
$lista = $model->getRepository('AppBundle:Propostes')->find($id);
$em = $this->getDoctrine()->getManager();
$listaVotacions = $em->getRepository('AppBundle:Votacions')->findByIdProposta($id);
return $this->render(':Proposta:index.html.php',
array('lista'=>$lista,'listaVotacions'=>$listaVotacions));
}
That's not working, when I execute this function, my server falls and I get this error:
[ERROR] Built-in server terminated unexpectedly.
That's my class of Votacions:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Votacions
*
* #ORM\Table(name="votacions")
* #ORM\Entity(repositoryClass="AppBundle\Repository\VotacionsRepository")
*/
class Votacions
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="Propostes")
*/
private $idProposta;
/**
* #ORM\ManyToOne(targetEntity="Usuaris")
*/
private $idUsuari;
/**
* #var bool
*
* #ORM\Column(name="vot", type="boolean", nullable=true)
*/
private $vot;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set idProposta
*
* #param integer $idProposta
*
* #return Votacions
*/
public function setIdProposta($idProposta)
{
$this->idProposta = $idProposta;
return $this;
}
/**
* Get idProposta
*
* #return int
*/
public function getIdProposta()
{
return $this->idProposta;
}
/**
* Set idUsuari
*
* #param integer $idUsuari
*
* #return Votacions
*/
public function setIdUsuari($idUsuari)
{
$this->idUsuari = $idUsuari;
return $this;
}
/**
* Get idUsuari
*
* #return int
*/
public function getIdUsuari()
{
return $this->idUsuari;
}
/**
* Set vot
*
* #param boolean $vot
*
* #return Votacions
*/
public function setVot($vot)
{
$this->vot = $vot;
return $this;
}
/**
* Get vot
*
* #return bool
*/
public function getVot()
{
return $this->vot;
}
}
And this my repository Votacions:
namespace AppBundle\Entity;
use Doctrine\ORM\EntityRepository;
class VotacionsRepository extends EntityRepository
{
public function findByIdProposta($id)
{
return $this->getEntityManager()
->createQuery(
'SELECT * FROM AppBundle:Votacions WHERE idProposta ='.$id
)->getResult();
}
}
Someone could help me :(?
Thank you so much.
Carles
Call only one time the "GetDoctrine"
-> find your lista object
-> Access idProposta from $lista object
-> the id from Proposta Entity
public function mostraAction($id) {
$model = $this->getDoctrine()->getManager();
$lista = $model->getRepository('AppBundle:Votacions')->find($id);
$lista->getIdProposta()->getId();
//..
return $this->render(':Proposta:index.html.php',
array('lista'=>$lista,'listaVotacions'=>$listaVotacions));
}
i'm new in symfony, i created a small DB schema attached:
Email Class:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Email
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="AppBundle\Entity\EmailRepository")
*/
class Email extends Service
{
/**
* #var string
*
* #ORM\Column(name="emailAddress", type="string", length=255)
*/
private $emailAddress;
/**
* Set emailAddress
*
* #param string $emailAddress
*
* #return Email
*/
public function setEmailAddress($emailAddress)
{
$this->emailAddress = $emailAddress;
return $this;
}
/**
* Get emailAddress
*
* #return string
*/
public function getEmailAddress()
{
return $this->emailAddress;
}
}
and my service class:
<?php
namespace AppBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* Service
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="AppBundle\Entity\ServiceRepository")
* #ORM\InheritanceType("JOINED")
* #ORM\DiscriminatorColumn(name="type", type="string")
* #ORM\DiscriminatorMap({"newsletter" = "Newsletter", "email" = "Email", "service" = "Service"})
*
*/
class Service
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="serviceTitle", type="string", length=255)
*/
private $serviceTitle;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set serviceTitle
*
* #param string $serviceTitle
*
* #return Service
*/
public function setServiceTitle($serviceTitle)
{
$this->serviceTitle = $serviceTitle;
return $this;
}
/**
* Get serviceTitle
*
* #return string
*/
public function getServiceTitle()
{
return $this->serviceTitle;
}
/**
* #ORM\ManyToOne(targetEntity="Service", inversedBy="children")
*/
private $parent;
/**
* #ORM\OneToMany(targetEntity="Service", mappedBy="parent")
*/
private $children;
/**
* Constructor
*/
public function __construct()
{
$this->children = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Set parent
*
* #param \AppBundle\Entity\Service $parent
*
* #return Service
*/
public function setParent(\AppBundle\Entity\Service $parent = null)
{
$this->parent = $parent;
return $this;
}
/**
* Get parent
*
* #return \AppBundle\Entity\Service
*/
public function getParent()
{
return $this->parent;
}
/**
* Add child
*
* #param \AppBundle\Entity\Service $child
*
* #return Service
*/
public function addChild(\AppBundle\Entity\Service $child)
{
$this->children[] = $child;
return $this;
}
/**
* Remove child
*
* #param \AppBundle\Entity\Service $child
*/
public function removeChild(\AppBundle\Entity\Service $child)
{
$this->children->removeElement($child);
}
/**
* Get children
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getChildren()
{
return $this->children;
}
}
then i generate crud for email, it was working perfect, now i actually want to add two fields for service (SERVICE TITLE, and PARENT SERVICE)
what i did, i just opened email type form and added two fields for (service title and Parent service):
<?php
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class EmailType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('emailAddress')
->add('serviceTitle')
->add('parent')
;
}
after saving, when i create new email service browser return exception:
Catchable Fatal Error: Object of class AppBundle\Entity\Email could not be converted to string
right now i just add parent ID in text box (input type text) but actually i want to use (choice lise) from which user can set a parent service at the time of creating new service, and that choice list having all previously created services
add a __toString() method to your email class:
public function __toString()
{
return $this->emailAddress;
}
I have read through various solutions for this issue but none seem to work. I really want to know what is at the heart of this issue. I am going to list exactly what I did since it is relatively simple and I can't understand what I am missing.
So I have created a simple database with a table person and I am trying to generate CRUD with bootstrap which I get working fine. My issue is when I try to get jquery plugin to work with autocomplete. Next thing I add a repository to handle my query and that's when I get the Symfony2 Undefined method 'findLikeFullnameArray' message. I am trying to use just annotations so if there is something wrong in my process please let me know.
Here are my commands:
Create Bundle
app/console generate:bundle --bundle-name=CompanyNameofBundle --format=annotation
Bundle namespace: Company/nameofBundle
Do you want to generate the whole directory structure: yes
Do you confirm generation: return
Confirm automatic update of your Kernel: yes
Confirm automatic update of the Routing: yes
Create entities with crud
app/console generate:bundle --bundle-name=CompanyNameofBundle --format=annotation
Bundle namespace: Company/nameofBundle
Do you want to generate the whole directory structure: yes
Do you confirm generation: return
Confirm automatic update of your Kernel: yes
Confirm automatic update of the Routing: yes
app/console doctrine:mapping:import --force CompanyNameofBundle xml
app/console doctrine:generate:entities CompanyNameofBundle
app/console generate:doctrine:crud –entity=CompanyNameofBundle:Entityname --format=annotation --with-write –no-interaction
I then create my SearchController:
namespace Company\NameofBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Company\NameofBundle\Form\JqueryType;
use Company\NameofBundle\Form\SearchType;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Company\NameofBundle\Entity\Person;
/**
* Search controller.
*
* #Route("/search")
*/
class SearchController extends Controller
{
/**
* #Route("/", name="search")
* #Template()
*/
public function indexAction()
{
$form = $this->createForm(new SearchType(), null, [
'action' => '',
'method' => 'POST'
]);
return array(
'form' => $form->createView(),
);
}
/**
* #Route("/person_search", name="person_search")
* #Template()
*
* #param Request $request
*
* #return array
*/
public function searchPersonAction(Request $request)
{
$q = $request->get('term');
$em = $this->getDoctrine()->getManager();
$results = $em->getRepository('CompanyNameofBundle:Person')->findLikeFullname($q);
return array('results' => $results);
}
/**
* #Route("/person_get", name="person_get")
*
* #param $id
*
* #return Response
*/
public function getPersonAction($id)
{
$em = $this->getDoctrine()->getManager();
$book = $em->getRepository('CompanyNameofBundle:Person')->find($id);
return new Response($book->getFullname());
}
/**
* #Route("/jquery", name="jquery")
* #Template()
*/
public function jqueryAction()
{
$form = $this->createForm(new JqueryType(), null, [
'action' => '',
'method' => 'POST'
]);
return array(
'form' => $form->createView(),
);
}
/**
* #Route("/jquery_search/{phrase}", name="jquery_search")
*
* #param string $phrase
*
* #return JsonResponse
*/
public function searchJqueryAction($phrase)
{
$em = $this->getDoctrine()->getManager();
$results = $em->getRepository('CompanyNameofBundle:Person')->findLikeFullnameArray($phrase);
return new JsonResponse($results);
}
}
Person Entity:
<?php
namespace Company\NameofBundle\Person;
use Doctrine\ORM\Mapping as ORM;
/**
* Person
* #ORM\Table()
* #ORM\Entity(repositoryClass="Company\NameofBundle\Entity\Repository\PersonRepository")
*/
class Person
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="fullname", type="string", length=255)
*/
private $fullname;
/**
* #var string
*
* #ORM\Column(name="email", type="string", length=255)
*/
private $email;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set fullname
*
* #param string $fullname
* #return Person
*/
public function setFullname($fullname)
{
$this->fullname = $fullname;
return $this;
}
/**
* Get fullname
*
* #return string
*/
public function getFullname()
{
return $this->fullname;
}
/**
* Set email
*
* #param string $email
* #return Person
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
}
Lastly PersonRepository
<?php
namespace Company\NameofBundle\Entity\Repository;
use Doctrine\ORM\EntityRepository;
class PersonRepository extends EntityRepository
{
public function findLikeFullnameArray($fullname)
{
return $this->createQueryBuilder('person_repository')
->where('person_repository.fullname LIKE :name')
->setParameter('name', '%' . $fullname . '%')
->getQuery()
->getArrayResult();
}
}
In just in case here is my app/config/routing.yml
company_nameofbundle:
resource: "#CompanyNameofBundle/Controller/"
type: annotation
prefix: /
Thanks in advance!
In a first time, you should have a look on the documentation to have a repository like this :
http://symfony.com/doc/current/book/doctrine.html
// src/AppBundle/Entity/Product.php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="AppBundle\Entity\ProductRepository")
*/
class Product
{
//...
}
In a second time, you have to check in case of xml format you have put
<entity name="Acme\StoreBundle\Entity\Product" repository-class="Acme\StoreBundle\Entity\ProductRepository">
You cannot have a mix of annotation, xml or yml format to shape an entity in Symfony 2, remove all the unnecessary files.