Craft 3 Class Reference

Abstract Class craft\web\Controller

Inheritance
craft\web\Controller » yii\web\Controller » yii\base\Controller » yii\base\Component » yii\base\BaseObject
Implements
yii\base\Configurable, yii\base\ViewContextInterface
Subclasses
craft\controllers\AppController, craft\controllers\AssetTransformsController, craft\controllers\AssetsController, craft\controllers\BaseElementsController, craft\controllers\BaseEntriesController, craft\controllers\BaseUpdaterController, craft\controllers\CategoriesController, craft\controllers\ChartsController, craft\controllers\DashboardController, craft\controllers\ElementIndexSettingsController, craft\controllers\ElementIndexesController, craft\controllers\ElementsController, craft\controllers\EntriesController, craft\controllers\EntryRevisionsController, craft\controllers\FieldsController, craft\controllers\GlobalsController, craft\controllers\InstallController, craft\controllers\NotFoundController, craft\controllers\PluginStoreController, craft\controllers\PluginsController, craft\controllers\QueueController, craft\controllers\RebrandController, 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
Available since version
3.0
Source Code
https://github.com/craftcms/cms/blob/master/src/web/Controller.php

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 Type Description Defined By
$action yii\base\Action The action that is currently being executed. yii\base\Controller
$actionParams array The parameters bound to the current action. yii\web\Controller
$defaultAction string The ID of the action that is used when the action ID is not specified in the request. yii\base\Controller
$enableCsrfValidation boolean Whether to enable CSRF validation for the actions in this controller. yii\web\Controller
$id string The ID of this controller. yii\base\Controller
$layout null, string, false The name of the layout to be applied to this controller's views. yii\base\Controller
$module yii\base\Module The module that this controller belongs to. yii\base\Controller
Protected Properties
Property Type Description Defined By
$allowAnonymous boolean, string[] Whether this controller’s actions can be accessed anonymously If set to false, you are required to be logged in to execute any of the given controller's actions. craft\web\Controller
Public Methods
Method Description Defined By
__call() Calls the named method which is not a class method. yii\base\BaseObject
__clone() This method is called after the object is created by cloning an existing one. yii\base\Component
__construct() Constructor. yii\base\BaseObject
__get() Returns the value of an object property. yii\base\BaseObject
__isset() Checks if a property is set, i.e. defined and not null. yii\base\BaseObject
__set() Sets value of an object property. yii\base\BaseObject
__unset() Sets an object property to null. yii\base\BaseObject
actions() Declares external actions for the controller. yii\base\Controller
afterAction() This method is invoked right after an action is executed. yii\base\Controller
asErrorJson() Responds to the request with a JSON error message. craft\web\Controller
asJson() Send data formatted as JSON. yii\web\Controller
asJsonP() Sets the response format of the given data as JSONP. craft\web\Controller
asRaw() Sets the response format of the given data as RAW. craft\web\Controller
asXml() Send data formatted as XML. yii\web\Controller
attachBehavior() Attaches a behavior to this component. yii\base\Component
attachBehaviors() Attaches a list of behaviors to the component. yii\base\Component
beforeAction() {@inheritdoc} craft\web\Controller
behaviors() Returns a list of behaviors that this component should behave as. yii\base\Component
bindActionParams() Binds the parameters to the action. yii\base\Controller
canGetProperty() Returns a value indicating whether a property can be read. yii\base\BaseObject
canSetProperty() Returns a value indicating whether a property can be set. yii\base\BaseObject
className() Returns the fully qualified name of this class. yii\base\BaseObject
createAction() Creates an action based on the given action ID. yii\base\Controller
detachBehavior() Detaches a behavior from the component. yii\base\Component
detachBehaviors() Detaches all behaviors from the component. yii\base\Component
ensureBehaviors() Makes sure that the behaviors declared in behaviors() are attached to this component. yii\base\Component
findLayoutFile() Finds the applicable layout file. yii\base\Controller
getBehavior() Returns the named behavior object. yii\base\Component
getBehaviors() Returns all behaviors attached to this component. yii\base\Component
getModules() Returns all ancestor modules of this controller. yii\base\Controller
getRoute() Returns the route of the current request. yii\base\Controller
getUniqueId() Returns the unique ID of the controller. yii\base\Controller
getView() Returns the view object that can be used to render views or view files. yii\base\Controller
getViewPath() yii\base\ViewContextInterface
goBack() Redirects the browser to the last visited page. yii\web\Controller
goHome() Redirects the browser to the home page. yii\web\Controller
hasEventHandlers() Returns a value indicating whether there is any handler attached to the named event. yii\base\Component
hasMethod() Returns a value indicating whether a method is defined. yii\base\BaseObject
hasProperty() Returns a value indicating whether a property is defined. yii\base\BaseObject
init() Initializes the object. yii\base\BaseObject
off() Detaches an existing event handler from this component. yii\base\Component
on() Attaches an event handler to an event. yii\base\Component
redirect() Redirects the browser to the specified URL. craft\web\Controller
redirectToPostedUrl() Redirects to the URI specified in the POST. craft\web\Controller
refresh() Refreshes the current page. yii\web\Controller
render() Renders a view and applies layout if available. yii\base\Controller
renderAjax() Renders a view in response to an AJAX request. yii\web\Controller
renderContent() Renders a static string by applying a layout. yii\base\Controller
renderFile() Renders a view file. yii\base\Controller
renderPartial() Renders a view without applying layout. yii\base\Controller
renderTemplate() Renders a template. craft\web\Controller
requireAcceptsJson() Throws a 400 error if the request doesn't accept JSON. craft\web\Controller
requireAdmin() Throws a 403 error if the current user is not an admin. craft\web\Controller
requireAuthorization() Checks whether the current user can perform a given action, and ends the request with a 403 error if they don’t. craft\web\Controller
requireElevatedSession() Requires that the user has an elevated session. craft\web\Controller
requireLogin() Redirects the user to the login template if they're not logged in. craft\web\Controller
requirePermission() Checks whether the current user has a given permission, and ends the request with a 403 error if they don’t. craft\web\Controller
requirePostRequest() Throws a 400 error if this isn’t a POST request craft\web\Controller
requireToken() Throws a 400 error if the current request doesn’t have a valid token. craft\web\Controller
run() Runs a request specified in terms of a route. yii\base\Controller
runAction() Runs an action within this controller with the specified action ID and parameters. craft\web\Controller
setView() Sets the view object to be used by this controller. yii\base\Controller
setViewPath() Sets the directory that contains the view files. yii\base\Controller
trigger() Triggers an event. yii\base\Component
Events
Event Type Description Defined By
EVENT_AFTER_ACTION yii\base\ActionEvent An event raised right after executing a controller action. yii\base\Controller
EVENT_BEFORE_ACTION yii\base\ActionEvent An event raised right before executing a controller action. yii\base\Controller

Property Details

$allowAnonymous protected property #

Whether this controller’s actions can be accessed anonymously If set to false, you are required to be logged in to execute any of the given controller's actions. If set to true, anonymous access is allowed for all of the given controller's actions. If the value is an array of action IDs, then you must be logged in for any actions except for the ones in the array list. If you have a controller that where the majority of actions allow anonymous access, but you only want require login on a few, you can set this to true and call requireLogin() in the individual methods.

protected boolean, string[] $allowAnonymous false

Method Details

asErrorJson() public method #

Responds to the request with a JSON error message.

public yii\web\Response asErrorJson ( \craft\web\string $error )
$error string The error message.

asJsonP() public method #

Sets the response format of the given data as JSONP.

See also:

public yii\web\Response asJsonP ( $data )
$data mixed The data that should be formatted.
return yii\web\Response A response that is configured to send $data formatted as JSON.

asRaw() public method #

Sets the response format of the given data as RAW.

See also:

public yii\web\Response asRaw ( $data )
$data mixed The data that should not be formatted.
return yii\web\Response A response that is configured to send $data without formatting.

beforeAction() public method #

{@inheritdoc}

public void beforeAction ( $action )
$action

redirect() public method #

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']);
public yii\web\Response redirect ( $url, $statusCode 302 )
$url string, array The URL to be redirected to. This can be in one of the following formats: a string representing a URL (e.g. "http://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]) \craft\web\Url::to() 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 The HTTP status code. Defaults to 302. See https://tools.ietf.org/html/rfc2616#section-10 for details about HTTP status code
return yii\web\Response The current response object

redirectToPostedUrl() public method #

Redirects to the URI specified in the POST.

public yii\web\Response redirectToPostedUrl ( $object null, \craft\web\string $default null )
$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.
throws yii\web\BadRequestHttpException if the redirect param was tampered with

renderTemplate() public method #

Renders a template.

public yii\web\Response renderTemplate ( \craft\web\string $template, array $variables = [] )
$template string The name of the template to load
$variables array The variables that should be available to the template
throws yii\base\InvalidArgumentException if the view file does not exist.

requireAcceptsJson() public method #

Throws a 400 error if the request doesn't accept JSON.

public void requireAcceptsJson ( )
throws yii\web\BadRequestHttpException if the request doesn't accept JSON

requireAdmin() public method #

Throws a 403 error if the current user is not an admin.

public void requireAdmin ( )
throws yii\web\ForbiddenHttpException if the current user is not an admin

requireAuthorization() public method #

Checks whether the current user can perform a given action, and ends the request with a 403 error if they don’t.

public void requireAuthorization ( \craft\web\string $action )
$action string The name of the action to check.
throws yii\web\ForbiddenHttpException if the current user is not authorized

requireElevatedSession() public method #

Requires that the user has an elevated session.

public void requireElevatedSession ( )
throws yii\web\ForbiddenHttpException if the current user does not have an elevated session

requireLogin() public method #

Redirects the user to the login template if they're not logged in.

public void requireLogin ( )

requirePermission() public method #

Checks whether the current user has a given permission, and ends the request with a 403 error if they don’t.

public void requirePermission ( \craft\web\string $permissionName )
$permissionName string The name of the permission.
throws yii\web\ForbiddenHttpException if the current user doesn’t have the required permission

requirePostRequest() public method #

Throws a 400 error if this isn’t a POST request

public void requirePostRequest ( )
throws yii\web\BadRequestHttpException if the request is not a post request

requireToken() public method #

Throws a 400 error if the current request doesn’t have a valid token.

public void requireToken ( )
throws yii\web\BadRequestHttpException if the request does not have a valid token

runAction() public method #

Runs an action within this controller with the specified action ID and parameters.

If the action ID is empty, the method will use $defaultAction.

public mixed runAction ( $id, $params = [] )
$id string The ID of the action to be executed.
$params array The parameters (name-value pairs) to be passed to the action.
return mixed The result of the action.
throws yii\base\InvalidRouteException if the requested action ID cannot be resolved into an action successfully.