-->

Custom Home page sonata page

2019-06-09 06:29发布

问题:

I create my custom controller for the page home.

controller:

class FrontPageController extends Controller
{
    public function homeAction()
    {
         return $this->render('FrontPageBundle:Page:home.html.twig');
    }
}

routing.yml

front_page_home:
   path: /
   defaults: { _controller: FrontPageBundle:FrontPage:home }

but the url to my controller redirects to the controller sonata.page.page_service_manager:execute

route: "page_slug"

回答1:

I found a solution but I don't know if it is good practice or not.

I create my customer RoutePageGenerator class and edit the class which will change the route to the homepage. Like this:

 // Iterate over declared routes from the routing mechanism
    foreach ($this->router->getRouteCollection()->all() as $name => $route) {

        if($route->getPath() === "/")
        {
            $name = trim($name);
            $root = $this->pageManager->create(array(
                'routeName'     => $name,
                'name'          => $name,
                'url'           => $route->getPath(),
                'site'          => $site,
                'requestMethod' => isset($requirements['_method']) ? $requirements['_method'] : 'GET|POST|HEAD|DELETE|PUT',
                'slug'          => '/',
            ));
        }

I delete this part of code:

        $root = $this->pageManager->getPageByUrl($site, '/');

    // no root url for the given website, create one
    if (!$root) {
        $root = $this->pageManager->create(array(
            'routeName'     => PageInterface::PAGE_ROUTE_CMS_NAME,
            'name'          => 'Homepage',
            'url'           => '/',
            'site'          => $site,
            'requestMethod' => isset($requirements['_method']) ? $requirements['_method'] : 'GET|POST|HEAD|DELETE|PUT',
            'slug'          => '/',
        ));

        $this->pageManager->save($root);
    }

I create my customer UpdateCoreRoutesCommand and I call my RoutePageGenerator:

just execute this command php app/console sonata:page:create-snapshots --site=1 and it works.