Yii ошибка 404

Yii includes a built-in error handler which makes error handling a much more pleasant
experience than before. In particular, the Yii error handler does the following to improve error handling:

  • All non-fatal PHP errors (e.g. warnings, notices) are converted into catchable exceptions.
  • Exceptions and fatal PHP errors are displayed with detailed call stack information and source code lines
    in debug mode.
  • Supports using a dedicated controller action to display errors.
  • Supports different error response formats.

The error handler is enabled by default. You may disable it by defining the constant
YII_ENABLE_ERROR_HANDLER to be false in the entry script of your application.

Using Error Handler ¶

The error handler is registered as an application component named errorHandler.
You may configure it in the application configuration like the following:

return [
    'components' => [
        'errorHandler' => [
            'maxSourceLines' => 20,
        ],
    ],
];

With the above configuration, the number of source code lines to be displayed in exception pages will be up to 20.

As aforementioned, the error handler turns all non-fatal PHP errors into catchable exceptions. This means you can
use the following code to deal with PHP errors:

use Yii;
use yii\base\ErrorException;

try {
    10/0;
} catch (ErrorException $e) {
    Yii::warning("Division by zero.");
}

// execution continues...

If you want to show an error page telling the user that his request is invalid or unexpected, you may simply
throw an HTTP exception, such as yii\web\NotFoundHttpException. The error handler
will correctly set the HTTP status code of the response and use an appropriate error view to display the error
message.

use yii\web\NotFoundHttpException;

throw new NotFoundHttpException();

Customizing Error Display ¶

The error handler adjusts the error display according to the value of the constant YII_DEBUG.
When YII_DEBUG is true (meaning in debug mode), the error handler will display exceptions with detailed call
stack information and source code lines to help easier debugging. And when YII_DEBUG is false, only the error
message will be displayed to prevent revealing sensitive information about the application.

Info: If an exception is a descendant of yii\base\UserException, no call stack will be displayed regardless
the value of YII_DEBUG. This is because such exceptions are considered to be caused by user mistakes and the
developers do not need to fix anything.

By default, the error handler displays errors using two views:

  • @yii/views/errorHandler/error.php: used when errors should be displayed WITHOUT call stack information.
    When YII_DEBUG is false, this is the only error view to be displayed.
  • @yii/views/errorHandler/exception.php: used when errors should be displayed WITH call stack information.

You can configure the errorView and exceptionView
properties of the error handler to use your own views to customize the error display.

Using Error Actions ¶

A better way of customizing the error display is to use dedicated error actions.
To do so, first configure the errorAction property of the errorHandler
component like the following:

return [
    'components' => [
        'errorHandler' => [
            'errorAction' => 'site/error',
        ],
    ]
];

The errorAction property takes a route
to an action. The above configuration states that when an error needs to be displayed without call stack information,
the site/error action should be executed.

You can create the site/error action as follows,

namespace app\controllers;

use Yii;
use yii\web\Controller;

class SiteController extends Controller
{
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }
}

The above code defines the error action using the yii\web\ErrorAction class which renders an error
using a view named error.

Besides using yii\web\ErrorAction, you may also define the error action using an action method like the following,

public function actionError()
{
    $exception = Yii::$app->errorHandler->exception;
    if ($exception !== null) {
        return $this->render('error', ['exception' => $exception]);
    }
}

You should now create a view file located at views/site/error.php. In this view file, you can access
the following variables if the error action is defined as yii\web\ErrorAction:

  • name: the name of the error;
  • message: the error message;
  • exception: the exception object through which you can retrieve more useful information, such as HTTP status code,
    error code, error call stack, etc.

Info: If you are using the basic project template or the advanced project template,
the error action and the error view are already defined for you.

Note: If you need to redirect in an error handler, do it the following way:

Yii::$app->getResponse()->redirect($url)->send();
return;

Customizing Error Response Format ¶

The error handler displays errors according to the format setting of the response.
If the response format is html, it will use the error or exception view
to display errors, as described in the last subsection. For other response formats, the error handler will
assign the array representation of the exception to the yii\web\Response::$data property which will then
be converted to different formats accordingly. For example, if the response format is json, you may see
the following response:

HTTP/1.1 404 Not Found
Date: Sun, 02 Mar 2014 05:31:43 GMT
Server: Apache/2.2.26 (Unix) DAV/2 PHP/5.4.20 mod_ssl/2.2.26 OpenSSL/0.9.8y
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8

{
    "name": "Not Found Exception",
    "message": "The requested resource was not found.",
    "code": 0,
    "status": 404
}

You may customize the error response format by responding to the beforeSend event of the response component
in the application configuration:

return [
    // ...
    'components' => [
        'response' => [
            'class' => 'yii\web\Response',
            'on beforeSend' => function ($event) {
                $response = $event->sender;
                if ($response->data !== null) {
                    $response->data = [
                        'success' => $response->isSuccessful,
                        'data' => $response->data,
                    ];
                    $response->statusCode = 200;
                }
            },
        ],
    ],
];

The above code will reformat the error response like the following:

HTTP/1.1 200 OK
Date: Sun, 02 Mar 2014 05:31:43 GMT
Server: Apache/2.2.26 (Unix) DAV/2 PHP/5.4.20 mod_ssl/2.2.26 OpenSSL/0.9.8y
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8

{
    "success": false,
    "data": {
        "name": "Not Found Exception",
        "message": "The requested resource was not found.",
        "code": 0,
        "status": 404
    }
}

I want to display 404 error page for that i have made error404.php file in my protected/view/system folder.

By default i have Sitecontroller and it contained error action function as below

public function actionError()
{
    if($error=Yii::app()->errorHandler->error)
    {

        if(Yii::app()->request->isAjaxRequest)
            echo $error['message'];
        else
            $this->render('error', $error);
    }
}

inside main config file it is defined as

    'errorHandler'=>array(
        // use 'site/error' action to display errors
        'errorAction'=>'site/error',
    ),

my problem is i need to customize 404 page only, rest of the error i need to handle the way it is being handle by sitecontroller’s error function. But i could not find a way to do that. If suppose i remove ‘errorAction’=>’site/error’, from the config main then it does show the 404 error by calling

        throw new CHttpException(404, 'Page not found');

but doing that i can only see the page without layout also other custom errors are treated same as 404 while they are not. I read the manual many times but i still cant able to resolve it.

asked Aug 5, 2012 at 10:05

wolvorinePk's user avatar

Use this code for actionError:

$app = Yii::app();
if( $error = $app->errorHandler->error->code )
{
    if( $app->request->isAjaxRequest )
        echo $error['message'];
    else
        $this->render( 'error' . ( $this->getViewFile( 'error' . $error ) ? $error : '' ), $error );
}

In views/site create error404.php for 404 errors and error.php for the rest.

Or you can define param in the config for errors you like to handle differently and check error code against it:

$app = Yii::app();
if( $error = $app->errorHandler->error->code )
{
    if( Yii::app()->request->isAjaxRequest )
        echo $error['message'];
    else    
        $this->render( 'error' . ( in_array( $error, $app->params[ 'customErrorPages' ] ) ? $error : '' ), $error );
}

Error handler works like this: when httpexception arise, component will check if there is any value in errorAction property and if there is any, will run this controller’s action. If there is no set value to the errorAction property, will display error view from system folder. So there is no need to mix error views from system view folder and controller’s view folder.

answered Aug 5, 2012 at 13:55

Boris Belenski's user avatar

3

Whenever errors occur, the action error in siteController is called. you can customize the error route in that action, you can do something like this:

if(404==Yii::app()->errorHandler->error->code){
     //go to custome error page
else
   //code default error.php

answered Aug 5, 2012 at 10:07

bingjie2680's user avatar

bingjie2680bingjie2680

7,6638 gold badges46 silver badges72 bronze badges

3

Can’t you do this with .htaccess? Personally I create an «errors» folder with all the html php files that holds the error messages and modify .htaccess to call those pages while coming across the error.

Links:

http://www.javascriptkit.com/howto/htaccess2.shtml

http://www.addedbytes.com/for-beginners/error-documents-for-beginners/

Examples:

Create a .htaccess file in the directory you want the error pages to be called and in the text file, write the following line:

ErrorDocument 404     /404.html

assuming there is a page called 404.html in the same directory, when a 404 page not found error is genrated, the 404.html page will be called.

The same works with other error codes:

ErrorDocument 500     /500error.html

assuming a 500 error was created and a 500error.html file exists in the same directory.

answered Aug 5, 2012 at 10:27

DMor's user avatar

DMorDMor

7702 gold badges8 silver badges17 bronze badges

1

In the latest versions of the framework (I am working with 1.14) use:

Yii::app()->errorHandler->error['code']

because error is an array.

answered Aug 18, 2014 at 8:22

croppio.com's user avatar

croppio.comcroppio.com

1,8435 gold badges28 silver badges44 bronze badges

Yii includes a built-in [[yii\web\ErrorHandler|error handler]] which makes error handling a much more pleasant
experience than before. In particular, the Yii error handler does the following to improve error handling:

  • All non-fatal PHP errors (e.g. warnings, notices) are converted into catchable exceptions.
  • Exceptions and fatal PHP errors are displayed with detailed call stack information and source code lines
    in debug mode.
  • Supports using a dedicated controller action to display errors.
  • Supports different error response formats.

The [[yii\web\ErrorHandler|error handler]] is enabled by default. You may disable it by defining the constant
YII_ENABLE_ERROR_HANDLER to be false in the entry script of your application.

Using Error Handler

The [[yii\web\ErrorHandler|error handler]] is registered as an application component named errorHandler.
You may configure it in the application configuration like the following:

return [
    'components' => [
        'errorHandler' => [
            'maxSourceLines' => 20,
        ],
    ],
];

With the above configuration, the number of source code lines to be displayed in exception pages will be up to 20.

As aforementioned, the error handler turns all non-fatal PHP errors into catchable exceptions. This means you can
use the following code to deal with PHP errors:

use Yii;
use yii\base\ErrorException;

try {
    10/0;
} catch (ErrorException $e) {
    Yii::warning("Division by zero.");
}

// execution continues...

If you want to show an error page telling the user that his request is invalid or unexpected, you may simply
throw an [[yii\web\HttpException|HTTP exception]], such as [[yii\web\NotFoundHttpException]]. The error handler
will correctly set the HTTP status code of the response and use an appropriate error view to display the error
message.

use yii\web\NotFoundHttpException;

throw new NotFoundHttpException();

Customizing Error Display

The [[yii\web\ErrorHandler|error handler]] adjusts the error display according to the value of the constant YII_DEBUG.
When YII_DEBUG is true (meaning in debug mode), the error handler will display exceptions with detailed call
stack information and source code lines to help easier debugging. And when YII_DEBUG is false, only the error
message will be displayed to prevent revealing sensitive information about the application.

Info: If an exception is a descendant of [[yii\base\UserException]], no call stack will be displayed regardless
the value of YII_DEBUG. This is because such exceptions are considered to be caused by user mistakes and the
developers do not need to fix anything.

By default, the [[yii\web\ErrorHandler|error handler]] displays errors using two views:

  • @yii/views/errorHandler/error.php: used when errors should be displayed WITHOUT call stack information.
    When YII_DEBUG is false, this is the only error view to be displayed.
  • @yii/views/errorHandler/exception.php: used when errors should be displayed WITH call stack information.

You can configure the [[yii\web\ErrorHandler::errorView|errorView]] and [[yii\web\ErrorHandler::exceptionView|exceptionView]]
properties of the error handler to use your own views to customize the error display.

Using Error Actions

A better way of customizing the error display is to use dedicated error actions.
To do so, first configure the [[yii\web\ErrorHandler::errorAction|errorAction]] property of the errorHandler
component like the following:

return [
    'components' => [
        'errorHandler' => [
            'errorAction' => 'site/error',
        ],
    ]
];

The [[yii\web\ErrorHandler::errorAction|errorAction]] property takes a route
to an action. The above configuration states that when an error needs to be displayed without call stack information,
the site/error action should be executed.

You can create the site/error action as follows,

namespace app\controllers;

use Yii;
use yii\web\Controller;

class SiteController extends Controller
{
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }
}

The above code defines the error action using the [[yii\web\ErrorAction]] class which renders an error
using a view named error.

Besides using [[yii\web\ErrorAction]], you may also define the error action using an action method like the following,

public function actionError()
{
    $exception = Yii::$app->errorHandler->exception;
    if ($exception !== null) {
        return $this->render('error', ['exception' => $exception]);
    }
}

You should now create a view file located at views/site/error.php. In this view file, you can access
the following variables if the error action is defined as [[yii\web\ErrorAction]]:

  • name: the name of the error;
  • message: the error message;
  • exception: the exception object through which you can retrieve more useful information, such as HTTP status code,
    error code, error call stack, etc.

Info: If you are using the basic project template or the advanced project template,
the error action and the error view are already defined for you.

Customizing Error Response Format

The error handler displays errors according to the format setting of the response.
If the the [[yii\web\Response::format|response format]] is html, it will use the error or exception view
to display errors, as described in the last subsection. For other response formats, the error handler will
assign the array representation of the exception to the [[yii\web\Response::data]] property which will then
be converted to different formats accordingly. For example, if the response format is json, you may see
the following response:

HTTP/1.1 404 Not Found
Date: Sun, 02 Mar 2014 05:31:43 GMT
Server: Apache/2.2.26 (Unix) DAV/2 PHP/5.4.20 mod_ssl/2.2.26 OpenSSL/0.9.8y
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8

{
    "name": "Not Found Exception",
    "message": "The requested resource was not found.",
    "code": 0,
    "status": 404
}

You may customize the error response format by responding to the beforeSend event of the response component
in the application configuration:

return [
    // ...
    'components' => [
        'response' => [
            'class' => 'yii\web\Response',
            'on beforeSend' => function ($event) {
                $response = $event->sender;
                if ($response->data !== null) {
                    $response->data = [
                        'success' => $response->isSuccessful,
                        'data' => $response->data,
                    ];
                    $response->statusCode = 200;
                }
            },
        ],
    ],
];

The above code will reformat the error response like the following:

HTTP/1.1 200 OK
Date: Sun, 02 Mar 2014 05:31:43 GMT
Server: Apache/2.2.26 (Unix) DAV/2 PHP/5.4.20 mod_ssl/2.2.26 OpenSSL/0.9.8y
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8

{
    "success": false,
    "data": {
        "name": "Not Found Exception",
        "message": "The requested resource was not found.",
        "code": 0,
        "status": 404
    }
}

После установки Yii2 уже имеется файл view-шаблона views/site/error.php. Чтобы получить свою страницу ошибки, можно просто отредактировать этот файл. В нём доступны три переменные: $name, $message, $exception. Признак ошибки 404 — это значение свойства statusCode объекта $exception. Таким образом можно написать свою проверку этого значения и для разных ошибок показывать пользователю разный ответ.

Почему для показа сообщения об ошибках используется шаблон views/site/error.php? Это задается в настройках приложения, в файле config/web.php:

$config = [
    /* ... */
    'components' => [
        /* ... */
        'errorHandler' => [
            'errorAction' => 'site/error'
        ],
        /* ... */
    ],
    /* ... */
];

Для обработки ошибок будет использован метод actionError() класса SiteController:

class SiteController extends Controller {
    /* ... */
    public function actionError() {
        $exception = Yii::$app->errorHandler->exception;
        if ($exception !== null) {
            return $this->render('error', ['exception' => $exception]);
        }
    }
    /* ... */
}

Но если мы заглянем в исходный код controllers/SiteController.php, то обнаружим, что такого метода там нет. А вместо него есть метод actions():

class SiteController extends Controller {
    /* ... */
    public function actions()
    {
        return [
            'error' => [
                // объявляем действие error и задаем имя класса
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }
    /* ... */
}

Все действия контроллера можно разделить на встроенные и отдельные. Встроенные действия определены как методы контроллера, например actionError(). Отдельные действия указываются в карте действий контроллера, в методе actions(). Сам же функционал таких действий описан в отдельных классах.

Мы договорились ранее использовать класс SiteController только как образец. Давайте зададим свой обработчик ошибки в файле конфигурации config/web.php:

$config = [
    /* ... */
    'components' => [
        /* ... */
        'errorHandler' => [
            'errorAction' => 'app/error'
        ],
        /* ... */
    ],
    /* ... */
];

Добавим метод actions() в класс AppController:

class AppController extends Controller {
    /* ... */
    public function actions() {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }
    /* ... */
}

Создадим view-шаблон views/app/error.php:

<?php
/* @var $this yii\web\View */
/* @var $name string */
/* @var $message string */
/* @var $exception Exception */

use yii\helpers\Html;

$this->title = $name;
?>
<div class="container">
    <h1><?= Html::encode($this->title) ?></h1>
    <div class="alert alert-danger">
        <?= nl2br(Html::encode($message)) ?>
    </div>
</div>

И внесем изменения в класс CatalogController, чтобы он выбрасывал исключение, когда в базе данных не удается найти категорию, бренд или товар каталога:

<?php
namespace app\controllers;

use app\models\Category;
use app\models\Brand;
use app\models\Product;
use yii\web\HttpException;
use Yii;

class CatalogController extends AppController {
    /**
     * Главная страница каталога товаров
     */
    public function actionIndex() {
        // получаем корневые категории
        $roots = Yii::$app->cache->get('root-categories');
        if ($roots === false) {
            $roots = Category::find()->where(['parent_id' => 0])->asArray()->all();
            Yii::$app->cache->set('root-categories', $roots);
        }
        // получаем популярные бренды
        $brands = Yii::$app->cache->get('popular-brands');
        if ($brands === false) {
            $brands = (new Brand())->getPopularBrands();
            Yii::$app->cache->set('popular-brands', $brands);
        }
        return $this->render('index', compact('roots', 'brands'));
    }

    /**
     * Категория каталога товаров
     */
    public function actionCategory($id, $page = 1) {
        $id = (int)$id;
        $page = (int)$page;
        // пробуем извлечь данные из кеша
        $data = Yii::$app->cache->get('category-'.$id.'-page-'.$page);
        if ($data === null) {
            // данные есть в кеше, но такой категории не существует
            throw new HttpException(
                404,
                'Запрошенная страница не найдена'
            );
        }
        if ($data === false) {
            // данных нет в кеше, получаем их заново
            $temp = new Category();
            // данные о категории
            $category = $temp->getCategory($id);
            if (!empty($category)) { // такая категория существует
                // товары категории
                list($products, $pages) = $temp->getCategoryProducts($id);
                // сохраняем полученные данные в кеше
                $data = [$products, $pages, $category];
                Yii::$app->cache->set('category-' . $id . '-page-' . $page, $data);
            } else { // такая категория не существует
                Yii::$app->cache->set('category-' . $id . '-page-' . $page, null);
                throw new HttpException(
                    404,
                    'Запрошенная страница не найдена'
                );
            }
        }
        list($products, $pages, $category) = $data;
        // устанавливаем мета-теги для страницы
        $this->setMetaTags(
            $category['name'] . ' | ' . Yii::$app->params['shopName'],
            $category['keywords'],
            $category['description']
        );
        return $this->render(
            'category',
            compact('category', 'products', 'pages')
        );
    }

    /**
     * Список всех брендов каталога товаров
     */
    public function actionBrands() {
        // пробуем извлечь данные из кеша
        $brands = Yii::$app->cache->get('all-brands');
        if ($brands === false) {
            // данных нет в кеше, получаем их заново
            $brands = (new Brand())->getAllBrands();
            // сохраняем полученные данные в кеше
            Yii::$app->cache->set('all-brands', $brands);
        }
        return $this->render(
            'brands',
            compact('brands')
        );
    }

    /**
     * Список товаров бренда с идентификатором $id
     */
    public function actionBrand($id, $page = 1) {
        $id = (int)$id;
        $page = (int)$page;
        // пробуем извлечь данные из кеша
        $data = Yii::$app->cache->get('brand-'.$id.'-page-'.$page);
        if ($data === null) {
            // данные есть в кеше, но такого бренда не существует
            throw new HttpException(
                404,
                'Запрошенная страница не найдена'
            );
        }
        if ($data === false) {
            // данных нет в кеше, получаем их заново
            $temp = new Brand();
            // данные о бренде
            $brand = $temp->getBrand($id);
            if (!empty($brand)) { // такой бренд существует
                // товары бренда
                list($products, $pages) = $temp->getBrandProducts($id);
                // сохраняем полученные данные в кеше
                $data = [$products, $pages, $brand];
                Yii::$app->cache->set('brand-'.$id.'-page-'.$page, $data);
            } else { // такой бренд не существует
                Yii::$app->cache->set('brand-'.$id.'-page-'.$page, null);
                throw new HttpException(
                    404,
                    'Запрошенная страница не найдена'
                );
            }
        }
        list($products, $pages, $brand) = $data;
        // устанавливаем мета-теги
        $this->setMetaTags(
            $brand['name'] . ' | ' . Yii::$app->params['shopName'],
            $brand['keywords'],
            $brand['description']
        );
        return $this->render(
            'brand',
            compact('brand', 'products', 'pages')
        );
    }

    /**
     * Страница товара с идентификатором $id
     */
    public function actionProduct($id) {
        $id = (int)$id;
        // пробуем извлечь данные из кеша
        $data = Yii::$app->cache->get('product-'.$id);
        if ($data === null) {
            // данные есть в кеше, но такого товара не существует
            throw new HttpException(
                404,
                'Запрошенная страница не найдена'
            );
        }
        if ($data === false) {
            // данных нет в кеше, получаем их заново
            $product = (new Product())->getProduct($id);
            if (!empty($product)) { // такой товар существует
                $brand = (new Brand())->getBrand($product['brand_id']);
                $data = [$product, $brand];
                // сохраняем полученные данные в кеше
                Yii::$app->cache->set('product-' . $id, $data);
            } else { // такого товара не существует
                Yii::$app->cache->set('product-' . $id, null);
                throw new HttpException(
                    404,
                    'Запрошенная страница не найдена'
                );
            }
        }
        list($product, $brand) = $data;
        // устанавливаем мета-теги
        $this->setMetaTags(
            $product['name'] . ' | ' . Yii::$app->params['shopName'],
            $product['keywords'],
            $product['description']
        );
        // получаем популярные товары, похожие на текущий
        $similar = Yii::$app->cache->get('similar-'.$product['id']);
        if ($similar === false) {
            // товары из той же категории того же бренда
            $similar = Product::find()
                ->where([
                    'hit' => 1,
                    'category_id' => $product['category_id'],
                    'brand_id' => $product['brand_id']
                ])
                ->andWhere(['NOT IN', 'id', $product['id']])
                ->limit(3)
                ->asArray()
                ->all();
            Yii::$app->cache->set('similar-'.$product['id'], $similar);
        }
        return $this->render(
            'product',
            compact('product', 'brand', 'similar')
        );
    }
}

Поиск:
Web-разработка • Yii2 • Интернет магазин • Исключение • Каталог товаров • Практика • Фреймворк • 404 • Not Found • Exception • Ошибка • Error

Каталог оборудования

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Производители

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Функциональные группы

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Answer by Braxton Nichols

The Controllers need to be all CamelCase and start with a capital letter. So in your case, GreetingController (both class and file).,This is the controllers\greetingController’s code:,Connect and share knowledge within a single location that is structured and easy to search.,Please be sure to answer the question. Provide details and share your research!

And in your action use:

return $this->render('index');

Answer by Kori Beil

Recently encountered similar problems.
Created models and CRUD with GII. Some Models worked fine but some models generated the Not Found (#404) when trying to request the CRUD views. Even with URL manager. I found out that Yii2 doesn’t like model names with multiple capitals in their name. e.g. I had a model called PProfs and the CRUD views were not found. When I changed the name to Pprofs and regenerated the CRUD view they could be found!
Couldn’t find it anywhere in Forum. So here it is!,It’s not clear what you mean. Where does your WsbNewsCategory route point to in your url rules from your config? What does your controller look like? Try looking at some of the basic tutorials like https://www.youtube.com/watch?v=H7uON7rcv4g&list=PLBEpR3pmwCayfpaE9Vk-0xDsE5HQRJxuq to get a basic understanding of how Yii works.,Correct it used PProfsController.
So I now understand the problem was in the naming of the controller. Thanks.
(at least people can find the solution when they make they same mistake),@StonePro What controller name did you have when CRUD for PProfs model didn’t work? Was it “PProfsController”? And what route did you try to access the CRUD with? It would not work with the url like «http://my.host/pprofs/index». You should have used «http://my.host/p-profs/index» instead.

The name of the model has nothing to do with the urls of the CRUD. It’s the name of the controller that matters in url management.

@StonePro What controller name did you have when CRUD for PProfs model didn’t work? Was it “PProfsController”? And what route did you try to access the CRUD with? It would not work with the url like "http://my.host/pprofs/index". You should have used "http://my.host/p-profs/index" instead.

"http://my.host/pprofs/index"

The name of the model has nothing to do with the urls of the CRUD. It’s the name of the controller that matters in url management.

@StonePro What controller name did you have when CRUD for PProfs model didn’t work? Was it “PProfsController”? And what route did you try to access the CRUD with? It would not work with the url like "http://my.host/pprofs/index". You should have used "http://my.host/p-profs/index" instead.

"http://my.host/p-profs/index"

Answer by Azrael Juarez

3Where the error in the algorithm implementation Merge Sort?,1Laravel error SQL query, can’t figure out why:<?,3How to prepare the database for the dictionary?

return [
 'id' => 'app-backend',
 'basePath' => dirname(__DIR__),
 'controllerNamespace' => 'backend\controllers',
 'bootstrap' => ['log','gii'],
 'modules' => [
 'gii' => [
 'class' => 'yii\gii\Module',
 'allowedIPs' => ['127.0.0.1', '::1']
],
 ],

Answer by Ila Salinas

I have just upgraded my Yii 2.0 app to 2.0.40. The app has served me well without issues. However, after update my rest api no longer works. It gives a consistent «Not Found (#404). Page not found» error. Whenever i go back to my backup previous Yii version, the rest api works well there but it just will not work on 2.0.40.
This issue occurs both on my local server and web server,Yes action is mybook and url is like this http://localhost/gig_books/backend/web/index.php/api/mybook. I made a typo error when posting.
Error remains. I have downgraded as far back as 2.0.15 and its same issue but when i go back to the original version, api works okay.,The check mentioned above is there to prevent such mistakes and it was introduced in 2.0.4.,Setting log level to trace would be better. I’ll try to dry-run the 2.0.1 version and see what are the differences in handling this.

<?php
return [
    'components' => [
        'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'mysql:host=localhost;dbname=gigs',
            'username' => 'root',
            'password' => '',
            'charset' => 'utf8',
        ],
        'mailer' => [
            'class' => 'yii\swiftmailer\Mailer',
            'viewPath' => '@common/mail',
		
          'useFileTransport' => true,
        ],
		'urlManager' => [
            'enablePrettyUrl' => true,
            'rules' => [
                // your rules go here
            ],
        ],		
    ],
];

Answer by Ayleen Henson

The routing of yii2 is not accessed in this way…To visitfrontend\controllers\SiteControllerThe correct URL should bexxx.com/index.php/siteorxxx.com/siteInstead ofxxx.com/frontend/web/site
Whyxxx.com/index.phpDirect accessproject/frontend/web/index.phpThis is done by writing routing rewriting rules to your nginx / apache.,iamzcr on Answer for How do coders solve UI design problems when developing their own apps,wankey on Answer for How do coders solve UI design problems when developing their own apps,
IOS multithreading related interview questions

You need to add a. htaccess file to the web directory

Options +FollowSymLinks
IndexIgnore /
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php

Answer by Sam Robertson

I hosted my application on to the app engine of the google cloud platform.,My application contain Angular and Php Yii2 framework.,Thanks for contributing an answer to Server Fault!,Server Fault is a question and answer site for system and network administrators. It only takes a minute to sign up.

You’ll need to change the order in your app.yaml:

threadsafe: true
runtime: php55
api_version: 2

handlers:

# The root URL (/) is handled by the Go application.
# No other URLs match this pattern.

- url: /
  static_files: index.html
  upload: index.html

- url: /web-service/*
  script: web-service/yii

- url: /(.+)
  static_files: \1
  upload: (.*)

Answer by Jeremiah Duarte

Add beforeAction() function inside your PageController like below.,I just tested it on localhost and it loads, validates and saves correctly.,Inside your PageController you should have an actions() function like below.,Create an XML file named customprogressbar.xml in your res->drawable folder:

I have following config of errorHandler

'errorHandler' => [
    'errorAction' => 'page/error',
],

Понравилась статья? Поделить с друзьями:
  • Youtube vanced ошибка подключения к сети
  • Youtube studio произошла ошибка
  • Youtube ошибка сервера 400 на телефоне
  • Yeelight ошибка музыкального режима
  • Youtube ошибка сервера 400 android