Symfony -undefined method named "render" of class - symfony

im new to symfony framework. it raises render error. i tried all suggestions
#App/default/index.html.twig
AppBundle:default:index.html.twig
default/index.html.twig
routing.yml
app:
resource: "#AppBundle/Controller/"
type: annotation
lucky_number:
path: /lucky/number/{count}
defaults: { _controller: AppBundle:Lucky:number }
LuckyController.php
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class LuckyController
{
/**
* #Route("/lucky/number/{count}")
*/
public function numberAction($count)
{
$number = rand(0, 100);
$html = $this->render('#App/default/index.html.twig','number'=>$number);
//$html = $this->container->get('templating')->render('AppBundle:default:index.html.twig',array('number' => $number));
//$html = $this->container->get('templating')->render('default/index.html.twig',array('number' => $number));
return new Response($html);
}
}
Error:
Attempted to call an undefined method named "render" of class
"AppBundle\Controller\LuckyController".

You forgot to extend your controller class with the symfony controller.
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class LuckyController extends Controller // <-- HERE
{
/**
* #Route("/lucky/number/{count}")
*/
public function numberAction($count)
{
$number = rand(0, 100);
return $this->render('AppBundle:default:index.html.twig',array('number' => $number));
}
}

Related

symfony6 - defining and using services.yaml in third part bundle

I'm making simple "MyCoreBundle" (MystertyCoreBundle) using symfony6.1 how to make bundle's doc.
I defined my bundle class vendor/mysterty/core-bundle/CoreBundle.class
<?php
namespace Mysterty\CoreBundle;
use Symfony\Component\HttpKernel\Bundle\AbstractBundle;
class MystertyCoreBundle extends AbstractBundle
{
}
I defined some parameters and configuration in vendor/mysterty/core-bundle/config/services.yaml as defaults :
services:
Mysterty\CoreBundle\Controller\CoreController:
public: true
calls:
- method: setContainer
arguments: ["#service_container"]
parameters:
app.admin_email: "mymailATserver.com"
Then I made simple controller in vendor/mysterty/core-bundle/src/Controller/CoreController.php:
<?php
namespace Mysterty\CoreBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Contracts\Translation\TranslatorInterface;
class CoreController extends AbstractController
{
#[Route('/', name: 'mty_default')]
public function indexNoLocale(): Response
{
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
$supportedLangs = explode('|', $this->getParameter('app.supported_locales'));
$lang = in_array($lang, $supportedLangs) ? $lang : $supportedLangs[0];
return $this->redirectToRoute('mty_home', ['_locale' => $lang]);
}
Finally, i added the bundle's routes to \config\routes.yaml
mysterty_core:
resource: "../vendor/mysterty/core-bundle/src/Controller/CoreController.php"
type: annotation
prefix: /
Here is the error i have on http://127.0.0.1:8000/ :
"Mysterty\CoreBundle\Controller\CoreController" has no container set, did you forget to define it as a service subscriber?
I try to make a shared bundle with default actions and components for all my symfony projects.
Solution (thx to helpers)
define loadExtension function in MyOwnBundle.php :
<?php
namespace MyOwn\MyOwnBundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symfony\Component\HttpKernel\Bundle\AbstractBundle;
class MyOwnBundle extends AbstractBundle
{
public function loadExtension(array $config, ContainerConfigurator $container, ContainerBuilder $builder): void
{
// load an XML, PHP or Yaml file
$container->import('../config/services.yaml');
}
}
It looks like Symfiony could not autoconfigure your controller. Try adding the #[AsController] attribute to your controller classes or add autoconfigure: true to your controller service definition in your services.yaml

Eventproblem Too few arguments to function

i have a problem with my Testproject, i tray to make Event, the function of this event is following, when the controller call the row with id 18 from the datebase, it will to call/dispach event, this event have to send email to a Email Adress.
the problem, i cannot call this event from my eventlistener, because i get the wrong:
Too few arguments to function App\customEvents\EmailEvent::SendEMail(), 0 passed in C:\xampp\htdocs\Authentication\src\EventListener\EmailListener.php on line 15 and exactly 1 expected
Controller:
namespace App\Controller;
use App\Entity\Posts;
use App\Repository\PostsRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class EventoController extends AbstractController
{
#[Route('/evento', name: 'app_evento')]
public function index(PostsRepository $Posts, EventDispatcherInterface $eventDispatcher): Response
{
$todo=$Posts->find(18);
$sendEmail=new \App\customEvents\EmailEvent;
$eventDispatcher->dispatch($sendEmail, \App\customEvents\EmailEvent::NAME);
return $this->render('evento/index.html.twig', [
'getdaten' => $todo,
]);
}
}
EmailListener
<?php
namespace App\EventListener;
use App\customEvents\EmailEvent;
use Symfony\Component\Mailer\MailerInterface;
class EmailListener
{
public function sendemailaktive( EmailEvent $MeinEmailEvent)
{
$MeinEmailEvent->SendEMail();
}
}
EmailEvent
<?php
namespace App\customEvents;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpFoundation\Request;
class EmailEvent extends EventDispatcher
{
public const NAME = 'send.email';
public function SendEMail(MailerInterface $mailer)
{
$email = (new Email())
->from('hello#asdasd.com')
->to('spam#muhkas.com')
->subject('Email From Send!')
->text('Sending emails is fun again!')
->html('<p>See Twig integration for better HTML integration!</p>');
$mailer->send($email);
}
}

Symfony Route. Can't set annotations

I can't understand, if i create crud controller with
bin/console make:crud all routes work from controller
like
/**
* #Route("/", name="product_index", methods="GET")
*/
public function index(ProductRepository $productRepository): Response
{
return $this->render('product/index.html.twig', ['products' => $productRepository->findAll()]);
}
.
If i create controller with bin/console make:controller
and define controller with annotation by myself they don't work
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use JMS\Serializer\SerializerBuilder;
use Symfony\Component\HttpFoundation\JsonResponse;
use App\Entity\Product;
use App\Repository\ProductRepository;
use JMS\Serializer\SerializationContext;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
class FirstApiController extends AbstractController
{
/**
*
* #Route("/first_api", name="first_api")
*/
public function index(ProductRepository $productRepository)
{
$data = $productRepository->findAll();
$serializer = SerializerBuilder::create()->build();
# $jsonContent = $serializer->serialize($data, 'json');
$jsonContent = $serializer->serialize($data, 'json', SerializationContext::create()->setGroups(array('details')));
$response = JsonResponse::fromJsonString($jsonContent);
return $response;
}
/*
* #Route("/first_api/send", name="send")
*
*/
public function send()
{
$a = "text";
return $a;
}
}
Why that route doesn't work
#Route("/first_api/send", name="send") ?
In routes.yaml i wrote nothing, just empty file.
I used wrong syntax !I used
/* <-- the error is here
* #Route("/first_api/send", name="send")
*
*/
I need to use
/** <-- i nee two "*"
* #Route("/first_api/send", name="send")
*
*/
public

No route found for "GET /home"

I am using Symfony 3.4.3.
This is my routing in
app/config/routing.yml:
blog:
resource: "#BlogBundle/Controller/"
type: annotation
this is my controller from BlogBundle/Controller/DefaultController.php
<?php
namespace BlogBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
/**
* #Route("/home", name="home_route")
*/
class DefaultController extends Controller
{
public function indexAction()
{
return $this->render('BlogBundle:Default:index.html.twig');
}
}
And when I go to http://localhost:8000/home address I am getting this error: No route found for "GET /home"
So, what am I doing wrong here?
You add to set the route annotation on the action
<?php
namespace BlogBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
class DefaultController extends Controller
{
/**
* #Route("/home", name="home_route")
*/
public function indexAction()
{
return $this->render('BlogBundle:Default:index.html.twig');
}
}
If you use annotation on the class, is to prefix all actions

Symfony2 - Controller as a Service - Routing via annotations

I am experimenting with creating controllers as services as shown at http://symfony.com/doc/current/cookbook/controller/service.html. I’ve followed this example and everything works fine when I have the route set in app/config/routing.yml. However when I try and set the route via annotations I get an error
My routing.yml file looks like this:
#hello:
# path: /hello/{name}
# defaults: { _controller: app.hello_controller:indexAction }
hello:
resource: "#EventBundle/Controller/HelloController.php"
type: annotation
My controller looks like this:
<?php
namespace Me\EventBundle\Controller;
//use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
use Symfony\Component\HttpFoundation\Response;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
//class HelloController extends Controller
class HelloController
{
private $templating;
public function __construct(EngineInterface $templating)
{
$this->templating = $templating;
}
/**
* #Route("/hello/{name}", name="hello")
*
*/
public function indexAction($name)
{
return $this->templating->renderResponse(
'EventBundle:Default:test.html.twig',
array('name' => $name)
);
}
}
As I say if I just use routing.yml and not the annotations the page renders correctly. However using annotations I get the error:
Catchable Fatal Error: Argument 1 passed to Me\EventBundle\Controller\HelloController::__construct() must be an instance of Symfony\Bundle\FrameworkBundle\Templating\EngineInterface, none given, called in /Library/WebServer/Documents/symfony-project/app/cache/dev/classes.php on line 2176 and defined
EDIT - as requested in comments:
service.yml looks like:
services:
app.hello_controller:
class: Me\EventBundle\Controller\HelloController
arguments: ['#templating']
The answer with thanks especially to #Artamiel and #Cerad was to add #Route(service="app.hello_controller") just above my class name, so it now looks like:
/**
* #Route(service="app.hello_controller")
*/
class HelloController
{
private $templating;
public function __construct(EngineInterface $templating)
{
$this->templating = $templating;
}
..........etc

Resources