CakePHP
  • Documentation
    • Book
    • API
    • Videos
    • Logos & Trademarks
  • Business Solutions
  • Swag
  • Road Trip
  • Team
  • Community
    • Community
    • Team
    • Issues (Github)
    • YouTube Channel
    • Get Involved
    • Bakery
    • Featured Resources
    • Newsletter
    • Certification
    • My CakePHP
    • CakeFest
    • Facebook
    • Twitter
    • Help & Support
    • Forum
    • Stack Overflow
    • IRC
    • Slack
    • Paid Support
CakePHP

C CakePHP 3.0 Red Velvet API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 3.0
      • 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

  • Cake
    • Auth
    • Cache
      • Engine
    • Collection
      • Iterator
    • Console
      • Exception
    • Controller
      • Component
      • Exception
    • Core
      • Configure
        • Engine
      • Exception
    • Database
      • Driver
      • Exception
      • Expression
      • Schema
      • Statement
      • Type
    • Datasource
      • Exception
    • Error
    • Event
    • Filesystem
    • Form
    • I18n
      • Formatter
      • Parser
    • Log
      • Engine
    • Network
      • Email
      • Exception
      • Http
        • Adapter
        • Auth
        • FormData
      • Session
    • ORM
      • Association
      • Behavior
        • Translate
      • Exception
      • Rule
    • Routing
      • Exception
      • Filter
      • Route
    • Shell
      • Task
    • TestSuite
      • Fixture
      • Stub
    • Utility
      • Exception
    • Validation
    • View
      • Exception
      • Form
      • Helper
      • Widget
  • None

Classes

  • AjaxView
  • Cell
  • Helper
  • HelperRegistry
  • JsonView
  • StringTemplate
  • View
  • ViewBlock
  • XmlView

Traits

  • CellTrait
  • StringTemplateTrait
  • ViewVarsTrait

Class AjaxView

A view class that is used for AJAX responses. Currently only switches the default layout and sets the response type - which just maps to text/html by default.

Cake\View\View implements Cake\Event\EventDispatcherInterface uses Cake\View\CellTrait , Cake\Event\EventDispatcherTrait , Cake\Log\LogTrait , Cake\Routing\RequestActionTrait , Cake\View\ViewVarsTrait
Extended by Cake\View\AjaxView
Namespace: Cake\View
Location: View/AjaxView.php

Inherited Constants

  • TYPE_ELEMENT, TYPE_LAYOUT, TYPE_VIEW

Properties summary

  • $layout public
    string

Inherited Magic Properties

  • Blocks, Form, Html, Number, Paginator, Rss, Session, Text, Time, Url

Inherited Properties

  • Blocks, _current, _currentType, _ext, _helpers, _parents, _passedVars, _paths, _pathsForPlugin, _stack, autoLayout, elementCache, hasRendered, helpers, layoutPath, name, passedArgs, plugin, request, response, subDir, theme, uuids, view, viewPath _eventClass, _eventManager viewVars

Method Summary

  • __construct() public
    Constructor

Method Detail

__construct() public ¶

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

Constructor

Parameters
Cake\Network\Request $request optional null
The request object.
Cake\Network\Response $response optional null
The response object.
Cake\Event\EventManager $eventManager optional null
Event manager object.
array $viewOptions optional []
View options.
Overrides
Cake\View\View::__construct()

Methods inherited from Cake\View\View

__get() public ¶

__get( string $name )

Magic accessor for helpers.

Parameters
string $name
Name of the attribute to get.
Returns
mixed

_checkFilePath() protected ¶

_checkFilePath( string $file , string $path )

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
The file path
Throws
InvalidArgumentException

_elementCache() protected ¶

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

Generate the cache configuration options for an element.

Parameters
string $name
Element name
array $data
Data
array $options
Element options
Returns
array
Element Cache configuration.

_evaluate() protected ¶

_evaluate( string $viewFile , array $dataForView )

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
Rendered output

_getElementFileName() protected ¶

_getElementFileName( string $name )

Finds an element filename, returns false on failure.

Parameters
string $name
The name of the element to find.
Returns
mixed
Either a string to the element filename or false when one can't be found.

_getLayoutFileName() protected ¶

_getLayoutFileName( string|null $name null )

Returns layout filename for this template as a string.

Parameters
string|null $name optional null
The name of the layout to find.
Returns
string
Filename for layout file (.ctp).
Throws
Cake\View\Exception\MissingLayoutException
when a layout cannot be located

_getSubPaths() protected ¶

_getSubPaths( string $basePath )

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
Array with all the templates paths.

_getViewFileName() protected ¶

_getViewFileName( string|null $name null )

Returns filename of given action's template file (.ctp) as a string. CamelCased action names will be under_scored! This means that you can have LongActionNames that refer to long_action_names.ctp views.

Parameters
string|null $name optional null
Controller action to find template filename for
Returns
string
Template filename
Throws
Cake\View\Exception\MissingTemplateException
when a view file could not be found.

_paths() protected ¶

_paths( string|null $plugin null , boolean $cached true )

Return all possible paths to find view files in order

Parameters
string|null $plugin optional null
Optional plugin name to scan for view files.
boolean $cached optional true
Set to false to force a refresh of view paths. Default true.
Returns
array
paths

_render() protected ¶

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

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

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
Rendered output
Throws
LogicException
When a block is left open.
Triggers
View.beforeRenderFile $this, [$viewFile]
View.afterRenderFile $this, [$viewFile, $content]

_renderElement() protected ¶

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

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
Triggers
View.beforeRender $this, [$file]
View.afterRender $this, [$file, $element]

append() public ¶

append( string $name , mixed $value null )

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 null
The content for the block.
See
ViewBlock::concat()

assign() public ¶

assign( string $name , mixed $value )

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.
See
ViewBlock::set()

blocks() public ¶

blocks( )

Get the names of all the existing blocks.

Returns
array
An array containing the blocks.
See
ViewBlock::keys()

cache() public ¶

cache( callable $block , array $options [] )

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
The rendered content.
Throws
RuntimeException
When $options is lacking a 'key' option.

element() public ¶

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

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/app/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
Rendered Element
Throws
Cake\View\Exception\MissingElementException

When an element is missing and ignoreMissing is false.


elementExists() public ¶

elementExists( string $name )

Checks if an element exists

Parameters
string $name

Name of template file in the /app/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
boolean
Success

end() public ¶

end( )

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

See
ViewBlock::end()

exists() public ¶

exists( string $name )

Check if a block exists

Parameters
string $name
Name of the block
Returns
boolean

extend() public ¶

extend( string $name )

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

Parameters
string $name
The view or element to 'extend' the current one with.
Throws
LogicException
when you extend a view with itself or make extend loops.
LogicException
when you extend an element which doesn't exist

fetch() public ¶

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

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
default The block content or $default if the block does not exist.
See
ViewBlock::get()

get() public ¶

get( string $var , mixed $default null )

Returns the contents of the given View variable.

Parameters
string $var
The view var you want the contents of.
mixed $default optional null
The default/fallback content of $var.
Returns
mixed
The content of the named var if its set, otherwise $default.

getCurrentType() public ¶

getCurrentType( )

Retrieve the current view type

Returns
string

getVars() public ¶

getVars( )

Returns a list of variables available in the current View context

Returns
array
Array of the set view variable names.

helpers() public ¶

helpers( )

Get the helper registry in use by this View class.

Returns
Cake\View\HelperRegistry

initialize() public ¶

initialize( )

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.

loadHelper() public ¶

loadHelper( string $name , array $config [] )

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
a constructed helper object.
See
HelperRegistry::load()

loadHelpers() public ¶

loadHelpers( )

Interact with the HelperRegistry to load all the helpers.

pluginSplit() public ¶

pluginSplit( string $name , boolean $fallback true )

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.
boolean $fallback optional true
If true uses the plugin set in the current Request when parsed plugin is not loaded
Returns
array
Array with 2 indexes. 0 => plugin name, 1 => filename

prepend() public ¶

prepend( string $name , mixed $value )

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.
See
ViewBlock::concat()

render() public ¶

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

Renders view for given view file and layout.

Render triggers helper callbacks, which are fired before and after the view 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 view will be returned bare.

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

Parameters
string|null $view optional null
Name of view file to use
string|null $layout optional null
Layout to use.
Returns
string|
Rendered content or null if content already rendered and returned earlier.
Throws
Cake\Core\Exception\Exception
If there is an error in the view.
Triggers
View.beforeRender $this, [$viewFileName]
View.afterRender $this, [$viewFileName]

renderLayout() public ¶

renderLayout( string $content , string|null $layout null )

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 view, wrapped by the surrounding layout.
string|null $layout optional null
Layout name
Returns
mixed
Rendered output, or false on error
Throws
Cake\Core\Exception\Exception
if there is an error in the view.
Triggers
View.beforeLayout $this, [$layoutFileName]
View.afterLayout $this, [$layoutFileName]

start() public ¶

start( string $name )

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.
See
ViewBlock::start()

uuid() public ¶

uuid( string $object , string $url )

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

Methods used from Cake\View\CellTrait

_createCell() protected ¶

_createCell( string $className , string $action , string $plugin , array $options )

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;

cell() public ¶

cell( string $cell , array $data [] , array $options [] )

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
The cell instance
Throws
Cake\View\Exception\MissingCellException
If Cell class was not found.
BadMethodCallException
If Cell class does not specified cell action.

Methods used from Cake\Event\EventDispatcherTrait

dispatchEvent() public ¶

dispatchEvent( string $name , array|null $data null , object|null $subject null )

Wrapper for creating and dispatching events.

Returns a dispatched event.

Parameters
string $name
Name of the event.
array|null $data optional null

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

object|null $subject optional null

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

Returns
Cake\Event\Event

eventManager() public ¶

eventManager( Cake\Event\EventManager $eventManager null )

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 $eventManager optional null
the eventManager to set
Returns
Cake\Event\EventManager

Methods used from Cake\Log\LogTrait

log() public ¶

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

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

Parameters
mixed $msg
Log message.
integer|string $level optional LogLevel::ERROR
Error level.
string|array $context optional []
Additional log data relevant to this message.
Returns
boolean
Success of log write.

Methods used from Cake\Routing\RequestActionTrait

requestAction() public ¶

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

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

Boolean true or false on success/failure, or contents of rendered action if 'return' is set in $extra.


Methods used from Cake\View\ViewVarsTrait

createView() public ¶

createView( string|null $viewClass null )

Constructs the view class instance based on object properties.

Parameters
string|null $viewClass optional null
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.

getView() public ¶

getView( string|null $viewClass null )

Get view instance

Parameters
string|null $viewClass optional null
View class name or null to use $viewClass
Returns
Cake\View\View
Throws
Cake\View\Exception\MissingViewException
If view class was not found.

set() public ¶

set( string|array $name , string|array|null $value null )

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 $value optional null

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

viewOptions() public ¶

viewOptions( string|array|null $options null , boolean $merge true )

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 null
string or array of string to be appended to _validViewOptions.
boolean $merge optional true

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

Returns
array
The updated view options as an array.

Properties detail

$layout ¶

public string
'ajax'
Follow @CakePHP
#IRC
OpenHub
Rackspace
  • Business Solutions
  • Showcase
  • Documentation
  • Book
  • API
  • Videos
  • Logos & Trademarks
  • Community
  • Team
  • Issues (Github)
  • YouTube Channel
  • Get Involved
  • Bakery
  • Featured Resources
  • Newsletter
  • Certification
  • My CakePHP
  • CakeFest
  • Facebook
  • Twitter
  • Help & Support
  • Forum
  • Stack Overflow
  • IRC
  • Slack
  • Paid Support

Generated using CakePHP API Docs