CakePHP
  • Documentation
    • Book
    • API
    • Videos
    • Reporting Security Issues
    • Privacy Policy
    • Logos & Trademarks
  • Business Solutions
  • Swag
  • Road Trip
  • Team
  • Community
    • Community
    • Get Involved
    • Issues (Github)
    • Bakery
    • Featured Resources
    • Training
    • Meetups
    • My CakePHP
    • CakeFest
    • Newsletter
    • Linkedin
    • YouTube
    • Facebook
    • Twitter
    • Mastodon
    • Help & Support
    • Forum
    • Stack Overflow
    • IRC
    • Slack
    • Paid Support
CakePHP

C CakePHP 3.2 Red Velvet API

  • Project:
    • CakePHP
      • CakePHP
      • Authentication
      • Authorization
      • Chronos
      • Elastic Search
      • Queue
  • Version:
    • 3.2
      • 5.2
      • 5.1
      • 5.0
      • 4.6
      • 4.5
      • 4.4
      • 4.3
      • 4.2
      • 4.1
      • 4.0
      • 3.10
      • 3.9
      • 3.8
      • 3.7
      • 3.6
      • 3.5
      • 3.4
      • 3.3
      • 3.2
      • 3.1
      • 3.0
      • 2.10
      • 2.9
      • 2.8
      • 2.7
      • 2.6
      • 2.5
      • 2.4
      • 2.3
      • 2.2
      • 2.1
      • 2.0
      • 1.3
      • 1.2

Namespaces

  • Global
  • Cake
    • Auth
    • Cache
    • Collection
    • Console
    • Controller
    • Core
    • Database
    • Datasource
    • Error
    • Event
    • Filesystem
    • Form
    • I18n
    • Log
    • Mailer
    • Network
    • ORM
    • Routing
    • Shell
    • TestSuite
    • Utility
    • Validation
    • View
      • Exception
      • Form
      • Helper
      • Widget

Class View

View, the V in the MVC triad. View interacts with Helpers and view variables passed in from the controller to render the results of the controller action. Often this is HTML, but can also take the form of JSON, XML, PDF's or streaming files.

CakePHP uses a two-step-view pattern. This means that the template content is rendered first, and then inserted into the selected layout. This also means you can pass data from the template to the layout using $this->set()

View class supports using plugins as themes. You can set

public function beforeRender(\Cake\Event\Event $event)
{
     $this->viewBuilder()->theme('SuperHot');
}

in your Controller to use plugin SuperHot as a theme. Eg. If current action is PostsController::index() then View class will look for template file plugins/SuperHot/Template/Posts/index.ctp. If a theme template is not found for the current action the default app template file is used.

Namespace: Cake\View

Constants

  • string
    TYPE_ELEMENT ¶
    'element'

    Constant for view file type 'element'

  • string
    TYPE_LAYOUT ¶
    'layout'

    Constant for view file type 'layout'

  • string
    TYPE_TEMPLATE ¶
    'view'

    Constant for view file type 'template'.

  • string
    TYPE_VIEW ¶
    'view'

    Constant for view file type 'view'

Property Summary

  • $Blocks public @property
    Cake\View\ViewBlock
  • $Flash public @property
    Cake\View\Helper\FlashHelper
  • $Form public @property
    Cake\View\Helper\FormHelper
  • $Html public @property
    Cake\View\Helper\HtmlHelper
  • $Number public @property
    Cake\View\Helper\NumberHelper
  • $Paginator public @property
    Cake\View\Helper\PaginatorHelper
  • $Rss public @property
    Cake\View\Helper\RssHelper
  • $Session public @property
    Cake\View\Helper\SessionHelper
  • $Text public @property
    Cake\View\Helper\TextHelper
  • $Time public @property
    Cake\View\Helper\TimeHelper
  • $Url public @property
    Cake\View\Helper\UrlHelper
  • $_current protected
    string

    The currently rendering view file. Used for resolving parent files.

  • $_currentType protected
    string

    Currently rendering an element. Used for finding parent fragments for elements.

  • $_eventClass protected
    string

    Default class name for new event objects.

  • $_eventManager protected
    Cake\Event\EventManager

    Instance of the Cake\Event\EventManager this object is using to dispatch inner events.

  • $_ext protected
    string

    File extension. Defaults to CakePHP's template ".ctp".

  • $_helpers protected
    Cake\View\HelperRegistry

    Helpers collection

  • $_parents protected
    array

    The names of views and their parents used with View::extend();

  • $_passedVars protected
    array

    List of variables to collect from the associated controller.

  • $_paths protected
    array

    Holds an array of paths.

  • $_pathsForPlugin protected
    array

    Holds an array of plugin paths.

  • $_stack protected
    array

    Content stack, used for nested templates that all use View::extend();

  • $_viewBuilder protected
    Cake\View\ViewBuilder

    The view builder instance being used.

  • $autoLayout public
    bool

    Turns on or off CakePHP's conventional mode of applying layout files. On by default. Setting to off means that layouts will not be automatically applied to rendered templates.

  • $elementCache public
    string

    The Cache configuration View will use to store cached elements. Changing this will change the default configuration elements are stored under. You can also choose a cache config per element.

  • $hasRendered public
    bool

    True when the view has been rendered.

  • $helpers public
    array

    An array of names of built-in helpers to include.

  • $layout public
    string

    The name of the layout file to render the template inside of. The name specified is the filename of the layout in /src/Template/Layout without the .ctp extension.

  • $layoutPath public
    string

    The name of the layouts subfolder containing layouts for this View.

  • $name public
    string

    Name of the controller that created the View if any.

  • $passedArgs public deprecated
    array

    Current passed params. Passed to View from the creating Controller for convenience.

  • $plugin public
    string

    The name of the plugin.

  • $request public
    Cake\Network\Request

    An instance of a Cake\Network\Request object that contains information about the current request. This object contains all the information about a request and several methods for reading additional information about the request.

  • $response public
    Cake\Network\Response

    Reference to the Response object

  • $subDir public
    string

    Sub-directory for this template file. This is often used for extension based routing. Eg. With an xml extension, $subDir would be xml/

  • $template public
    string

    The name of the template file to render. The name specified is the filename in /src/Template/ without the .ctp extension.

  • $templatePath public
    string

    The name of the subfolder containing templates for this View.

  • $theme public
    string

    The view theme to use.

  • $uuids public
    array

    List of generated DOM UUIDs.

  • $viewClass public deprecated
    string

    The name of default View class.

  • $viewVars public
    array

    Variables for the view

Method Summary

  • __construct() public

    Constructor

  • __get() public

    Magic accessor for helpers.

  • __set() public

    Magic setter for deprecated properties.

  • _checkFilePath() protected

    Check that a view file path does not go outside of the defined template paths.

  • _createCell() protected

    Create and configure the cell instance.

  • _elementCache() protected

    Generate the cache configuration options for an element.

  • _evaluate() protected

    Sandbox method to evaluate a template / view script in.

  • _getElementFileName() protected

    Finds an element filename, returns false on failure.

  • _getLayoutFileName() protected

    Returns layout filename for this template as a string.

  • _getSubPaths() protected

    Find all sub templates path, based on $basePath If a prefix is defined in the current request, this method will prepend the prefixed template path to the $basePath, cascading up in case the prefix is nested. This is essentially used to find prefixed template paths for elements and layouts.

  • _getViewFileName() protected

    Returns filename of given action's template file (.ctp) as a string. CamelCased action names will be under_scored by default. This means that you can have LongActionNames that refer to long_action_names.ctp views. You can change the inflection rule by overriding _inflectViewFileName.

  • _inflectViewFileName() protected

    Change the name of a view template file into underscored format.

  • _paths() protected

    Return all possible paths to find view files in order

  • _render() protected

    Renders and returns output for given template filename with its array of data. Handles parent/extended templates.

  • _renderElement() protected

    Renders an element and fires the before and afterRender callbacks for it and writes to the cache if a cache is used

  • append() public

    Append to an existing or new block.

  • assign() public

    Set the content for a block. This will overwrite any existing content.

  • autoLayout() public

    Turns on or off CakePHP's conventional mode of applying layout files. On by default. Setting to off means that layouts will not be automatically applied to rendered templates.

  • blocks() public

    Get the names of all the existing blocks.

  • cache() public

    Create a cached block of view logic.

  • cell() public

    Renders the given cell.

  • createView() public

    Constructs the view class instance based on the current configuration.

  • dispatchEvent() public

    Wrapper for creating and dispatching events.

  • element() public

    Renders a piece of PHP with provided parameters and returns HTML, XML, or any other string.

  • elementExists() public

    Checks if an element exists

  • end() public

    End a capturing block. The compliment to View::start()

  • eventManager() public

    Returns the Cake\Event\EventManager manager instance for this object.

  • exists() public

    Check if a block exists

  • extend() public

    Provides template or element extension/inheritance. Views can extends a parent view and populate blocks in the parent template.

  • fetch() public

    Fetch the content for a block. If a block is empty or undefined '' will be returned.

  • get() public

    Returns the contents of the given View variable.

  • getCurrentType() public

    Retrieve the current view type

  • getVars() public

    Returns a list of variables available in the current View context

  • helpers() public

    Get the helper registry in use by this View class.

  • initialize() public

    Initialization hook method.

  • layout() public

    Get/set the name of the layout file to render the template inside of. The name specified is the filename of the layout in /src/Template/Layout without the .ctp extension.

  • layoutPath() public

    Get/set path for layout files.

  • loadHelper() public

    Loads a helper. Delegates to the HelperRegistry::load() to load the helper

  • loadHelpers() public

    Interact with the HelperRegistry to load all the helpers.

  • log() public

    Convenience method to write a message to Log. See Log::write() for more information on writing to logs.

  • pluginSplit() public

    Splits a dot syntax plugin name into its plugin and filename. If $name does not have a dot, then index 0 will be null. It checks if the plugin is loaded, else filename will stay unchanged for filenames containing dot

  • prepend() public

    Prepend to an existing or new block.

  • render() public

    Renders view for given template file and layout.

  • renderLayout() public

    Renders a layout. Returns output from _render(). Returns false on error. Several variables are created for use in layout.

  • requestAction() public

    Calls a controller's method from any location. Can be used to connect controllers together or tie plugins into a main application. requestAction can be used to return rendered views or fetch the return value from controller actions.

  • reset() public

    Reset the content for a block. This will overwrite any existing content.

  • set() public

    Saves a variable or an associative array of variables for use inside a template.

  • start() public

    Start capturing output for a 'block'

  • template() public

    Get/set the name of the template file to render. The name specified is the filename in /src/Template/ without the .ctp extension.

  • templatePath() public

    Get/set path for templates files.

  • theme() public

    The view theme to use.

  • uuid() public

    Generates a unique, non-random DOM ID for an object, based on the object type and the target URL.

  • viewBuilder() public

    Get the view builder being used.

  • viewOptions() public

    Get/Set valid view options in the object's _validViewOptions property. The property is created as an empty array if it is not set. If called without any parameters it will return the current list of valid view options. See createView().

Method Detail

__construct() ¶ public

__construct(Cake\Network\Request|null $request = null, Cake\Network\Response|null $response = null, Cake\Event\EventManager|null $eventManager = null, array $viewOptions = [])

Constructor

Parameters
Cake\Network\Request|null $request optional

Request instance.

Cake\Network\Response|null $response optional

Response instance.

Cake\Event\EventManager|null $eventManager optional

Event manager instance.

array $viewOptions optional

View options. See View::$_passedVars for list of options which get set as class properties.

__get() ¶ public

__get(string $name): mixed

Magic accessor for helpers.

Parameters
string $name

Name of the attribute to get.

Returns
mixed

__set() ¶ public

__set(string $name, mixed $value): void

Magic setter for deprecated properties.

Parameters
string $name

Name to property.

mixed $value

Value for property.

Returns
void

_checkFilePath() ¶ protected

_checkFilePath(string $file, string $path): string

Check that a view file path does not go outside of the defined template paths.

Only paths that contain .. will be checked, as they are the ones most likely to have the ability to resolve to files outside of the template paths.

Parameters
string $file

The path to the template file.

string $path

Base path that $file should be inside of.

Returns
string
Throws
InvalidArgumentException

_createCell() ¶ protected

_createCell(string $className, string $action, string $plugin, array $options): Cake\View\Cell

Create and configure the cell instance.

Parameters
string $className

The cell classname.

string $action

The action name.

string $plugin

The plugin name.

array $options

The constructor options for the cell.

Returns
Cake\View\Cell

_elementCache() ¶ protected

_elementCache(string $name, array $data, array $options): array

Generate the cache configuration options for an element.

Parameters
string $name

Element name

array $data

Data

array $options

Element options

Returns
array

_evaluate() ¶ protected

_evaluate(string $viewFile, array $dataForView): string

Sandbox method to evaluate a template / view script in.

Parameters
string $viewFile

Filename of the view

array $dataForView

Data to include in rendered view. If empty the current View::$viewVars will be used.

Returns
string

_getElementFileName() ¶ protected

_getElementFileName(string $name): string|false

Finds an element filename, returns false on failure.

Parameters
string $name

The name of the element to find.

Returns
string|false

_getLayoutFileName() ¶ protected

_getLayoutFileName(string|null $name = null): string

Returns layout filename for this template as a string.

Parameters
string|null $name optional

The name of the layout to find.

Returns
string
Throws
Cake\View\Exception\MissingLayoutException
when a layout cannot be located

_getSubPaths() ¶ protected

_getSubPaths(string $basePath): array

Find all sub templates path, based on $basePath If a prefix is defined in the current request, this method will prepend the prefixed template path to the $basePath, cascading up in case the prefix is nested. This is essentially used to find prefixed template paths for elements and layouts.

Parameters
string $basePath

Base path on which to get the prefixed one.

Returns
array

_getViewFileName() ¶ protected

_getViewFileName(string|null $name = null): string

Returns filename of given action's template file (.ctp) as a string. CamelCased action names will be under_scored by default. This means that you can have LongActionNames that refer to long_action_names.ctp views. You can change the inflection rule by overriding _inflectViewFileName.

Parameters
string|null $name optional

Controller action to find template filename for

Returns
string
Throws
Cake\View\Exception\MissingTemplateException
when a view file could not be found.

_inflectViewFileName() ¶ protected

_inflectViewFileName(string $name): string

Change the name of a view template file into underscored format.

Parameters
string $name

Name of file which should be inflected.

Returns
string

_paths() ¶ protected

_paths(string|null $plugin = null, bool $cached = true): array

Return all possible paths to find view files in order

Parameters
string|null $plugin optional

Optional plugin name to scan for view files.

bool $cached optional

Set to false to force a refresh of view paths. Default true.

Returns
array

_render() ¶ protected

_render(string $viewFile, array $data = []): string

Renders and returns output for given template filename with its array of data. Handles parent/extended templates.

Parameters
string $viewFile

Filename of the view

array $data optional

Data to include in rendered view. If empty the current View::$viewVars will be used.

Returns
string
Throws
LogicException
When a block is left open.

_renderElement() ¶ protected

_renderElement(string $file, array $data, array $options): string

Renders an element and fires the before and afterRender callbacks for it and writes to the cache if a cache is used

Parameters
string $file

Element file path

array $data

Data to render

array $options

Element options

Returns
string

append() ¶ public

append(string $name, mixed $value = null): void

Append to an existing or new block.

Appending to a new block will create the block.

Parameters
string $name

Name of the block

mixed $value optional

The content for the block. Value will be type cast to string.

Returns
void
See Also
\Cake\View\ViewBlock::concat()

assign() ¶ public

assign(string $name, mixed $value): void

Set the content for a block. This will overwrite any existing content.

Parameters
string $name

Name of the block

mixed $value

The content for the block. Value will be type cast to string.

Returns
void
See Also
\Cake\View\ViewBlock::set()

autoLayout() ¶ public

autoLayout(bool|null $autoLayout = null): bool|null

Turns on or off CakePHP's conventional mode of applying layout files. On by default. Setting to off means that layouts will not be automatically applied to rendered templates.

Parameters
bool|null $autoLayout optional

Boolean to turn on/off. If null returns current value.

Returns
bool|null

blocks() ¶ public

blocks(): array

Get the names of all the existing blocks.

Returns
array
See Also
\Cake\View\ViewBlock::keys()

cache() ¶ public

cache(callable $block, array $options = []): string

Create a cached block of view logic.

This allows you to cache a block of view output into the cache defined in elementCache.

This method will attempt to read the cache first. If the cache is empty, the $block will be run and the output stored.

Parameters
callable $block

The block of code that you want to cache the output of.

array $options optional

The options defining the cache key etc.

Returns
string
Throws
RuntimeException
When $options is lacking a 'key' option.

cell() ¶ public

cell(string $cell, array $data = [], array $options = []): Cake\View\Cell

Renders the given cell.

Example:

// Taxonomy\View\Cell\TagCloudCell::smallList()
$cell = $this->cell('Taxonomy.TagCloud::smallList', ['limit' => 10]);

// App\View\Cell\TagCloudCell::smallList()
$cell = $this->cell('TagCloud::smallList', ['limit' => 10]);

The display action will be used by default when no action is provided:

// Taxonomy\View\Cell\TagCloudCell::display()
$cell = $this->cell('Taxonomy.TagCloud');

Cells are not rendered until they are echoed.

Parameters
string $cell

You must indicate cell name, and optionally a cell action. e.g.: TagCloud::smallList will invoke View\Cell\TagCloudCell::smallList(), display action will be invoked by default when none is provided.

array $data optional

Additional arguments for cell method. e.g.: cell('TagCloud::smallList', ['a1' => 'v1', 'a2' => 'v2']) maps to View\Cell\TagCloud::smallList(v1, v2)

array $options optional

Options for Cell's constructor

Returns
Cake\View\Cell
Throws
Cake\View\Exception\MissingCellException
If Cell class was not found.
BadMethodCallException
If Cell class does not specified cell action.

createView() ¶ public

createView(string|null $viewClass = null): Cake\View\View

Constructs the view class instance based on the current configuration.

Parameters
string|null $viewClass optional

Optional namespaced class name of the View class to instantiate.

Returns
Cake\View\View
Throws
Cake\View\Exception\MissingViewException
If view class was not found.

dispatchEvent() ¶ public

dispatchEvent(string $name, array|null $data = null, object|null $subject = null): Cake\Event\Event

Wrapper for creating and dispatching events.

Returns a dispatched event.

Parameters
string $name

Name of the event.

array|null $data optional

Any value you wish to be transported with this event to it can be read by listeners.

object|null $subject optional

The object that this event applies to ($this by default).

Returns
Cake\Event\Event

element() ¶ public

element(string $name, array $data = [], array $options = []): string

Renders a piece of PHP with provided parameters and returns HTML, XML, or any other string.

This realizes the concept of Elements, (or "partial layouts") and the $params array is used to send data to be used in the element. Elements can be cached improving performance by using the cache option.

Parameters
string $name

Name of template file in the /src/Template/Element/ folder, or MyPlugin.template to use the template element from MyPlugin. If the element is not found in the plugin, the normal view path cascade will be searched.

array $data optional

Array of data to be made available to the rendered view (i.e. the Element)

array $options optional

Array of options. Possible keys are:

  • cache - Can either be true, to enable caching using the config in View::$elementCache. Or an array If an array, the following keys can be used:
    • config - Used to store the cached element in a custom cache configuration.
    • key - Used to define the key used in the Cache::write(). It will be prefixed with element_
  • callbacks - Set to true to fire beforeRender and afterRender helper callbacks for this element. Defaults to false.
  • ignoreMissing - Used to allow missing elements. Set to true to not throw exceptions.
Returns
string
Throws
Cake\View\Exception\MissingElementException
When an element is missing and `ignoreMissing` is false.

elementExists() ¶ public

elementExists(string $name): bool

Checks if an element exists

Parameters
string $name

Name of template file in the /src/Template/Element/ folder, or MyPlugin.template to check the template element from MyPlugin. If the element is not found in the plugin, the normal view path cascade will be searched.

Returns
bool

end() ¶ public

end(): void

End a capturing block. The compliment to View::start()

Returns
void
See Also
\Cake\View\ViewBlock::end()

eventManager() ¶ public

eventManager(Cake\Event\EventManager|null $eventManager = null): Cake\Event\EventManager

Returns the Cake\Event\EventManager manager instance for this object.

You can use this instance to register any new listeners or callbacks to the object events, or create your own events and trigger them at will.

Parameters
Cake\Event\EventManager|null $eventManager optional

the eventManager to set

Returns
Cake\Event\EventManager

exists() ¶ public

exists(string $name): bool

Check if a block exists

Parameters
string $name

Name of the block

Returns
bool

extend() ¶ public

extend(string $name): void

Provides template or element extension/inheritance. Views can extends a parent view and populate blocks in the parent template.

Parameters
string $name

The template or element to 'extend' the current one with.

Returns
void
Throws
LogicException
when you extend a template with itself or make extend loops.
LogicException
when you extend an element which doesn't exist

fetch() ¶ public

fetch(string $name, string $default = ''): string

Fetch the content for a block. If a block is empty or undefined '' will be returned.

Parameters
string $name

Name of the block

string $default optional

Default text

Returns
string
See Also
\Cake\View\ViewBlock::get()

get() ¶ public

get(string $var, mixed $default = null): mixed

Returns the contents of the given View variable.

Parameters
string $var

The view var you want the contents of.

mixed $default optional

The default/fallback content of $var.

Returns
mixed

getCurrentType() ¶ public

getCurrentType(): string

Retrieve the current view type

Returns
string

getVars() ¶ public

getVars(): array

Returns a list of variables available in the current View context

Returns
array

helpers() ¶ public

helpers(): Cake\View\HelperRegistry

Get the helper registry in use by this View class.

Returns
Cake\View\HelperRegistry

initialize() ¶ public

initialize(): void

Initialization hook method.

Properties like $helpers etc. cannot be initialized statically in your custom view class as they are overwritten by values from controller in constructor. So this method allows you to manipulate them as required after view instance is constructed.

Returns
void

layout() ¶ public

layout(string|null $name = null): string|null

Get/set the name of the layout file to render the template inside of. The name specified is the filename of the layout in /src/Template/Layout without the .ctp extension.

Parameters
string|null $name optional

Layout file name to set. If null returns current name.

Returns
string|null

layoutPath() ¶ public

layoutPath(string|null $path = null): string|null

Get/set path for layout files.

Parameters
string|null $path optional

Path for layout files. If null returns current path.

Returns
string|null

loadHelper() ¶ public

loadHelper(string $name, array $config = []): Cake\View\Helper

Loads a helper. Delegates to the HelperRegistry::load() to load the helper

Parameters
string $name

Name of the helper to load.

array $config optional

Settings for the helper

Returns
Cake\View\Helper
See Also
\Cake\View\HelperRegistry::load()

loadHelpers() ¶ public

loadHelpers(): void

Interact with the HelperRegistry to load all the helpers.

Returns
void

log() ¶ public

log(mixed $msg, int|string $level = LogLevel::ERROR, string|array $context = []): bool

Convenience method to write a message to Log. See Log::write() for more information on writing to logs.

Parameters
mixed $msg

Log message.

int|string $level optional

Error level.

string|array $context optional

Additional log data relevant to this message.

Returns
bool

pluginSplit() ¶ public

pluginSplit(string $name, bool $fallback = true): array

Splits a dot syntax plugin name into its plugin and filename. If $name does not have a dot, then index 0 will be null. It checks if the plugin is loaded, else filename will stay unchanged for filenames containing dot

Parameters
string $name

The name you want to plugin split.

bool $fallback optional

If true uses the plugin set in the current Request when parsed plugin is not loaded

Returns
array

prepend() ¶ public

prepend(string $name, mixed $value): void

Prepend to an existing or new block.

Prepending to a new block will create the block.

Parameters
string $name

Name of the block

mixed $value

The content for the block. Value will be type cast to string.

Returns
void
See Also
\Cake\View\ViewBlock::concat()

render() ¶ public

render(string|null $view = null, string|null $layout = null): string|null

Renders view for given template file and layout.

Render triggers helper callbacks, which are fired before and after the template are rendered, as well as before and after the layout. The helper callbacks are called:

  • beforeRender
  • afterRender
  • beforeLayout
  • afterLayout

If View::$autoRender is false and no $layout is provided, the template will be returned bare.

Template and layout names can point to plugin templates/layouts. Using the Plugin.template syntax a plugin template/layout can be used instead of the app ones. If the chosen plugin is not found the template will be located along the regular view path cascade.

Parameters
string|null $view optional

Name of view file to use

string|null $layout optional

Layout to use.

Returns
string|null
Throws
Cake\Core\Exception\Exception
If there is an error in the view.

renderLayout() ¶ public

renderLayout(string $content, string|null $layout = null): mixed

Renders a layout. Returns output from _render(). Returns false on error. Several variables are created for use in layout.

Parameters
string $content

Content to render in a template, wrapped by the surrounding layout.

string|null $layout optional

Layout name

Returns
mixed
Throws
Cake\Core\Exception\Exception
if there is an error in the view.

requestAction() ¶ public

requestAction(string|array $url, array $extra = []): mixed

Calls a controller's method from any location. Can be used to connect controllers together or tie plugins into a main application. requestAction can be used to return rendered views or fetch the return value from controller actions.

Under the hood this method uses Router::reverse() to convert the $url parameter into a string URL. You should use URL formats that are compatible with Router::reverse()

Examples

A basic example getting the return value of the controller action:

$variables = $this->requestAction('/articles/popular');

A basic example of request action to fetch a rendered page without the layout.

$viewHtml = $this->requestAction('/articles/popular', ['return']);

You can also pass the URL as an array:

$vars = $this->requestAction(['controller' => 'articles', 'action' => 'popular']);

Passing other request data

You can pass POST, GET, COOKIE and other data into the request using the appropriate keys. Cookies can be passed using the cookies key. Get parameters can be set with query and post data can be sent using the post key.

$vars = $this->requestAction('/articles/popular', [
  'query' => ['page' => 1],
  'cookies' => ['remember_me' => 1],
]);

Sending environment or header values

By default actions dispatched with this method will use the global $_SERVER and $_ENV values. If you want to override those values for a request action, you can specify the values:

$vars = $this->requestAction('/articles/popular', [
  'environment' => ['CONTENT_TYPE' => 'application/json']
]);

Transmitting the session

By default actions dispatched with this method will use the standard session object. If you want a particular session instance to be used, you need to specify it.

$vars = $this->requestAction('/articles/popular', [
  'session' => new Session($someSessionConfig)
]);
Parameters
string|array $url

String or array-based url. Unlike other url arrays in CakePHP, this url will not automatically handle passed arguments in the $url parameter.

array $extra optional

if array includes the key "return" it sets the autoRender to true. Can also be used to submit GET/POST data, and passed arguments.

Returns
mixed

reset() ¶ public

reset(string $name): void

Reset the content for a block. This will overwrite any existing content.

Parameters
string $name

Name of the block

Returns
void
See Also
\Cake\View\ViewBlock::set()

set() ¶ public

set(string|array $name, string|array|null|bool $value = null): $this

Saves a variable or an associative array of variables for use inside a template.

Parameters
string|array $name

A string or an array of data.

string|array|null|bool $value optional

Value in case $name is a string (which then works as the key). Unused if $name is an associative array, otherwise serves as the values to $name's keys.

Returns
$this

start() ¶ public

start(string $name): void

Start capturing output for a 'block'

You can use start on a block multiple times to append or prepend content in a capture mode.

// Append content to an existing block.
$this->start('content');
echo $this->fetch('content');
echo 'Some new content';
$this->end();

// Prepend content to an existing block
$this->start('content');
echo 'Some new content';
echo $this->fetch('content');
$this->end();
Parameters
string $name

The name of the block to capture for.

Returns
void
See Also
\Cake\View\ViewBlock::start()

template() ¶ public

template(string|null $name = null): string|null

Get/set the name of the template file to render. The name specified is the filename in /src/Template/ without the .ctp extension.

Parameters
string|null $name optional

Template file name to set. If null returns current name.

Returns
string|null

templatePath() ¶ public

templatePath(string|null $path = null): string|null

Get/set path for templates files.

Parameters
string|null $path optional

Path for template files. If null returns current path.

Returns
string|null

theme() ¶ public

theme(string|null $theme = null): string|null

The view theme to use.

Parameters
string|null $theme optional

Theme name. If null returns current theme.

Returns
string|null

uuid() ¶ public

uuid(string $object, string $url): string

Generates a unique, non-random DOM ID for an object, based on the object type and the target URL.

Parameters
string $object

Type of object, i.e. 'form' or 'link'

string $url

The object's target URL

Returns
string

viewBuilder() ¶ public

viewBuilder(): Cake\View\ViewBuilder

Get the view builder being used.

Returns
Cake\View\ViewBuilder

viewOptions() ¶ public

viewOptions(string|array|null $options = null, bool $merge = true): array

Get/Set valid view options in the object's _validViewOptions property. The property is created as an empty array if it is not set. If called without any parameters it will return the current list of valid view options. See createView().

Parameters
string|array|null $options optional

string or array of string to be appended to _validViewOptions.

bool $merge optional

Whether to merge with or override existing valid View options. Defaults to true.

Returns
array

Property Detail

$Blocks ¶ public @property

Type
Cake\View\ViewBlock

$Flash ¶ public @property

Type
Cake\View\Helper\FlashHelper

$Form ¶ public @property

Type
Cake\View\Helper\FormHelper

$Html ¶ public @property

Type
Cake\View\Helper\HtmlHelper

$Number ¶ public @property

Type
Cake\View\Helper\NumberHelper

$Paginator ¶ public @property

Type
Cake\View\Helper\PaginatorHelper

$Rss ¶ public @property

Type
Cake\View\Helper\RssHelper

$Session ¶ public @property

Type
Cake\View\Helper\SessionHelper

$Text ¶ public @property

Type
Cake\View\Helper\TextHelper

$Time ¶ public @property

Type
Cake\View\Helper\TimeHelper

$Url ¶ public @property

Type
Cake\View\Helper\UrlHelper

$_current ¶ protected

The currently rendering view file. Used for resolving parent files.

Type
string

$_currentType ¶ protected

Currently rendering an element. Used for finding parent fragments for elements.

Type
string

$_eventClass ¶ protected

Default class name for new event objects.

Type
string

$_eventManager ¶ protected

Instance of the Cake\Event\EventManager this object is using to dispatch inner events.

Type
Cake\Event\EventManager

$_ext ¶ protected

File extension. Defaults to CakePHP's template ".ctp".

Type
string

$_helpers ¶ protected

Helpers collection

Type
Cake\View\HelperRegistry

$_parents ¶ protected

The names of views and their parents used with View::extend();

Type
array

$_passedVars ¶ protected

List of variables to collect from the associated controller.

Type
array

$_paths ¶ protected

Holds an array of paths.

Type
array

$_pathsForPlugin ¶ protected

Holds an array of plugin paths.

Type
array

$_stack ¶ protected

Content stack, used for nested templates that all use View::extend();

Type
array

$_viewBuilder ¶ protected

The view builder instance being used.

Type
Cake\View\ViewBuilder

$autoLayout ¶ public

Turns on or off CakePHP's conventional mode of applying layout files. On by default. Setting to off means that layouts will not be automatically applied to rendered templates.

Type
bool

$elementCache ¶ public

The Cache configuration View will use to store cached elements. Changing this will change the default configuration elements are stored under. You can also choose a cache config per element.

Type
string

$hasRendered ¶ public

True when the view has been rendered.

Type
bool

$helpers ¶ public

An array of names of built-in helpers to include.

Type
array

$layout ¶ public

The name of the layout file to render the template inside of. The name specified is the filename of the layout in /src/Template/Layout without the .ctp extension.

Type
string

$layoutPath ¶ public

The name of the layouts subfolder containing layouts for this View.

Type
string

$name ¶ public

Name of the controller that created the View if any.

Type
string

$passedArgs ¶ public deprecated

Current passed params. Passed to View from the creating Controller for convenience.

Type
array

$plugin ¶ public

The name of the plugin.

Type
string

$request ¶ public

An instance of a Cake\Network\Request object that contains information about the current request. This object contains all the information about a request and several methods for reading additional information about the request.

Type
Cake\Network\Request

$response ¶ public

Reference to the Response object

Type
Cake\Network\Response

$subDir ¶ public

Sub-directory for this template file. This is often used for extension based routing. Eg. With an xml extension, $subDir would be xml/

Type
string

$template ¶ public

The name of the template file to render. The name specified is the filename in /src/Template/ without the .ctp extension.

Type
string

$templatePath ¶ public

The name of the subfolder containing templates for this View.

Type
string

$theme ¶ public

The view theme to use.

Type
string

$uuids ¶ public

List of generated DOM UUIDs.

Type
array

$viewClass ¶ public deprecated

The name of default View class.

Type
string

$viewVars ¶ public

Variables for the view

Type
array
OpenHub
Pingping
Linode
  • Business Solutions
  • Showcase
  • Documentation
  • Book
  • API
  • Videos
  • Reporting Security Issues
  • Privacy Policy
  • Logos & Trademarks
  • Community
  • Get Involved
  • Issues (Github)
  • Bakery
  • Featured Resources
  • Training
  • Meetups
  • My CakePHP
  • CakeFest
  • Newsletter
  • Linkedin
  • YouTube
  • Facebook
  • Twitter
  • Mastodon
  • Help & Support
  • Forum
  • Stack Overflow
  • IRC
  • Slack
  • Paid Support

Generated using CakePHP API Docs