Home > OS >  How can I use a custom method in Symfony?
How can I use a custom method in Symfony?

Time:11-24

In my Data Repository I created a function:

  public function myData(){
    $data = $this->createQueryBuilder('data')
    ->leftJoin('data.fields', 'f')
    ->andWhere('f.name = :field')
    ->setParameter('field', 'company');
    $result = $qb->getQuery()->execute();
  
    return $result;
}

In my Controller I want to use this function:

class PagesController extends AbstractController
{

 public function __construct(EntityManagerInterface $em) {
    $this->em = $em;
}


/**
 * @Route("/page", name="page", methods={"POST", "GET"})
 */
public function page(Request $request)
{

$data = $this->em->getRepository('App\\Entity\\Data')->myData();

But I get the error message:

Undefined method 'myData'. The method name must start with either findBy, findOneBy or countBy!

CodePudding user response:

You should inject your repository in your controller:

class PagesController extends AbstractController
{

 public function __construct(private DataRepository $dataRepository) {}


/**
 * @Route("/page", name="page", methods={"POST", "GET"})
 */
public function page(Request $request)
{

$data = $this->dataRepository->myData();

CodePudding user response:

In your myData function your using variable called $data but then in $result your using $qb... You should change $data by $qb

  • Related