AFS AFS - 5 months ago 36
PHP Question

Set href path on twig with annotation route on symfony

I'am using annotations routes and I have to set an href path but I get this message

An exception has been thrown during the rendering of a template ("Unable to generate a URL for the named route "crear" as such route does not exist.") in menu.html.twig at line 20.


this is menu.html.twig at line 20

<li><a href="{{ path('crear') }}">Crear</a></li>


and this is the controller

<?php

namespace UserBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;
use UserBundle\Entity\User;
use \DateTime;

class DefaultController extends Controller
{
/**
* @Route("/")
*/
public function indexAction()
{
/*$user = new User();
$user->setUsername("usuario2");
$user->setFirstName("aaa");
$user->setLastName("bb");
$user->setEmail("bbb@mail.com");
$user->setPassword("123456");
$user->setRole('ROLE_ADMIN');
$user->setIsActive(true);
$user->setCreatedAt(new DateTime());
$user->setUpdatedAt(new DateTime());
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();*/
return $this->render('UserBundle:Default:index.html.twig');
//return new Response(phpinfo());
}
/**
*@Route("/ver")
*/
public function viewAction(){
$repository = $this->getDoctrine()->getRepository('UserBundle:User');
$users = $repository->findAll();
//return new Response($user->getEmail());
return $this->render('UserBundle:User:view.html.twig',array('users'=>$users ));
}

/**
*@Route("/crear")
*/
public function createAction(){
return new Response("Crear");
}
}


and routing.yml

user:
resource: "@UserBundle/Controller/"
type: annotation
prefix: /

app:
resource: "@AppBundle/Controller/"
type: annotation


I have to activate some route or what I have to do?

Answer

You need to specify a name for the route in order to generate via twig, so change the controller annotation as follow:

/**
*@Route("/crear", name="crear")
*/
public function createAction(){
  return new Response("Crear");
}
Comments