Controller ​
- Type
- Abstract Class
- Namespace
- craft\web
- Inherits
- craft\web\Controller » yii\web\Controller » yii\base\Controller » yii\base\Component » yii\base\BaseObject
- Implements
- yii\base\Configurable, yii\base\ViewContextInterface
- Extended by
- craft\controllers\AppController, craft\controllers\AssetSettingsController, craft\controllers\AssetTransformsController, craft\controllers\AssetsController, craft\controllers\BaseElementsController, craft\controllers\BaseEntriesController, craft\controllers\BaseUpdaterController, craft\controllers\CategoriesController, craft\controllers\ChartsController, craft\controllers\ConfigSyncController, craft\controllers\DashboardController, craft\controllers\DraftsController, craft\controllers\EditController, craft\controllers\ElementIndexSettingsController, craft\controllers\ElementIndexesController, craft\controllers\ElementsController, craft\controllers\EntriesController, craft\controllers\EntryRevisionsController, craft\controllers\FieldsController, craft\controllers\GlobalsController, craft\controllers\GraphqlController, craft\controllers\InstallController, craft\controllers\LivePreviewController, craft\controllers\NotFoundController, craft\controllers\PluginStoreController, craft\controllers\PluginsController, craft\controllers\PreviewController, craft\controllers\ProjectConfigController, craft\controllers\QueueController, craft\controllers\RebrandController, craft\controllers\RedirectController, craft\controllers\RoutesController, craft\controllers\SectionsController, craft\controllers\SitesController, craft\controllers\StructuresController, craft\controllers\SystemMessagesController, craft\controllers\SystemSettingsController, craft\controllers\TagsController, craft\controllers\TemplatesController, craft\controllers\UpdaterController, craft\controllers\UserSettingsController, craft\controllers\UsersController, craft\controllers\UtilitiesController, craft\controllers\VolumesController, craft\controllers\pluginstore\InstallController, craft\controllers\pluginstore\RemoveController, craft\test\mockclasses\controllers\TestController
- Since
- 3.0.0
Controller is a base class that all controllers in Craft extend.
It extends Yii’s yii\web\Controller, overwriting specific methods as required.
Public Properties ​
Property | Description |
---|---|
action | yii\base\Action, null – The action that is currently being executed. |
actionParams | array – The parameters bound to the current action. |
behaviors | yii\base\Behavior – List of behaviors attached to this component. |
defaultAction | string – The ID of the action that is used when the action ID is not specified in the request. |
enableCsrfValidation | boolean – Whether to enable CSRF validation for the actions in this controller. |
id | string – The ID of this controller. |
layout | string, null, false – The name of the layout to be applied to this controller's views. |
module | yii\base\Module – The module that this controller belongs to. |
modules | yii\base\Module – All ancestor modules that this controller is located within. |
request | craft\web\Request |
response | craft\web\Response |
route | string – The route (module ID, controller ID and action ID) of the current request. |
uniqueId | string – The controller ID that is prefixed with the module ID (if any). |
view | craft\web\View – The view object that can be used to render views or view files |
viewPath | string – The directory containing the view files for this controller. |
request
​
- Type
- craft\web\Request
- Default value
null
response
​
- Type
- craft\web\Response
- Default value
null
view
​
- Type
- craft\web\View
- Default value
null
The view object that can be used to render views or view files
Protected Properties ​
Property | Description |
---|---|
allowAnonymous | integer, boolean, integer[], string[] – Whether this controller’s actions can be accessed anonymously. |
allowAnonymous
​
Whether this controller’s actions can be accessed anonymously.
Public Methods ​
Method | Description |
---|---|
__call() | Calls the named method which is not a class method. |
__clone() | This method is called after the object is created by cloning an existing one. |
__construct() | |
__get() | Returns the value of a component property. |
__isset() | Checks if a property is set, i.e. defined and not null. |
__set() | Sets the value of a component property. |
__unset() | Sets a component property to be null. |
actions() | Declares external actions for the controller. |
afterAction() | This method is invoked right after an action is executed. |
asErrorJson() | Responds to the request with a JSON error message. |
asJson() | Send data formatted as JSON. |
asJsonP() | Sets the response format of the given data as JSONP. |
asRaw() | Sets the response format of the given data as RAW. |
asXml() | Send data formatted as XML. |
attachBehavior() | Attaches a behavior to this component. |
attachBehaviors() | Attaches a list of behaviors to the component. |
beforeAction() | This method is invoked right before an action is executed. |
behaviors() | Returns a list of behaviors that this component should behave as. |
bindActionParams() | Binds the parameters to the action. |
canGetProperty() | Returns a value indicating whether a property can be read. |
canSetProperty() | Returns a value indicating whether a property can be set. |
className() | Returns the fully qualified name of this class. |
createAction() | Creates an action based on the given action ID. |
detachBehavior() | Detaches a behavior from the component. |
detachBehaviors() | Detaches all behaviors from the component. |
ensureBehaviors() | Makes sure that the behaviors declared in behaviors() are attached to this component. |
findLayoutFile() | Finds the applicable layout file. |
getBehavior() | Returns the named behavior object. |
getBehaviors() | Returns all behaviors attached to this component. |
getModules() | Returns all ancestor modules of this controller. |
getRoute() | Returns the route of the current request. |
getUniqueId() | Returns the unique ID of the controller. |
getView() | Returns the view object that can be used to render views or view files |
getViewPath() | Returns the directory containing view files for this controller. |
goBack() | Redirects the browser to the last visited page. |
goHome() | Redirects the browser to the home page. |
hasEventHandlers() | Returns a value indicating whether there is any handler attached to the named event. |
hasMethod() | Returns a value indicating whether a method is defined. |
hasProperty() | Returns a value indicating whether a property is defined for this component. |
init() | Initializes the object. |
off() | Detaches an existing event handler from this component. |
on() | Attaches an event handler to an event. |
redirect() | Redirects the browser to the specified URL. |
redirectToPostedUrl() | Redirects to the URI specified in the POST. |
refresh() | Refreshes the current page. |
render() | Renders a view and applies layout if available. |
renderAjax() | Renders a view in response to an AJAX request. |
renderContent() | Renders a static string by applying a layout. |
renderFile() | Renders a view file. |
renderPartial() | Renders a view without applying layout. |
renderTemplate() | Renders a template. |
requireAcceptsJson() | Throws a 400 error if the request doesn't accept JSON. |
requireAdmin() | Throws a 403 error if the current user is not an admin. |
requireAuthorization() | Checks whether the current user can perform a given action, and ends the request with a 403 error if they don’t. |
requireCpRequest() | Throws a 400 error if the current request isn’t a control panel request. |
requireElevatedSession() | Requires that the user has an elevated session. |
requireGuest() | Redirects the user to the account template if they are logged in. |
requireLogin() | Redirects the user to the login template if they're not logged in. |
requirePermission() | Checks whether the current user has a given permission, and ends the request with a 403 error if they don’t. |
requirePostRequest() | Throws a 400 error if this isn’t a POST request |
requireSiteRequest() | Throws a 400 error if the current request isn’t a site request. |
requireToken() | Throws a 400 error if the current request doesn’t have a valid Craft token. |
run() | Runs a request specified in terms of a route. |
runAction() | Runs an action within this controller with the specified action ID and parameters. |
setFailFlash() | Sets an error flash message on the user session. |
setSuccessFlash() | Sets a success flash message on the user session. |
setView() | Sets the view object to be used by this controller. |
setViewPath() | Sets the directory that contains the view files. |
trigger() | Triggers an event. |
asErrorJson()
​
Responds to the request with a JSON error message.
Arguments ​
$error
(string) – The error message.
Returns ​
asJsonP()
​
Sets the response format of the given data as JSONP.
See also:
Arguments ​
$data
(mixed
) – The data that should be formatted.
Returns ​
yii\web\Response – A response that is configured to send $data
formatted as JSON.
asRaw()
​
Sets the response format of the given data as RAW.
See also:
Arguments ​
$data
(mixed
) – The data that should not be formatted.
Returns ​
yii\web\Response – A response that is configured to send $data
without formatting.
beforeAction()
​
This method is invoked right before an action is executed.
The method will trigger the EVENT_BEFORE_ACTION event. The return value of the method will determine whether the action should continue to run.
In case the action should not run, the request should be handled inside of the beforeAction
code by either providing the necessary output or redirecting the request. Otherwise the response will be empty.
If you override this method, your code should look like the following:
public function beforeAction($action)
{
// your custom code here, if you want the code to run before action filters,
// which are triggered on the [EVENT_BEFORE_ACTION](https://www.yiiframework.com/doc/api/2.0/yii-base-controller#EVENT_BEFORE_ACTION-detail) event, e.g. PageCache or AccessControl
if (!parent::beforeAction($action)) {
return false;
}
// other custom code here
return true; // or false to not run the action
}
Arguments ​
$action
(yii\base\Action) – The action to be executed.
Returns ​
boolean – Whether the action should continue to run.
Throws ​
- yii\web\BadRequestHttpException
if the request is missing a valid CSRF token - yii\web\ForbiddenHttpException
if the user is not logged in or lacks the necessary permissions - craft\web\ServiceUnavailableHttpException
if the system is offline and the user isn't allowed to access it - yii\web\UnauthorizedHttpException
getView()
​
Returns the view object that can be used to render views or view files
Returns ​
craft\web\View –
init()
​
Initializes the object.
This method is invoked at the end of the constructor after the object is initialized with the given configuration.
Throws ​
- yii\base\InvalidConfigException
if allowAnonymous is set to an invalid value
redirect()
​
Redirects the browser to the specified URL.
This method is a shortcut to craft\web\Response::redirect().
You can use it in an action by returning the craft\web\Response directly:
// stop executing this action and redirect to login page
return $this->redirect(['login']);
Arguments ​
$url
(string, array) – The URL to be redirected to. This can be in one of the following formats:$statusCode
(integer) – The HTTP status code. Defaults to 302. See https://tools.ietf.org/html/rfc2616#section-10 for details about HTTP status code
Returns ​
yii\web\Response – The current response object
redirectToPostedUrl()
​
Redirects to the URI specified in the POST.
Arguments ​
$object
(mixed
) – Object containing properties that should be parsed for in the URL.$default
(string, null) – The default URL to redirect them to, if no 'redirect' parameter exists. If this is left null, then the current request’s path will be used.
Returns ​
Throws ​
- yii\web\BadRequestHttpException
if the redirect param was tampered with
renderTemplate()
​
Renders a template.
Arguments ​
$template
(string) – The name of the template to load$variables
(array) – The variables that should be available to the template$templateMode
(string) – The template mode to use
Returns ​
Throws ​
- yii\base\InvalidArgumentException
if the view file does not exist.
requireAcceptsJson()
​
Throws a 400 error if the request doesn't accept JSON.
Throws ​
- yii\web\BadRequestHttpException
if the request doesn't accept JSON
requireAdmin()
​
Throws a 403 error if the current user is not an admin.
Arguments ​
$requireAdminChanges
(boolean) – Whether the config3:allowAdminChanges config setting must also be enabled.
Throws ​
- yii\web\ForbiddenHttpException
if the current user is not an admin
requireAuthorization()
​
Checks whether the current user can perform a given action, and ends the request with a 403 error if they don’t.
Arguments ​
$action
(string) – The name of the action to check.
Throws ​
- yii\web\ForbiddenHttpException
if the current user is not authorized
requireCpRequest()
​
- Since
- 3.1.0
Throws a 400 error if the current request isn’t a control panel request.
Throws ​
- yii\web\BadRequestHttpException
if this is not a control panel request
requireElevatedSession()
​
Requires that the user has an elevated session.
Throws ​
- yii\web\ForbiddenHttpException
if the current user does not have an elevated session
requireGuest()
​
- Since
- 3.4.0
Redirects the user to the account template if they are logged in.
requireLogin()
​
Redirects the user to the login template if they're not logged in.
requirePermission()
​
Checks whether the current user has a given permission, and ends the request with a 403 error if they don’t.
Arguments ​
$permissionName
(string) – The name of the permission.
Throws ​
- yii\web\ForbiddenHttpException
if the current user doesn’t have the required permission
requirePostRequest()
​
Throws a 400 error if this isn’t a POST request
Throws ​
- yii\web\BadRequestHttpException
if the request is not a post request
requireSiteRequest()
​
- Since
- 3.1.0
Throws a 400 error if the current request isn’t a site request.
Throws ​
- yii\web\BadRequestHttpException
if the request is not a site request
requireToken()
​
Throws a 400 error if the current request doesn’t have a valid Craft token.
See also craft\web\Request::getToken()View source
Throws ​
- yii\web\BadRequestHttpException
if the request does not have a valid Craft token
setFailFlash()
​
- Since
- 3.5.0
Sets an error flash message on the user session.
If a hashed failMessage
param was sent with the request, that will be used instead of the provided default.
Arguments ​
setSuccessFlash()
​
- Since
- 3.5.0
Sets a success flash message on the user session.
If a hashed successMessage
param was sent with the request, that will be used instead of the provided default.
Arguments ​
Protected Methods ​
Method | Description |
---|---|
bindInjectedParams() | Fills parameters based on types and names in action method signature. |
Constants ​
Constant | Description |
---|---|
ALLOW_ANONYMOUS_LIVE | |
ALLOW_ANONYMOUS_NEVER | |
ALLOW_ANONYMOUS_OFFLINE |