Symfony2 How to use parameters.yml in controller as variable
I am working with a Symfony2 project.
I am trying to pice data, decleared in parameters.yml, and use that data in one of my controllers.
I read this one in the Symfony2 documentation about getParameters()
but it doesn't work.
In my .yml options, I did this:
sitemap_root_url: http:/example.co.uk/news/
In my controller, I am trying to do this:
$this->test = $this->container->getParameters('sitemap_root_url');
This is the error I am getting:
Notice: Undefined property $container
source to share
Try $this->container->getParameter('sitemap_root_url');
This works well for me, I am using Symfony 2.5.
If you want to use a container in your controller you can extend
Symfony \ Bundle \ FrameworkBundle \ Controller \ Controller (Basic Symfony Controller).
// src/AppBundle/Controller/HelloController.php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class HelloController extends Controller
{
// ...
}
Then you can get your property. Example controller that works for me:
namespace AppBundle\Controller;
use Symfony\Component\HttpFoundation\Response
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class HelloController extends Controller
{
public function indexAction()
{
return new Response(
$this->container->getParameter('sitemap_root_url');
);
}
}
source to share
Apparently $container
not declared in your controller, if you want to access the controller you can extend Symfony\Bundle\FrameworkBundle\Controller\Controller
and then use$this->container->getParameter('sitemap_root_url')
Otherwise, you will have to declare the controller as a service and inject the container.
source to share