简体   繁体   English

Symfony 5 & EasyAdmin 3.0 - /admin 路由未找到

[英]Symfony 5 & EasyAdmin 3.0 - /admin route not found

I have fresh Symfony 5 project instlled locally, and added Easy Admin trought Symfony CLI:我在本地安装了新的 Symfony 5 项目,并添加了 Easy Admin trought Symfony CLI:

symfony composer req admin

I should have /admin route but it's missing我应该有/admin路线,但它不见了

I run:我跑:

symfony console cache:clear

symfony composer dump-autoload

rm -rf var/cache/*

symfony console debug:router
 -------------------------- -------- -------- ------ ----------------------------------- 
  Name                       Method   Scheme   Host   Path                               
 -------------------------- -------- -------- ------ ----------------------------------- 
  _preview_error             ANY      ANY      ANY    /_error/{code}.{_format}           
  _wdt                       ANY      ANY      ANY    /_wdt/{token}                      
  _profiler_home             ANY      ANY      ANY    /_profiler/                        
  _profiler_search           ANY      ANY      ANY    /_profiler/search                  
  _profiler_search_bar       ANY      ANY      ANY    /_profiler/search_bar              
  _profiler_phpinfo          ANY      ANY      ANY    /_profiler/phpinfo                 
  _profiler_search_results   ANY      ANY      ANY    /_profiler/{token}/search/results  
  _profiler_open_file        ANY      ANY      ANY    /_profiler/open                    
  _profiler                  ANY      ANY      ANY    /_profiler/{token}                 
  _profiler_router           ANY      ANY      ANY    /_profiler/{token}/router          
  _profiler_exception        ANY      ANY      ANY    /_profiler/{token}/exception       
  _profiler_exception_css    ANY      ANY      ANY    /_profiler/{token}/exception.css   
  homepage                   ANY      ANY      ANY    /                                  
 -------------------------- -------- -------- ------ ----------------------------------- 
// config/routes/easy_admin.yaml

easy_admin_bundle:
    resource: '@EasyAdminBundle/Controller/EasyAdminController.php'
    prefix: /admin
    type: annotation
symfony console router:match /admin

                                                                                                                       
 [ERROR] None of the routes match the path "/admin"

What am I missing?我错过了什么?

You need to create at least one dashboard.您需要创建至少一个仪表板。 Try:尝试:

php bin/console make:admin:dashboard

Next, you can create a CrudController with:接下来,您可以使用以下命令创建 CrudController:

php bin/console make:admin:crud

https://symfony.com/doc/master/bundles/EasyAdminBundle/dashboards.html https://symfony.com/doc/master/bundles/EasyAdminBundle/dashboards.html

Yeah, I am reading this book right now and ran into the same issue.是的,我现在正在读这本书,遇到了同样的问题。

First, make sure that your working directory is clean (run " git status " and remove all changes made by EasyAdminBundle setup).首先,确保您的工作目录是干净的(运行“ git status ”并删除 EasyAdminBundle 设置所做的所有更改)。

Then run:然后运行:

composer require easycorp/easyadmin-bundle:2.*

to install EasyAdminBundle version 2;安装 EasyAdminBundle 版本 2; with this version, you can proceed as described in the book.使用此版本,您可以按照书中的说明进行操作。

As others have already said you need to create a dashboard with:正如其他人已经说过的,您需要创建一个仪表板:

php bin/console make:admin:dashboard

And then create at least one crud controller.然后创建至少一个 crud controller。 Since it seems you're using the Fast Track book, you need to type the following command twice and make one for both Comment and Conference:由于您似乎使用的是 Fast Track 书,因此您需要键入以下命令两次,并为评论和会议创建一个:

php bin/console make:admin:crud

I am using the Fast Track book too and this is how my files ended up.我也在使用 Fast Track 书,这就是我的文件的最终结果。 I am still learning easy admin3 and thus make no claims as to best practice, but this should make the menus look as they do in the Fast Track screenshots:我仍在学习easy admin3,因此没有声称最佳实践,但这应该使菜单看起来像在Fast Track屏幕截图中一样:

src/Controller/Admin/DashboardController.php: src/Controller/Admin/DashboardController.php:

/**
 * @Route("/admin", name="admin")
 */
public function index(): Response
{
    $routeBuilder = $this->get(CrudUrlGenerator::class)->build();

    return $this->redirect($routeBuilder->setController(ConferenceCrudController::class)->generateUrl());
}

public function configureDashboard(): Dashboard
{
    return Dashboard::new()
        ->setTitle('Guestbook');
}

public function configureMenuItems(): iterable
{
    yield MenuItem::linktoRoute('Back to website', 'fa fa-home', 'homepage');
    yield MenuItem::linkToCrud('Conference', 'fa fa-map-marker', Conference::class);
    yield MenuItem::linkToCrud('Comment', 'fa fa-comment', Comment::class);
}

src/Controller/Admin/CommentCrudController.php: src/Controller/Admin/CommentCrudController.php:

public static function getEntityFqcn(): string
{
    return Comment::class;
}

public function configureFields(string $pageName): iterable
{
    return [
        IdField::new('id')->hideOnForm(),
        TextField::new('author'),
        TextareaField::new('text')->hideOnIndex(), // Removing ->hideOnIndex() will display a link to a text modal
        EmailField::new('email'),
        DateTimeField::new('createdAt')->hideOnForm(),
        ImageField::new('photoFilename', 'Photo')->setBasePath('/uploads/photos')->hideOnForm(),

        AssociationField::new('conference')
    ];
}

src/Controller/Admin/ConferenceCrudController.php src/Controller/Admin/ConferenceCrudController.php

public static function getEntityFqcn(): string
{
    return Conference::class;
}

public function configureFields(string $pageName): iterable
{
    return [
        IdField::new('id')->hideOnForm(),
        TextField::new('city'),
        TextField::new('year'),
        BooleanField::new('isInternational'),
        IntegerField::new('commentCount', 'Comments')->hideOnForm()
    ];
}

And in src/Entity/Conference.php I added the following to make commentCount available:在 src/Entity/Conference.php 我添加了以下内容以使commentCount可用:

public function getCommentCount(): int
{
    return $this->comments->count();
}

To generate the createdAt datetime automatically when the comment is submitted, I first installed the following bundle:为了在提交评论时自动生成 createdAt 日期时间,我首先安装了以下包:

$ composer require stof/doctrine-extensions-bundle

And then modified config/packages/stof_doctrine_extensions.yaml:然后修改config/packages/stof_doctrine_extensions.yaml:

stof_doctrine_extensions:
    default_locale: en_US
    orm:
        default:
            tree: true
            timestampable: true

And finally decorated private $createdAt in src/Entity/Comment.php with the following:最后在 src/Entity/Comment.php 中装饰private $createdAt如下:

/**
 * @var \DateTime
 * @ORM\Column(type="datetime")
 * @Gedmo\Mapping\Annotation\Timestampable(on="create")
 * @Doctrine\ORM\Mapping\Column(type="datetime")
 */
private $createdAt;

EasyAdminBundle v3 have another configuration and you no longer need to use EasyAdminController resource. EasyAdminBundle v3 有另一个配置,您不再需要使用EasyAdminController资源。

You can find more information about it here您可以在此处找到有关它的更多信息

https://github.com/EasyCorp/EasyAdminBundle/blob/master/src/Controller/EasyAdminController.php https://github.com/EasyCorp/EasyAdminBundle/blob/master/src/Controller/EasyAdminController.php

and here和这里

https://symfony.com/doc/master/bundles/EasyAdminBundle/dashboards.html https://symfony.com/doc/master/bundles/EasyAdminBundle/dashboards.html

I solved this problem as follows:我解决了这个问题如下:

  1. Remove EasyAdmin 3删除 EasyAdmin 3
composer remove admin
  1. Install additional package.安装额外的 package。
composer require "easycorp/easyadmin-bundle":"^2.3"
  1. Update packages.更新软件包。
composer update

When migrating from easyadmin 2 to 3, it appears that the route name is not preserved.从 easyadmin 2 迁移到 3 时,似乎没有保留路由名称。 One way to do this is in DashboardController, add一种方法是在 DashboardController 中添加

/**
 * @Route("/admin", name="easyadmin")
 */
public function index(): Response
{
    return parent::index();
}

In my case就我而言

first第一的

composer remove doctrine/common

and then接着

 composer require easycorp/easyadmin-bundle v2.3.9 doctrine/common v2.13.3 doctrine/persistence v1.3.8

With that it worked for the book有了它,它适用于这本书

For me, the clearest and most complete explanation is the answer to @AnnaHowell I would only change a part of your code.对我来说,最清晰、最完整的解释是对@AnnaHowell 的回答,我只会更改您的部分代码。 In src/Controller/Admin/CommentCrudController.ph p:src/Controller/Admin/CommentCrudController.php中:

 public function configureFields(string $pageName): iterable
{
    $avatar = ImageField::new('photoFilename')->setBasePath('uploads/photos/')->setLabel('Photo');
    $avatarTextFile = TextField::new('photoFilename');
   
     {
        yield     TextField::new('author');
        yield     TextEditorField::new('text');
        yield     TextField::new('state');
        yield     EmailField::new('email');
        yield     DateTimeField::new('createdAt', 'Created')->setFormat('dd-MM-y HH:mm:ss')
                ->setSortable(true)->setFormTypeOption('disabled','disabled');
        if (Crud::PAGE_INDEX === $pageName) {
        yield ImageField::new('photoFilename')->setBasePath('uploads/photos/')->setLabel('Photo');
    } elseif (Crud::PAGE_EDIT === $pageName) {
       yield TextField::new('photoFilename')->setLabel('Photo');
    }      
       
};

Thus, we allow the Administrator to not only evaluate the text, but also the relevance of the photo.因此,我们允许管理员不仅评估文本,还评估照片的相关性。 What if a comment has great text, but an inconvenient or trivial photo?如果评论有很棒的文字,但照片不方便或琐碎怎么办? The Administrator could delete the name of the photo (and that way it would not be visible), leave the text comment and publish it.管理员可以删除照片的名称(这样就不会显示),留下文字评论并发布。

Simply copy all of /vendor/easycorp/easyadmin-bundle/src/Resources/public to public/bundles/easyadmin只需将所有/vendor/easycorp/easyadmin-bundle/src/Resources/public复制到public/bundles/easyadmin

Short answer:简短的回答:

Make sure you are using HTTPS to access the admin route.确保您使用 HTTPS 访问管理路由。 Even if the admin route is supposed to use any scheme in the debug:router command.即使管理员路由应该使用 debug:router 命令中的任何方案。

Detailed answer详细解答

Same situation, reproducible with Symfony 4.4 and Symfony 5.2 and Easyadmin 3.2同样的情况,可使用 Symfony 4.4 和 Symfony 5.2 和 Easyadmin 3.2 重现

I found out that I was accessing my server with http (WAMP):我发现我正在使用 http (WAMP) 访问我的服务器:

URL URL Result结果
http://localhost http://localhost 200 200
http://localhost/admin http://localhost/admin 404 404

Then I tried with然后我尝试了

symfony console server:start

Noticed the warning about installing the certificate, installed it and ran again the symfony server.注意到有关安装证书的警告,安装它并再次运行 symfony 服务器。

After than I was able to use HTTPS, and the admin was accessible on https://localhost/admin之后我能够使用 HTTPS,并且可以在 https://localhost/admin 上访问管理员

I was testing - easyAdmin4, with Symfony 6, with Lando backend, in Ubuntu.我正在测试 - easyAdmin4,Symfony 6,Lando 后端,Ubuntu。

No matter what I try, not only /admin routing, any of the controller was not working.无论我尝试什么,不仅是/admin路由,controller 中的任何一个都不工作。

Make sure, if the issue is with EasyAdmin or with controllers.确保问题出在EasyAdmin或控制器上。

The controller issue is resolved after controller问题解决后

composer require symfony/apache-pack

From this post从这篇文章

Also, you can test /admin controller with此外,您可以测试/admin controller

returning返回

  1. Twig Template (By Uncommenting) return $this->render('template1.html.twig'); Twig 模板(通过取消注释) return $this->render('template1.html.twig'); and the template file will be present inside, templates/template1.html.twig并且模板文件将出现在里面, templates/template1.html.twig
  2. Simple Response use ing class Symfony\Component\HttpFoundation\Response;简单Response use ing class Symfony\Component\HttpFoundation\Response;
  3. Or JSON data use ing Symfony\Component\HttpFoundation\JsonResponse;JSON数据use ing Symfony\Component\HttpFoundation\JsonResponse;

-- By default the /admin route will open default template return parent::index(); -- 默认情况下/admin路由将打开默认模板return parent::index();

The Only solution seems to copy - .htaccess file inside public directory唯一的解决方案似乎是复制 - public目录中的.htaccess文件

# Use the front controller as index file. It serves as a fallback solution when
# every other rewrite/redirect fails (e.g. in an aliased environment without
# mod_rewrite). Additionally, this reduces the matching process for the
# start page (path "/") because otherwise Apache will apply the rewriting rules
# to each configured DirectoryIndex file (e.g. index.php, index.html, index.pl).
DirectoryIndex index.php

# By default, Apache does not evaluate symbolic links if you did not enable this
# feature in your server configuration. Uncomment the following line if you
# install assets as symlinks or if you experience problems related to symlinks
# when compiling LESS/Sass/CoffeScript assets.
# Options +FollowSymlinks

# Disabling MultiViews prevents unwanted negotiation, e.g. "/index" should not resolve
# to the front controller "/index.php" but be rewritten to "/index.php/index".
<IfModule mod_negotiation.c>
    Options -MultiViews
</IfModule>

<IfModule mod_rewrite.c>
    RewriteEngine On

    # Determine the RewriteBase automatically and set it as environment variable.
    # If you are using Apache aliases to do mass virtual hosting or installed the
    # project in a subdirectory, the base path will be prepended to allow proper
    # resolution of the index.php file and to redirect to the correct URI. It will
    # work in environments without path prefix as well, providing a safe, one-size
    # fits all solution. But as you do not need it in this case, you can comment
    # the following 2 lines to eliminate the overhead.
    RewriteCond %{REQUEST_URI}::$0 ^(/.+)/(.*)::\2$
    RewriteRule .* - [E=BASE:%1]

    # Sets the HTTP_AUTHORIZATION header removed by Apache
    RewriteCond %{HTTP:Authorization} .+
    RewriteRule ^ - [E=HTTP_AUTHORIZATION:%0]

    # Redirect to URI without front controller to prevent duplicate content
    # (with and without `/index.php`). Only do this redirect on the initial
    # rewrite by Apache and not on subsequent cycles. Otherwise we would get an
    # endless redirect loop (request -> rewrite to front controller ->
    # redirect -> request -> ...).
    # So in case you get a "too many redirects" error or you always get redirected
    # to the start page because your Apache does not expose the REDIRECT_STATUS
    # environment variable, you have 2 choices:
    # - disable this feature by commenting the following 2 lines or
    # - use Apache >= 2.3.9 and replace all L flags by END flags and remove the
    #   following RewriteCond (best solution)
    RewriteCond %{ENV:REDIRECT_STATUS} =""
    RewriteRule ^index\.php(?:/(.*)|$) %{ENV:BASE}/$1 [R=301,L]

    # If the requested filename exists, simply serve it.
    # We only want to let Apache serve files and not directories.
    # Rewrite all other queries to the front controller.
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ %{ENV:BASE}/index.php [L]
</IfModule>

<IfModule !mod_rewrite.c>
    <IfModule mod_alias.c>
        # When mod_rewrite is not available, we instruct a temporary redirect of
        # the start page to the front controller explicitly so that the website
        # and the generated links can still be used.
        RedirectMatch 307 ^/$ /index.php/
        # RedirectTemp cannot be used instead
    </IfModule>
</IfModule>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM