Cakephp Classroom image

osdyui
 
To post your Question Join Classroom
 
Lesson Topics's No:-  First|5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13|Last
Lessons:-Views

JSONP response

When using JsonView you can use the special view variable _jsonp to enable returning a JSONP response.
Setting it to true makes the view class check if query string parameter named “callback” is set and if so
wrap the json response in the function name provided. If you want to use a custom query string parameter
name instead of “callback” set _jsonp to required name instead of true.

Helpers

Helpers are the component-like classes for the presentation layer of your application. They contain presentational logic that is shared between many views, elements, or layouts. This chapter will show you how to create your own helpers, and outline the basic tasks CakePHP’s core helpers can help you accomplish. CakePHP features a number of helpers that aid in view creation. They assist in creating well-formed markup (including forms), aid in formatting text, times and numbers, and can even speed up AJAX functionality. For more information on the helpers included in CakePHP, check out the chapter for each helper:

CacheHelper

The Cache helper assists in caching entire layouts and views, saving time repetitively retrieving data. View
Caching in CakePHP temporarily stores parsed layouts and views as simple PHP + HTML files. It should
be noted that the Cache helper works quite differently than other helpers. It does not have methods that are directly called. Instead, a view is marked with cache tags indicating which blocks of content should not be cached. The CacheHelper then uses helper callbacks to process the file and output to generate the cache file.

When a URL is requested, CakePHP checks to see if that request string has already been cached. If it has,
the rest of the URL dispatching process is skipped. Any nocache blocks are processed normally and the
view is served. This creates a big savings in processing time for each request to a cached URL as minimal
code is executed. If CakePHP doesn’t find a cached view, or the cache has expired for the requested URL it continues to process the request normally.

Using the Helper

There are two steps you have to take before you can use the CacheHelper. First in your
APP/Config/core.php uncomment the Configure write call for Cache.check. This will tell
CakePHP to check for, and generate view cache files when handling requests.
Once you’ve uncommented the Cache.check line you will need to add the helper to your controller’s
$helpers array:

class PostsController extends AppController {
public $helpers = array('Cache');
}

You will also need to add the CacheDispatcher to your dispatcher filters in your bootstrap:

Configure::write('Dispatcher.filters', array(
'CacheDispatcher'
));

Additional configuration options

CacheHelper has a few additional configuration options you can use to tune and tweak its behavior. This is
done through the $cacheAction variable in your controllers. $cacheAction should be set to an array
which contains the actions you want cached, and the duration in seconds you want those views cached. The time value can be expressed in a strtotime() format (e.g. “1 hour”, or “3 minutes”).

Using the example of an ArticlesController, that receives a lot of traffic that needs to be cached:

public $cacheAction = array(
'view' => 36000,
'index' => 48000
);

This will cache the view action 10 hours, and the index action 13 hours. By making $cacheAction a
strtotime() friendly value you can cache every action in the controller:

public $cacheAction = "1 hour";

You can also enable controller/component callbacks for cached views created with CacheHelper. To do
so you must use the array format for $cacheAction and create an array like the following:

public $cacheAction = array(
'view' => array('callbacks' => true, 'duration' => 21600),
'add' => array('callbacks' => true, 'duration' => 36000),
'index' => array('callbacks' => true, 'duration' => 48000)
);

By setting callbacks => true you tell CacheHelper that you want the generated files to create the
components and models for the controller. Additionally, fire the component initialize, controller beforeFilter,
and component startup callbacks.

Marking Non-Cached Content in Views

There will be times when you don’t want an entire view cached. For example, certain parts of the page may
look different whether a user is currently logged in or browsing your site as a guest.

To indicate blocks of content that are not to be cached, wrap them in <!--nocache-->
<!--/nocache--> like so:

<!--nocache-->
<?php if ($this->Session->check('User.name')): ?>
Welcome, <?php echo h($this->Session->read('User.name')); ?>.
<?php else: ?>
<?php echo $this->Html->link('Login', 'users/login'); ?>
<?php endif; ?>
<!--/nocache-->

It should be noted that once an action is cached, the controller method for the action will not be called. When a cache file is created, the request object, and view variables are serialized with PHP’s serialize().

Clearing the Cache

It is important to remember that CakePHP will clear a cached view if a model used in the cached view is
modified. For example, if a cached view uses data from the Post model, and there has been an INSERT,
UPDATE, or DELETE query made to a Post, the cache for that view is cleared, and new content is generated on the next request.

If you need to manually clear the cache, you can do so by calling Cache::clear(). This will clear all cached
data, excluding cached view files. If you need to clear the cached view files, use clearCache().

FlashHelper

FlashHelper provides a way to render flash messages that were set in $_SESSION by FlashComponent.
FlashComponent and FlashHelper primarily use elements to render flash messages. Flash elements are
found under the app/View/Elements/Flash directory. You’ll notice that CakePHP’s App template
comes with two flash elements: success.ctp and error.ctp.

The FlashHelper replaces the flash() method on SessionHelper and should be used instead of that
method.

Rendering Flash Messages

To render a flash message, you can simply use FlashHelper’s render() method:

<?php echo $this->Flash->render() ?>

By default, CakePHP uses a “flash” key for flash messages in a session. But, if you’ve specified a key when
setting the flash message in FlashComponent, you can specify which flash key to render:

<?php echo $this->Flash->render('other') ?>

You can also override any of the options that were set in FlashComponent:

// In your Controller
$this->Flash->set('The user has been saved.', array(
'element' => 'success'
));
// In your View: Will use great_success.ctp instead of success.ctp
<?php echo $this->Flash->render('flash', array(
'element' => 'great_success'
));

For more information about the available array options, please refer to the FlashComponent section.

FormHelper

The FormHelper does most of the heavy lifting in form creation. The FormHelper focuses on creating forms
quickly, in a way that will streamline validation, re-population and layout. The FormHelper is also flexible
- it will do almost everything for you using conventions, or you can use specific methods to get only what
you need.

Creating Forms

The first method you’ll need to use in order to take advantage of the FormHelper is create(). This special
method outputs an opening form tag.
FormHelper::create(string $model = null, array $options = array())
All parameters are optional. If create() is called with no parameters supplied, it assumes you are

building a form that submits to the current controller, via the current URL. The default method for
form submission is POST. The form element is also returned with a DOM ID. The ID is generated
using the name of the model, and the name of the controller action, CamelCased. If I were to call
create() inside a UsersController view, I’d see something like the following output in the rendered
view:

<form id="UserAddForm" method="post" action="/users/add">

The create() method allows us to customize much more using the parameters, however. First, you
can specify a model name. By specifying a model for a form, you are creating that form’s context.
All fields are assumed to belong to this model (unless otherwise specified), and all models referenced
are assumed to be associated with it. If you do not specify a model, then it assumes you are using the
default model for the current controller:

// If you are on /recipes/add
echo $this->Form->create('Recipe');

Output:

<form id="RecipeAddForm" method="post" action="/recipes/add">

This will POST the form data to the add() action of RecipesController. However, you can also use
the same logic to create an edit form. The FormHelper uses the $this->request->data property
to automatically detect whether to create an add or edit form. If $this->request->data
contains an array element named after the form’s model, and that array contains a non-empty value of
the model’s primary key, then the FormHelper will create an edit form for that record. For example,
if we browse to http://site.com/recipes/edit/5, we would get the following:

// Controller/RecipesController.php:
public function edit($id = null) {
if (empty($this->request->data)) {
$this->request->data = $this->Recipe->findById($id);
} else {
// Save logic goes here
}
}
// View/Recipes/edit.ctp:
// Since $this->request->data['Recipe']['id'] = 5,
// we will get an edit form
<?php echo $this->Form->create('Recipe'); ?>

<form id="RecipeEditForm" method="post" action="/recipes/edit/5">
<input type="hidden" name="_method" value="PUT" />

When creating forms for models in plugins, you should always use plugin syntax when creating a
form. This will ensure the form is correctly generated:

echo $this->Form->create('ContactManager.Contact');

The $options array is where most of the form configuration happens. This special array can contain
a number of different key-value pairs that affect the way the form tag is generated.
Changed in version 2.0: The default URL for all forms, is now the current URL including passed,
named, and querystring parameters. You can override this default by supplying $options['url']
in the second parameter of $this->Form->create().

Options for create

There are a number of options for create():

  •  $options['type'] This key is used to specify the type of form to be created. Valid values include ‘post’, ‘get’, ‘file’, ‘put’ and ‘delete’.

Supplying either ‘post’ or ‘get’ changes the form submission method accordingly:

echo $this->Form->create('User', array('type' => 'get'));

Output:

<form id="UserAddForm" method="get" action="/users/add">

Specifying ‘file’ changes the form submission method to ‘post’, and includes an enctype of
“multipart/form-data” on the form tag. This is to be used if there are any file elements inside the
form. The absence of the proper enctype attribute will cause the file uploads not to function:

echo $this->Form->create('User', array('type' => 'file'));

Output:

When using ‘put’ or ‘delete’, your form will be functionally equivalent to a ‘post’ form, but when
submitted, the HTTP request method will be overridden with ‘PUT’ or ‘DELETE’, respectively. This
allows CakePHP to emulate proper REST support in web browsers.

  • $options['action'] The action key allows you to point the form to a specific action in your current controller. For example, if you’d like to point the form to the login() action of the current controller, you would supply an $options array like the following:

echo $this->Form->create('User', array('action' => 'login'));

Output:

<form id="UserLoginForm" method="post" action="/users/login">

Deprecated since version 2.8.0: The $options['action'] option was deprecated as of 2.8.0.
Use the $options['url'] and $options['id'] options instead.

  • $options['url'] If the desired form action isn’t in the current controller, you can specify a URL for the form action using the ‘url’ key of the $options array. The supplied URL can be relative to your CakePHP application:

echo $this->Form->create(false, array(
'url' => array('controller' => 'recipes', 'action' => 'add'),
'id' => 'RecipesAdd'
));

Output:

<form method="post" action="/recipes/add">

or can point to an external domain:

echo $this->Form->create(false, array(
'url' => 'https://www.google.com/search',
'type' => 'get'
));

Output:

<form method="get" action="https://www.google.com/search">

Changed in version 2.8.0: Use 'url' => false if you don’t want to output a URL as the form
action.

  • $options['default'] If ‘default’ has been set to boolean false, the form’s submit action ischanged so that pressing the submit button does not submit the form. If the form is meant to besubmitted via AJAX, setting ‘default’ to false suppresses the form’s default behavior so you can grab the data and submit it via AJAX instead.
  • $options['inputDefaults'] You can declare a set of default options for input() with the inputDefaults key to customize your default input creation:

echo $this->Form->create('User', array(
'inputDefaults' => array(
'label' => false,

'div' => false
)
));

All inputs created from that point forward would inherit the options declared in inputDefaults. You
can override the defaultOptions by declaring the option in the input() call:

echo $this->Form->input('password'); // No div, no label
// has a label element
echo $this->Form->input(
'username',
array('label' => 'Username')
);

 
 
 

osdyui

Skills    Cakephp

Qualifications :-
Location :-,,,
Description:-
Explore
 

  Students (0)