Y
Y
yii2-prog112019-06-13 15:53:33
Yii
yii2-prog11, 2019-06-13 15:53:33

What needs to be written so that there is a correct URL for frontend and backend in yii2?

There is a site on an openserver and the following domains are registered to it:
Domain name: localhost. Domain folder: \localhost\frontend\web
Domain name: admin.localhost. Domain folder: \localhost\backend\web
Images are saved and displayed in the admin panel in the folder backend/web/upload/images
Here is an example of how I display an image in the admin panel:

$dir = '/upload/images/preview-' . $model->img;
return Html::img(Yii::$app->urlManager->createUrl($dir));

The question is the following. How to correctly specify the URL to the image so that it is displayed in the user part?
Or how should I write the paths if I create a shared folder, for example, in common?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2019-06-13
@yii2-prog11

Good afternoon.
You can do this:
In common/config/main.php

$baseUrlFrontend = str_replace('backend/web', '', (new Request)->getBaseUrl());

return [
    'components' => [
        'cache'              => [
            'class' => 'yii\caching\FileCache',
        ],
        'urlManagerFrontend' => [
            'class'           => 'yii\web\UrlManager',
            'baseUrl'         => $baseUrlFrontend,
            'enablePrettyUrl' => true,
            'showScriptName'  => false,
        ]
    ]
]

Images are stored in frontend/web/images. In the backend you get them like this:
$img =  (Yii::$app->urlManagerFrontend->createUrl( $model->images[0]['path'] . DIRECTORY_SEPARATOR . $model->images[0]['title']));
echo Html::img($img);

In the frontend you get it in the usual way.
ps I can have several images per entry, so I use the "images" link and display the first image from the array with index "0".
pss urlManagerFrontend placed in common because I use it not only in the backend. You try to place in backend/config/main.php

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question