Controller
- Type
- Abstract Class
- Namespace
- craft\web
- Inherits
- craft\web\Controller » yii\web\Controller (opens new window) » yii\base\Controller (opens new window) » yii\base\Component (opens new window) » yii\base\BaseObject (opens new window)
- Implements
- yii\base\Configurable (opens new window), yii\base\ViewContextInterface (opens new window)
- Extended by
- craft\controllers\AddressesController, craft\controllers\AppController, craft\controllers\AssetIndexesController, craft\controllers\AssetSettingsController, craft\controllers\AssetsController, craft\controllers\BaseElementsController, craft\controllers\BaseEntriesController, craft\controllers\BaseUpdaterController, craft\controllers\CategoriesController, craft\controllers\ChartsController, craft\controllers\ConditionsController, craft\controllers\ConfigSyncController, craft\controllers\DashboardController, craft\controllers\ElementIndexSettingsController, craft\controllers\ElementIndexesController, craft\controllers\ElementSelectorModalsController, craft\controllers\ElementsController, craft\controllers\EntriesController, craft\controllers\FieldsController, craft\controllers\FsController, craft\controllers\GlobalsController, craft\controllers\GraphqlController, craft\controllers\ImageTransformsController, 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\RelationalFieldsController, 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 (opens new window), overwriting specific methods as required.
View source (opens new window)
# Public Properties
Property | Description |
---|---|
action (opens new window) | yii\base\Action (opens new window), null (opens new window) – The action that is currently being executed. |
actionParams (opens new window) | array (opens new window) – The parameters bound to the current action. |
behaviors (opens new window) | yii\base\Behavior (opens new window) – List of behaviors attached to this component. |
defaultAction (opens new window) | string (opens new window) – The ID of the action that is used when the action ID is not specified in the request. |
enableCsrfValidation (opens new window) | boolean (opens new window) – Whether to enable CSRF validation for the actions in this controller. |
id (opens new window) | string (opens new window) – The ID of this controller. |
layout (opens new window) | string (opens new window), null (opens new window), false (opens new window) – The name of the layout to be applied to this controller's views. |
module (opens new window) | yii\base\Module (opens new window) – The module that this controller belongs to. |
modules (opens new window) | yii\base\Module (opens new window) – All ancestor modules that this controller is located within. |
request | craft\web\Request |
response | craft\web\Response |
route (opens new window) | string (opens new window) – The route (module ID, controller ID and action ID) of the current request. |
uniqueId (opens new window) | string (opens new window) – 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 (opens new window) | string (opens new window) – The directory containing the view files for this controller. |
# request
- Type
- craft\web\Request
- Default value
null
View source (opens new window)
# response
- Type
- craft\web\Response
- Default value
null
View source (opens new window)
# view
- Type
- craft\web\View
- Default value
null
The view object that can be used to render views or view files
View source (opens new window)
# Protected Properties
Property | Description |
---|---|
allowAnonymous | integer (opens new window), boolean (opens new window), integer (opens new window)[], string (opens new window)[] – Whether this controller’s actions can be accessed anonymously. |
# allowAnonymous
- Type
- integer (opens new window), boolean (opens new window), integer (opens new window)[], string (opens new window)[]
- Default value
self::ALLOW_ANONYMOUS_NEVER
Whether this controller’s actions can be accessed anonymously.
This can be set to any of the following:
false
orself::ALLOW_ANONYMOUS_NEVER
(default) – indicates that all controller actions should never be accessed anonymouslytrue
orself::ALLOW_ANONYMOUS_LIVE
– indicates that all controller actions can be accessed anonymously when the system is liveself::ALLOW_ANONYMOUS_OFFLINE
– indicates that all controller actions can be accessed anonymously when the system is offlineself::ALLOW_ANONYMOUS_LIVE | self::ALLOW_ANONYMOUS_OFFLINE
– indicates that all controller actions can be accessed anonymously when the system is live or offline- An array of action IDs (e.g.
['save-guest-entry', 'edit-guest-entry']
) – indicates that the listed action IDs can be accessed anonymously when the system is live - An array of action ID/bitwise pairs (e.g.
['save-guest-entry' => self::ALLOW_ANONYMOUS_OFFLINE]
– indicates that the listed action IDs can be accessed anonymously per the bitwise int assigned to it.
View source (opens new window)
# Public Methods
Method | Description |
---|---|
__call() (opens new window) | Calls the named method which is not a class method. |
__clone() (opens new window) | This method is called after the object is created by cloning an existing one. |
__construct() (opens new window) | |
__get() (opens new window) | Returns the value of a component property. |
__isset() (opens new window) | Checks if a property is set, i.e. defined and not null. |
__set() (opens new window) | Sets the value of a component property. |
__unset() (opens new window) | Sets a component property to be null. |
actions() (opens new window) | Declares external actions for the controller. |
afterAction() (opens new window) | This method is invoked right after an action is executed. |
asCpScreen() | Sends a control panel screen response. |
asErrorJson() | Responds to the request with a JSON error message. |
asFailure() | Sends a failure response. |
asJson() (opens new window) | Send data formatted as JSON. |
asJsonP() | Sets the response format of the given data as JSONP. |
asModelFailure() | Sends a failure response for a model. |
asModelSuccess() | Sends a success response for a model. |
asRaw() | Sets the response format of the given data as RAW. |
asSuccess() | Sends a success response. |
asXml() (opens new window) | Send data formatted as XML. |
attachBehavior() (opens new window) | Attaches a behavior to this component. |
attachBehaviors() (opens new window) | 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() (opens new window) | Binds the parameters to the action. |
canGetProperty() (opens new window) | Returns a value indicating whether a property can be read. |
canSetProperty() (opens new window) | Returns a value indicating whether a property can be set. |
className() (opens new window) | Returns the fully qualified name of this class. |
createAction() (opens new window) | Creates an action based on the given action ID. |
currentUser() | Returns the currently logged-in user. |
detachBehavior() (opens new window) | Detaches a behavior from the component. |
detachBehaviors() (opens new window) | Detaches all behaviors from the component. |
ensureBehaviors() (opens new window) | Makes sure that the behaviors declared in behaviors() (opens new window) are attached to this component. |
findLayoutFile() (opens new window) | Finds the applicable layout file. |
getBehavior() (opens new window) | Returns the named behavior object. |
getBehaviors() (opens new window) | Returns all behaviors attached to this component. |
getModules() (opens new window) | Returns all ancestor modules of this controller. |
getRoute() (opens new window) | Returns the route of the current request. |
getUniqueId() (opens new window) | Returns the unique ID of the controller. |
getView() | Returns the view object that can be used to render views or view files |
getViewPath() (opens new window) | Returns the directory containing view files for this controller. |
goBack() (opens new window) | Redirects the browser to the last visited page. |
goHome() (opens new window) | Redirects the browser to the home page. |
hasEventHandlers() (opens new window) | Returns a value indicating whether there is any handler attached to the named event. |
hasMethod() (opens new window) | Returns a value indicating whether a method is defined. |
hasProperty() (opens new window) | Returns a value indicating whether a property is defined for this component. |
init() | Initializes the object. |
off() (opens new window) | Detaches an existing event handler from this component. |
on() (opens new window) | 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() (opens new window) | Refreshes the current page. |
render() (opens new window) | Renders a view and applies layout if available. |
renderAjax() (opens new window) | Renders a view in response to an AJAX request. |
renderContent() (opens new window) | Renders a static string by applying a layout. |
renderFile() (opens new window) | Renders a view file. |
renderPartial() (opens new window) | Renders a view without applying layout. |
renderTemplate() | Sends a rendered template response. |
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() (opens new window) | Runs a request specified in terms of a route. |
runAction() (opens new window) | 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() (opens new window) | Sets the view object to be used by this controller. |
setViewPath() (opens new window) | Sets the directory that contains the view files. |
trigger() (opens new window) | Triggers an event. |
# asCpScreen()
- Since
- 4.0.0
Sends a control panel screen response.
View source (opens new window)
Returns
# asErrorJson()
DEPRECATED
Deprecated in 4.0.0. asFailure() should be used instead.
Responds to the request with a JSON error message.
View source (opens new window)
Arguments
$error
(string (opens new window)) – The error message.
Returns
yii\web\Response (opens new window)
# asFailure()
- Since
- 4.0.0
Sends a failure response.
View source (opens new window)
Arguments
$message
(string (opens new window), null (opens new window))$data
(array (opens new window)) – Additional data to include in the JSON response$routeParams
(array (opens new window)) – The route params to send back to the template
Returns
yii\web\Response (opens new window), null (opens new window)
# asJsonP()
Sets the response format of the given data as JSONP.
See also:
- yii\web\Response::$format (opens new window)
- yii\web\Response::FORMAT_JSONP (opens new window)
- yii\web\JsonResponseFormatter (opens new window)
View source (opens new window)
Arguments
$data
(mixed
) – The data that should be formatted.
Returns
yii\web\Response (opens new window) – A response that is configured to send $data
formatted as JSON.
# asModelFailure()
- Since
- 4.0.0
Sends a failure response for a model.
View source (opens new window)
Arguments
$model
(yii\base\Model (opens new window), craft\base\ModelInterface) – The model that was being operated on$message
(string (opens new window), null (opens new window))$modelName
(string (opens new window), null (opens new window)) – The route param name that the model should be set to$data
(array (opens new window)) – Additional data to include in the JSON response$routeParams
(array (opens new window)) – Additional route params that should be set for the next controller action
Returns
yii\web\Response (opens new window), null (opens new window)
# asModelSuccess()
- Since
- 4.0.0
Sends a success response for a model.
View source (opens new window)
Arguments
$model
(yii\base\Model (opens new window), craft\base\ModelInterface) – The model that was being operated on$message
(string (opens new window), null (opens new window))$modelName
(string (opens new window), null (opens new window)) – The route param name that the model should be set to$data
(array (opens new window)) – Additional data to include in the JSON response$redirect
(string (opens new window), null (opens new window)) – The default URL to redirect the request
Returns
yii\web\Response (opens new window)
# asRaw()
Sets the response format of the given data as RAW.
See also:
View source (opens new window)
Arguments
$data
(mixed
) – The data that should not be formatted.
Returns
yii\web\Response (opens new window) – A response that is configured to send $data
without formatting.
# asSuccess()
- Since
- 4.0.0
Sends a success response.
View source (opens new window)
Arguments
$message
(string (opens new window), null (opens new window))$data
(array (opens new window)) – Additional data to include in the JSON response$redirect
(string (opens new window), null (opens new window)) – The URL to redirect the request$notificationSettings
(array (opens new window)) – Control panel notification settings
Returns
yii\web\Response (opens new window), null (opens new window)
# beforeAction()
This method is invoked right before an action is executed.
The method will trigger the EVENT_BEFORE_ACTION (opens new window) 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): bool
{
// 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
}
View source (opens new window)
Arguments
$action
(yii\base\Action (opens new window)) – The action to be executed.
Returns
boolean (opens new window) – Whether the action should continue to run.
Throws
- yii\web\BadRequestHttpException (opens new window)
if the request is missing a valid CSRF token - yii\web\ForbiddenHttpException (opens new window)
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 (opens new window)
# behaviors()
Returns a list of behaviors that this component should behave as.
Child classes may override this method to specify the behaviors they want to behave as.
The return value of this method should be an array of behavior objects or configurations indexed by behavior names. A behavior configuration can be either a string specifying the behavior class or an array of the following structure:
'behaviorName' => [
'class' => 'BehaviorClass',
'property1' => 'value1',
'property2' => 'value2',
]
Note that a behavior class must extend from \craft\web\Behavior
. Behaviors can be attached using a name or anonymously.
When a name is used as the array key, using this name, the behavior can later be retrieved using getBehavior() (opens new window)
or be detached using detachBehavior() (opens new window). Anonymous behaviors can not be retrieved or detached.
Behaviors declared in this method will be attached to the component automatically (on demand).
View source (opens new window)
Returns
array (opens new window) – The behavior configurations.
# currentUser()
- Since
- 4.3.0
Returns the currently logged-in user.
See also yii\web\User::getIdentity() (opens new window) View source (opens new window)
Arguments
$autoRenew
(boolean (opens new window))
Returns
craft\elements\User, null (opens new window)
# getView()
Returns the view object that can be used to render views or view files
View source (opens new window)
Returns
# init()
Initializes the object.
This method is invoked at the end of the constructor after the object is initialized with the given configuration.
View source (opens new window)
Throws
- yii\base\InvalidConfigException (opens new window)
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']);
View source (opens new window)
Arguments
$url
(string (opens new window), array (opens new window), null (opens new window)) – The URL to be redirected to. This can be in one of the following formats:a string representing a URL (e.g. "https://example.com")
a string representing a URL alias (e.g. "@example.com")
an array in the format of
[$route, ...name-value pairs...]
(e.g.['site/index', 'ref' => 1]
) yii\helpers\Url::to() (opens new window) will be used to convert the array into a URL.
Any relative URL that starts with a single forward slash "/" will be converted into an absolute one by prepending it with the host info of the current request.
$statusCode
(integer (opens new window)) – The HTTP status code. Defaults to 302. See https://tools.ietf.org/html/rfc2616#section-10 (opens new window) for details about HTTP status code
Returns
yii\web\Response (opens new window) – The current response object
# redirectToPostedUrl()
Redirects to the URI specified in the POST.
View source (opens new window)
Arguments
$object
(object (opens new window), null (opens new window)) – Object containing properties that should be parsed for in the URL.$default
(string (opens new window), null (opens new window)) – 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
yii\web\Response (opens new window)
Throws
- yii\web\BadRequestHttpException (opens new window)
if the redirect param was tampered with
# renderTemplate()
Sends a rendered template response.
View source (opens new window)
Arguments
$template
(string (opens new window)) – The name of the template to load$variables
(array (opens new window)) – The variables that should be available to the template$templateMode
(string (opens new window), null (opens new window)) – The template mode to use
Returns
yii\web\Response (opens new window)
Throws
- yii\base\InvalidArgumentException (opens new window)
if the view file does not exist.
# requireAcceptsJson()
Throws a 400 error if the request doesn't accept JSON.
View source (opens new window)
Throws
- yii\web\BadRequestHttpException (opens new window)
if the request doesn't accept JSON
# requireAdmin()
Throws a 403 error if the current user is not an admin.
View source (opens new window)
Arguments
$requireAdminChanges
(boolean (opens new window)) – Whether the config4:allowAdminChanges (opens new window) config setting must also be enabled.
Throws
- yii\web\ForbiddenHttpException (opens new window)
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.
View source (opens new window)
Arguments
$action
(string (opens new window)) – The name of the action to check.
Throws
- yii\web\ForbiddenHttpException (opens new window)
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.
View source (opens new window)
Throws
- yii\web\BadRequestHttpException (opens new window)
if this is not a control panel request
# requireElevatedSession()
Requires that the user has an elevated session.
View source (opens new window)
Throws
- yii\web\ForbiddenHttpException (opens new window)
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.
View source (opens new window)
# requireLogin()
Redirects the user to the login template if they're not logged in.
View source (opens new window)
# requirePermission()
Checks whether the current user has a given permission, and ends the request with a 403 error if they don’t.
View source (opens new window)
Arguments
$permissionName
(string (opens new window)) – The name of the permission.
Throws
- yii\web\ForbiddenHttpException (opens new window)
if the current user doesn’t have the required permission
# requirePostRequest()
Throws a 400 error if this isn’t a POST request
View source (opens new window)
Throws
- yii\web\BadRequestHttpException (opens new window)
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.
View source (opens new window)
Throws
- yii\web\BadRequestHttpException (opens new window)
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 (opens new window)
Throws
- yii\web\BadRequestHttpException (opens new window)
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.
View source (opens new window)
Arguments
$default
(string (opens new window), null (opens new window)) – The default message, if nosuccessMessage
param was sent$settings
(array (opens new window)) – Control panel notification settings
# 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.
View source (opens new window)
Arguments
$default
(string (opens new window), null (opens new window)) – The default message, if nosuccessMessage
param was sent$settings
(array (opens new window)) – Control panel notification settings
# Protected Methods
Method | Description |
---|---|
bindInjectedParams() (opens new window) | Fills parameters based on types and names in action method signature. |
defineBehaviors() | Returns the behaviors to attach to this class. |
getPostedRedirectUrl() | Gets the redirect param specified in the POST data. |
# defineBehaviors()
- Since
- 4.5.0
Returns the behaviors to attach to this class.
See behaviors() for details about what should be returned.
Controllers should override this method instead of behaviors() so EVENT_DEFINE_BEHAVIORS handlers can modify the class-defined behaviors.
View source (opens new window)
Returns
# getPostedRedirectUrl()
- Since
- 4.0.0
Gets the redirect
param specified in the POST data.
View source (opens new window)
Arguments
$object
(object (opens new window), null (opens new window)) – Object containing properties that should be parsed for in the URL.
Returns
string (opens new window), null (opens new window)
Throws
- yii\web\BadRequestHttpException (opens new window)
if the redirect param was tampered with
# Constants
Constant | Description |
---|---|
ALLOW_ANONYMOUS_LIVE | |
ALLOW_ANONYMOUS_NEVER | |
ALLOW_ANONYMOUS_OFFLINE |
# Events
# EVENT_DEFINE_BEHAVIORS
- Type
- craft\events\DefineBehaviorsEvent
- Since
- 4.5.0
The event that is triggered when defining the class behaviors
See also behaviors()