Controller Actions

You are viewing documentation for an unreleased version of Craft CMS. Please be aware that some pages, screenshots, and technical reference may still reflect older versions.

Controllers are Craft’s way of talking to the outside world. Pretty much everything you do with Craft is part of a request that involves a controller action (opens new window)—from updating settings to rendering an entry.

Most controllers and actions are carefully locked down with permissions to prevent malicious activity, but a select few are necessarily available to users and guests without special permissions to support features like public registration or cart management.

The following list of controller actions is non-exhaustive, but covers common patterns like logging in, creating entries, and managing an address book.

Using Forms
Start here to learn about sending data to Craft.

# Available Actions

This is not a comprehensive list! We have selected a few actions to illustrate fundamentals that many projects can benefit from—and to get you prepared to explore the rest of Craft’s HTTP API (opens new window).

Action Description
POST entries/save-entry Creates or updates an entry.
POST users/login Logs a user in.
POST users/save-user Creates or updates a user account.
POST users/upload-user-photo Sets a user’s photo.
POST users/send-password-reset-email Sends a password reset email.
GET/POST users/set-password Sets a new password on a user account.
POST users/save-address Create or update an address element.
POST users/delete-address Delete an address element.
GET users/session-info Retrieve information about the current session.
GET app/health-check Ping your app to make sure it’s up.

In each of the following examples, you’ll find a list of Supported Params (the values you can send as GET query params or in the POST body) and information about the possible Response conditions.

Supported Params can be encoded in the query string, submitted with form inputs, or sent as properties in a JSON payload.

All POST actions honor a few additional parameters, except when using an Accepts: application/json header:

  • redirect: A hashed URL or path that Craft will send the user to after a successful request (i.e. a user is registered or an entry is saved).
  • successMessage: Overrides the default flash notice for the action.
  • failMessage: Overrides the default flash error for the action.

# POST entries/save-entry

Create or update an entry the current User has appropriate permissions for.

See the Entry Form (opens new window) guide for an example of working with this action.

Note that all custom fields can updated by users. For this reason, you should not assume that custom fields are protected from modification simply because they are omitted from the form.

Similarly, if you are outputting user-submitted content anywhere on site, take special care to prevent yourself or other users from being exposed to XSS vulnerabilities (opens new window)!

# Supported Params

Param Description
author The ID of the user account that should be set as the entry author. (Defaults to the entry’s current author, or the logged-in user.)
canonicalId The ID of the entry to save, if updating an existing entry.
enabledForSite Whether the entry should be enabled for the entry’s siteId (1/0), or an array of site IDs that the entry should be enabled for. (Defaults to the enabled param.)
enabled Whether the entry should be enabled (1/0). (Defaults to enabled.)
entryId Fallback if canonicalId isn’t passed, for backwards compatibility.
entryVariable The hashed name of the variable that should reference the entry, if a validation error occurs. (Defaults to entry.)
expiryDate The expiry date for the entry. (Defaults to the current expiry date, or null.)
fieldsLocation Parameter name under which Craft will look for custom field data. (Defaults to fields.)
fields[...] Custom field values.
parentId The ID of the parent entry, if it belongs to a structure section.
postDate The post date for the entry. (Defaults to the current post date, or the current time.)
provisional Updates the current user’s provisional draft (in the control panel, this correlates to an auto-save).
revisionNotes Notes that should be stored on the new entry revision.
sectionId The ID of the section the entry will be created in. (Only for new entries. User must have appropriate permissions.)
siteId The ID of the site to save the entry in.
slug The entry slug. (Defaults to the current slug, or an auto-generated slug.)
sourceId Fallback if canonicalId isn’t passed, for backwards compatibility.
title The entry title. (Defaults to the current entry title.)
typeId The entry type ID to save the entry as. (Defaults to the current entry type for existing entries, or the first configured type for new ones.)

# Permissions

Requests to entries/save-entry must by made by a logged-in user with the appropriate permissions. Permissions are dependent upon the site, section, and the original author (for existing entries).

It is not currently possible to allow anonymous access without a plugin (opens new window).

# Response

The action’s output depends on whether the entry saved successfully and the Accept header.

State text/html application/json
Standard behavior. Standard behavior; entry available under an entry key in the response object.
Standard behavior; entry available under an entry variable, in the template. Standard behavior.

# POST users/login

Logs a user in.

See the Front-End User Accounts (opens new window) guide for an example of working with this action.

# Supported Params

Param Description
loginName The username or email of the user to login.
password The user’s password.
rememberMe Whether to keep the user logged-in for an extended period of time per the rememberedUserSessionDuration config setting (1/0).

# Response

The output of the action depends on whether the login was successful and the Accept header.

State text/html application/json
Standard behavior. Standard behavior; additional returnUrl, csrfTokenValue, and user properties are included in the response object.
Standard behavior; additional loginName, rememberMe, errorCode, and errorMessage variables will be available in the template. Standard behavior; additional loginName, rememberMe, errorCode, and errorMessage properties are included in the response object.

The errorCode corresponds to one of the craft\elements\User::AUTH_* constants (opens new window).

# POST users/save-user

Registers a new user account, or updates an existing one.

See the Front-End User Accounts (opens new window) guide for an example of working with this action.

Note that all custom fields can updated by users. For this reason, you should not assume that custom fields are protected from modification simply because they are omitted from the form.

# Supported Params

Param Description
admin Whether the user should be saved as an admin (1/0). Only assignable if the logged-in user is an admin.
currentPassword The user’s current password, which is required if email or newPassword are sent.
email The user’s email address. (Only checked if registering a new user, updating the logged-in user, or the logged-in user is allowed to administrate users.)
fieldsLocation Parameter name under which Craft will look for custom field data. (Defaults to fields.)
fields[...] Custom field values.
fullName The user’s full name. Preferred to discrete firstName and lastName params.
firstName The user’s first name. fullName is preferred.
lastName The user’s last name. fullName is preferred.
newPassword The user’s new password, if updating the logged-in user’s account. (If registering a new user, send password.)
passwordResetRequired Whether the user must reset their password before logging in again (1/0). Only assignable if the logged-in user is an admin.
password The user’s password, when registering a new user. (Has no effect if deferPublicRegistrationPassword is true. To change the current user’s password, send newPassword.)
photo An uploaded user photo. Use <input type="file">.
sendVerificationEmail Whether a verification email should be sent before accepting the new email (1/0). (Only used if email verification is enabled, and the logged-in user is allowed to opt out of sending it.)
userId The ID of the user to save, if updating an existing user.
userVariable The hashed name of the variable that should reference the user, if a validation error occurs. (Defaults to user.)
username The user’s username. (Only checked if the useEmailAsUsername config setting is false.)

# Permissions

Special permissions are required to allow users to administrate or update other users. A user can always update their own account.

Granting administrative permissions to front-end users opens your site up to permissions escalation and significant abuse.

# Response

The output depends on whether the user save action was successful and the Accept header.

State text/html application/json
Standard behavior; default redirection uses the activateAccountSuccessPath config setting, if email verification is not required. Standard behavior; additional id and csrfTokenValue keys.
Standard behavior; user will be available in the template under a variable determined by the userVariable param, or user by default. Standard behavior.

# POST users/upload-user-photo

Sets a user’s photo to an uploaded image.

You can update a user’s other properties and fields at the same time as uploading a photo, via users/save-user.

# Supported Params

Param Description
userId ID of the user. Required, pass {{ currentUser.id }} to change a user’s own photo.
photo Uploaded image. Use <input type="file">.

Files cannot be uploaded using Content-Type: application/json.

# Response

The output depends on whether the upload was successful. Only JSON is returned, and the request must include the Accept: application/json header.

State application/json
Standard behavior; html and photoId properties. html is only useful in control panel contexts.
Standard behavior; additional error key is available in the response object, with the exception message.

# POST users/send-password-reset-email

Sends a password reset email.

See the Front-End User Accounts (opens new window) guide for an example of working with this action.

# Supported Params

Param Description
loginName The username or email of the user to send a password reset email for.
userId The ID of the user to send a password reset email for. (Only checked if the logged-in user has permission to edit other users.)

# Response

The output of the action depends on whether the user exists, the reset password email was sent successfully, and the Accept header.

State text/html application/json
Standard behavior. Standard behavior.
Standard behavior; additional errors and loginName variables are passed to the template. Standard behavior; additional errors and loginName keys are available in the response object.

The errors variable may include multiple discrete failure messages, but the standard message variable will still be an accurate summary.

# GET/POST users/set-password

A GET request displays a form allowing a user to set a new password on their account, and POST sets a new password on a user account. If the user is pending, their account will be activated.

This action is responsible for rendering the route defined by the setPasswordPath setting.

# Supported Params

Param Description
code GET/POST The user’s verification code. Craft will provide this in URLs generated from the control panel, or when a link is sent via email.
id GET/POST The user’s UUID.
newPassword POST The user’s new password.

code and id are required for both GET and POST requests; users may click a link from an email that includes both as query params—it’s your responsibility to pass these to Craft as hidden fields (along with newPassword) in a subsequent form submission.

See the Front-End User Accounts (opens new window) article for an example of how to set up this form.

# Response

The output of the action depends on the request method, whether the password was updated successfully, and the Accept header.

For GET requests:

State text/html
Standard behavior; template determined by setPasswordPath is rendered with id and code variables available.
Standard behavior; exception message will point to the issue—commonly, a missing or invalid token.

For POST requests:

State text/html application/json
Standard behavior; redirection depends on the autoLoginAfterAccountActivation and setPasswordSuccessPath config settings, and whether the user has access to the control panel. Standard behavior; additional csrfTokenName key will be available in the response object.
Standard behavior; errors , code, id, and newUser variables will be passed to the resulting template. Standard behavior.

# POST users/save-address

Saves or updates an address element against the current user’s account.

# Supported Params

Param Description
addressId An existing address’s ID can be sent to update it, as long as it’s owned by the current user.
userId Owner of the new address. Owners cannot be changed after creation, and new addresses can only be created for the current user or other users they are allowed to edit.
fullName Name for the address. First and last names are not stored discretely, but can by submitted separately.
firstName Can be submitted independently from lastName, but will be combined for storage.
lastName Can be submitted independently from firstName, but will be combined for storage.
countryCode Required to localize and validate the rest of the address.
organization Additional line for an organization or business name.
organizationTaxId Tax/VAT ID.
latitude and longitude GPS coordinates for the address. Not automatically populated or validated.
fields[...] Custom field values.
fieldsLocation Parameter name under which Craft will look for custom field data. (Defaults to fields.)

This list is incomplete!

The remaining params depend upon the submitted countryCode—refer to the commerceguys/addressing library (opens new window) for a comprehensive list, or learn more about managing addresses in Craft.

# Response

The output of the action depends on whether the address was saved successfully and the Accept header.

State text/html application/json
Standard behavior. Standard behavior; address available under the address property in the response object.
Standard behavior; additional address variable will be passed to the resulting template. Standard behavior; additional address property will be available in the response object.

# POST users/delete-address

Deletes an address owned by the current user or another user they can edit.

# Supported Params

Param Description
addressId An existing address ID, owned by the current user or a user they’re allowed to edit.

# Response

State text/html application/json
Standard behavior. Standard behavior; additional address property will be available in the response object.
Standard behavior. Standard behavior.

# GET users/session-info

Retrieves information about the current session. Data is returned as JSON, and is only intended for consumption via Ajax.

# Response

Only JSON responses are sent, but its content will differ for guests and logged-in users.

State application/json
Standard behavior; response object will contain at least isGuest and timeout keys, plus a csrfTokenName and csrfTokenValue (when CSRF protection is enabled), and the current user’s id, uid, username, and email (if logged in).
Standard behavior.

# GET app/health-check

A “no-op (opens new window)” action provided for automated monitoring.

# Response

The response will be successful (but empty) in all but “exceptional” situations, like an issue connecting to the database. Read more about the criteria (opens new window) for a successful health check.

State Any
An empty document with a 200 status code.
400- or 500-level status, with an error message or stack trace (in devMode, or when the current user has enabled the “show full exception views” preference enabled).

# Plugins + Custom Actions

Many plugins expose functionality via their own controllers and actions. Their accepted parameters and response types are entirely up to the author, but the fundamentals will be the same. Consult the appropriate documentation for specifics!

Here are some examples in our own plugins:

Custom modules can also provide actions via a Controller.