diff --git a/source/appendices.rst b/source/appendices.rst new file mode 100644 index 0000000000000000000000000000000000000000..93486c943073a14d452048d8de5bd158a2521532 --- /dev/null +++ b/source/appendices.rst @@ -0,0 +1,11 @@ +12 Appendices +------------- + +Appendices contain information regarding the new features +introduced in 1.3 and migration path from 1.2 to 1.3 + +12 Appendices +------------- + +Appendices contain information regarding the new features +introduced in 1.3 and migration path from 1.2 to 1.3 diff --git a/source/appendices/migrating-from-cakephp-1-2-to-1-3.rst b/source/appendices/migrating-from-cakephp-1-2-to-1-3.rst new file mode 100644 index 0000000000000000000000000000000000000000..8a5465ec23f7a6fa45705397a1b05002a009634c --- /dev/null +++ b/source/appendices/migrating-from-cakephp-1-2-to-1-3.rst @@ -0,0 +1,1641 @@ +12.1 Migrating from CakePHP 1.2 to 1.3 +-------------------------------------- + +This guide summarizes many of the changes necessary when migrating +from a 1.2 to 1.3 Cake core. Each section contains relevant +information for the modifications made to existing methods as well +as any methods that have been removed/renamed. + +**App File Replacements (important)** + + +- webroot/index.php: Must be replaced due to changes in + bootstrapping process. +- config/core.php: Additional settings have been put in place + which are required for PHP 5.3. +- webroot/test.php: Replace if you want to run unit tests. + +Removed Constants +~~~~~~~~~~~~~~~~~ + +The following constants have been removed from CakePHP. If your +application depends on them you must define them in +``app/config/bootstrap.php`` + + +- ``CIPHER_SEED`` - It has been replaced with Configure class var + ``Security.cipherSeed`` which should be changed in + ``app/config/core.php`` +- ``PEAR`` +- ``INFLECTIONS`` +- ``VALID_NOT_EMPTY`` +- ``VALID_EMAIL`` +- ``VALID_NUMBER`` +- ``VALID_YEAR`` + +Configuration and application bootstrapping +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +**Bootstrapping Additional Paths.** + +In your app/config/bootstrap.php you may have variables like +``$pluginPaths`` or ``$controllerPaths``. +There is a new way to add those paths. As of 1.3 RC1 the +``$pluginPaths`` variables will no longer work. You must use +``App::build()`` to modify paths. + +:: + + App::build(array( + 'plugins' => array('/full/path/to/plugins/', '/next/full/path/to/plugins/'), + 'models' => array('/full/path/to/models/', '/next/full/path/to/models/'), + 'views' => array('/full/path/to/views/', '/next/full/path/to/views/'), + 'controllers' => array('/full/path/to/controllers/', '/next/full/path/to/controllers/'), + 'datasources' => array('/full/path/to/datasources/', '/next/full/path/to/datasources/'), + 'behaviors' => array('/full/path/to/behaviors/', '/next/full/path/to/behaviors/'), + 'components' => array('/full/path/to/components/', '/next/full/path/to/components/'), + 'helpers' => array('/full/path/to/helpers/', '/next/full/path/to/helpers/'), + 'vendors' => array('/full/path/to/vendors/', '/next/full/path/to/vendors/'), + 'shells' => array('/full/path/to/shells/', '/next/full/path/to/shells/'), + 'locales' => array('/full/path/to/locale/', '/next/full/path/to/locale/'), + 'libs' => array('/full/path/to/libs/', '/next/full/path/to/libs/') + )); + + +#. ``App::build(array(`` +#. ``'plugins' => array('/full/path/to/plugins/', '/next/full/path/to/plugins/'),`` +#. ``'models' => array('/full/path/to/models/', '/next/full/path/to/models/'),`` +#. ``'views' => array('/full/path/to/views/', '/next/full/path/to/views/'),`` +#. ``'controllers' => array('/full/path/to/controllers/', '/next/full/path/to/controllers/'),`` +#. ``'datasources' => array('/full/path/to/datasources/', '/next/full/path/to/datasources/'),`` +#. ``'behaviors' => array('/full/path/to/behaviors/', '/next/full/path/to/behaviors/'),`` +#. ``'components' => array('/full/path/to/components/', '/next/full/path/to/components/'),`` +#. ``'helpers' => array('/full/path/to/helpers/', '/next/full/path/to/helpers/'),`` +#. ``'vendors' => array('/full/path/to/vendors/', '/next/full/path/to/vendors/'),`` +#. ``'shells' => array('/full/path/to/shells/', '/next/full/path/to/shells/'),`` +#. ``'locales' => array('/full/path/to/locale/', '/next/full/path/to/locale/'),`` +#. ``'libs' => array('/full/path/to/libs/', '/next/full/path/to/libs/')`` +#. ``));`` + +Also changed is the order in which bootstrapping occurs. In the +past ``app/config/core.php`` was loaded **after** +``app/config/bootstrap.php``. This caused any ``App::import()`` in +an application bootstrap to be un-cached and considerably slower +than a cached include. In 1.3 core.php is loaded and the core cache +configs are created **before** bootstrap.php is loaded. + +**Loading custom inflections** + +``inflections.php`` has been removed, it was an unnecessary file +hit, and the related features have been refactored into a method to +increase their flexibility. You now use ``Inflector::rules()`` to +load custom inflections. + +:: + + Inflector::rules('singular', array( + 'rules' => array('/^(bil)er$/i' => '\1', '/^(inflec|contribu)tors$/i' => '\1ta'), + 'uninflected' => array('singulars'), + 'irregular' => array('spins' => 'spinor') + )); + + +#. ``Inflector::rules('singular', array(`` +#. ``'rules' => array('/^(bil)er$/i' => '\1', '/^(inflec|contribu)tors$/i' => '\1ta'),`` +#. ``'uninflected' => array('singulars'),`` +#. ``'irregular' => array('spins' => 'spinor')`` +#. ``));`` + +Will merge the supplied rules into the infection sets, with the +added rules taking precedence over the core rules. + +File renames and internal changes +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +**Library Renames** + +Core libraries of libs/session.php, libs/socket.php, +libs/model/schema.php and libs/model/behavior.php have been renamed +so that there is a better mapping between filenames and main +classes contained within (as well as dealing with some name-spacing +issues): + + +- session.php ⇒ cake\_session.php + + + - App::import('Core', 'Session') ⇒ App::import('Core', + 'CakeSession') + +- socket.php ⇒ cake\_socket.php + + + - App::import('Core', 'Socket') ⇒ App::import('Core', + 'CakeSocket') + +- schema.php ⇒ cake\_schema.php + + + - App::import('Model', 'Schema') ⇒ App::import('Model', + 'CakeSchema') + +- behavior.php ⇒ model\_behavior.php + + + - App::import('Core', 'Behavior') ⇒ App::import('Core', + 'ModelBehavior') + + +In most cases, the above renaming will not affect userland code. + +**Inheritance from Object** + +The following classes no longer extend Object: + + +- Router +- Set +- Inflector +- Cache +- CacheEngine + +If you were using Object methods from these classes, you will need +to not use those methods. + +Controller & Components +~~~~~~~~~~~~~~~~~~~~~~~ + +**Controller** + + +- ``Controller::set()`` no longer changes variables from + ``$var_name`` to ``$varName``. Variables always appear in the view + exactly as you set them. + +- ``Controller::set('title', $var)`` no longer sets + ``$title_for_layout`` when rendering the layout. + ``$title_for_layout`` is still populated by default. But if you + want to customize it, use + ``$this->set('title_for_layout', $var)``. + +- ``Controller::$pageTitle`` has been removed. Use + ``$this->set('title_for_layout', $var);`` instead. + +- Controller has two new methods ``startupProcess`` and + ``shutdownProcess``. These methods are responsible for handling the + controller startup and shutdown processes. + +**Component** + + +- ``Component::triggerCallback`` has been added. It is a generic + hook into the component callback process. It supplants + ``Component::startup()``, ``Component::shutdown()`` and + ``Component::beforeRender()`` as the preferred way to trigger + callbacks. + +**CookieComponent** + + +- ``del`` is deprecated use ``delete`` + +**AclComponent + DbAcl** + +Node reference checks done with paths are now less greedy and will +no longer consume intermediary nodes when doing searches. In the +past given the structure: + +:: + + ROOT/ + Users/ + Users/ + edit + + +#. ``ROOT/`` +#. ``Users/`` +#. ``Users/`` +#. ``edit`` + +The path ``ROOT/Users`` would match the last Users node instead of +the first. In 1.3, if you were expecting to get the last node you +would need to use the path ``ROOT/Users/Users`` + +**RequestHandlerComponent** + + +- ``getReferrer`` is deprecated use ``getReferer`` + +**SessionComponent & SessionHelper** + + +- ``del`` is deprecated use ``delete`` + +``SessionComponent::setFlash()`` second param used to be used for +setting the layout and accordingly rendered a layout file. This has +been modifed to use an element. If you specified custom session +flash layouts in your applications you will need to make the +following changes. + + +#. Move the required layout files into app/views/elements +#. Rename the $content\_for\_layout variable to $message +#. Make sure you have ``echo $session->flash();`` in your layout + +``SessionComponent`` and ``SessionHelper`` are not automatically +loaded. +Both ``SessionComponent`` and ``SessionHelper`` are no longer +automatically included without you asking for them. SessionHelper +and SessionComponent now act like every other component and must be +declared like any other helper/component. You should update +``AppController::$components`` and ``AppController::$helpers`` to +include these classes to retain existing behavior. + +:: + + var $components = array('Session', 'Auth', ...); + var $helpers = array('Session', 'Html', 'Form' ...); + + +#. ``var $components = array('Session', 'Auth', ...);`` +#. ``var $helpers = array('Session', 'Html', 'Form' ...);`` + +These change were done to make CakePHP more explicit and +declarative in what classes you the application developer want to +use. In the past there was no way to avoid loading the Session +classes without modifying core files. Which is something we want +you to be able to avoid. In addition Session classes were the only +magical component and helper. This change helps unify and normalize +behavior amongst all classes. + +Library Classes +~~~~~~~~~~~~~~~ + +**CakeSession** + + +- ``del`` is deprecated use ``delete`` + +**SessionComponent** + + +- ``SessionComponent::setFlash()`` now uses an *element* instead + of a *layout* as its second parameter. Be sure to move any flash + layouts from app/views/layouts to app/views/elements and change + instances of $content\_for\_layout to $message. + +**Folder** + + +- ``mkdir`` is deprecated use ``create`` +- ``mv`` is deprecated use ``move`` +- ``ls`` is deprecated use ``read`` +- ``cp`` is deprecated use ``copy`` +- ``rm`` is deprecated use ``delete`` + +**Set** + + +- ``isEqual`` is deprecated. Use == or ===. + +**String** + + +- ``getInstance`` is deprecated, call String methods statically. + +**Router** + +``Routing.admin`` is deprecated. It provided an inconsistent +behavior with other prefix style routes in that it was treated +differently. Instead you should use ``Routing.prefixes``. Prefix +routes in 1.3 do not require additional routes to be declared +manually. All prefix routes will be generated automatically. To +update simply change your core.php. + +:: + + //from: + Configure::write('Routing.admin', 'admin'); + + //to: + Configure::write('Routing.prefixes', array('admin')); + + +#. ``//from:`` +#. ``Configure::write('Routing.admin', 'admin');`` +#. ``//to:`` +#. ``Configure::write('Routing.prefixes', array('admin'));`` + +See the New features guide for more information on using prefix +routes. A small change has also been done to routing params. Routed +params should now only consist of alphanumeric chars, - and \_ or +``/[A-Z0-9-_+]+/``. + +:: + + Router::connect('/:$%@#param/:action/*', array(...)); // BAD + Router::connect('/:can/:anybody/:see/:m-3/*', array(...)); //Acceptable + + +#. ``Router::connect('/:$%@#param/:action/*', array(...)); // BAD`` +#. ``Router::connect('/:can/:anybody/:see/:m-3/*', array(...)); //Acceptable`` + +For 1.3 the internals of the Router were heavily refactored to +increase performance and reduce code clutter. The side effect of +this is two seldom used features were removed, as they were +problematic and buggy even with the existing code base. First path +segments using full regular expressions was removed. You can no +longer create routes like + +:: + + Router::connect('/([0-9]+)-p-(.*)/', array('controller' => 'products', 'action' => 'show')); + + +#. ``Router::connect('/([0-9]+)-p-(.*)/', array('controller' => 'products', 'action' => 'show'));`` + +These routes complicated route compilation and impossible to +reverse route. If you need routes like this, it is recommended that +you use route parameters with capture patterns. Next mid-route +greedy star support has been removed. It was previously possible to +use a greedy star in the middle of a route. + +:: + + Router::connect( + '/pages/*/:event', + array('controller' => 'pages', 'action' => 'display'), + array('event' => '[a-z0-9_-]+') + ); + + +#. ``Router::connect(`` +#. ``'/pages/*/:event',`` +#. ``array('controller' => 'pages', 'action' => 'display'),`` +#. ``array('event' => '[a-z0-9_-]+')`` +#. ``);`` + +This is no longer supported as mid-route greedy stars behaved +erratically, and complicated route compiling. Outside of these two +edge-case features and the above changes the router behaves exactly +as it did in 1.2 + +Also, people using the 'id' key in array-form URLs will notice that +Router::url() now treats this as a named parameter. If you +previously used this approach for passing the ID parameter to +actions, you will need to rewrite all your $html->link() and +$this->redirect() calls to reflect this change. + +:: + + // old format: + $url = array('controller' => 'posts', 'action' => 'view', 'id' => $id); + // use cases: + Router::url($url); + $html->link($url); + $this->redirect($url); + // 1.2 result: + /posts/view/123 + // 1.3 result: + /posts/view/id:123 + // correct format: + $url = array('controller' => 'posts', 'action' => 'view', $id); + + +#. ``// old format:`` +#. ``$url = array('controller' => 'posts', 'action' => 'view', 'id' => $id);`` +#. ``// use cases:`` +#. ``Router::url($url);`` +#. ``$html->link($url);`` +#. ``$this->redirect($url);`` +#. ``// 1.2 result:`` +#. ``/posts/view/123`` +#. ``// 1.3 result:`` +#. ``/posts/view/id:123`` +#. ``// correct format:`` +#. ``$url = array('controller' => 'posts', 'action' => 'view', $id);`` + +**Dispatcher** + +``Dispatcher`` is no longer capable of setting a controller's +layout/viewPath with request parameters. Control of these +properties should be handled by the Controller, not the Dispatcher. +This feature was also undocumented, and untested. + +**Debugger** + + +- ``Debugger::checkSessionKey()`` has been renamed to + ``Debugger::checkSecurityKeys()`` +- Calling ``Debugger::output("text")`` no longer works. Use + ``Debugger::output("txt")``. + +**Object** + + +- ``Object::$_log`` has been removed. ``CakeLog::write`` is now + called statically. See `New Logging features `_ + for more information on changes made to logging. + +**Sanitize** + + +- ``Sanitize::html()`` now actually always returns escaped + strings. In the past using the ``$remove`` parameter would skip + entity encoding, returning possibly dangerous content. +- ``Sanitize::clean()`` now has a ``remove_html`` option. This + will trigger the ``strip_tags`` feature of ``Sanitize::html()``, + and must be used in conjunction with the ``encode`` parameter. + +**Configure and App** + + +- Configure::listObjects() replaced by App::objects() +- Configure::corePaths() replaced by App::core() +- Configure::buildPaths() replaced by App::build() +- Configure no longer manages paths. +- Configure::write('modelPaths', array...) replaced by + App::build(array('models' => array...)) +- Configure::read('modelPaths') replaced by App::path('models') +- There is no longer a debug = 3. The controller dumps generated + by this setting often caused memory consumption issues making it an + impractical and unusable setting. The ``$cakeDebug`` variable has + also been removed from ``View::renderLayout`` You should remove + this variable reference to avoid errors. +- ``Configure::load()`` can now load configuration files from + plugins. Use ``Configure::load('plugin.file');`` to load + configuration files from plugins. Any configuration files in your + application that use ``.`` in the name should be updated to use + ``_`` + +**Cache** + +In addition to being able to load CacheEngines from app/libs or +plugins, Cache underwent some refactoring for CakePHP1.3. These +refactorings focused around reducing the number and frequency of +method calls. The end result was a significant performance +improvement with only a few minor API changes which are detailed +below. + +The changes in Cache removed the singletons used for each Engine +type, and instead an engine instance is made for each unique key +created with ``Cache::config()``. Since engines are not singletons +anymore, ``Cache::engine()`` was not needed and was removed. In +addition ``Cache::isInitialized()`` now checks cache +*configuration names*, not cache *engine names*. You can still use +``Cache::set()`` or ``Cache::engine()`` to modify cache +configurations. Also checkout the +`New features guide `_ for +more information on the additional methods added to ``Cache``. + +It should be noted that using an app/libs or plugin cache engine +for the default cache config can cause performance issues as the +import that loads these classes will always be uncached. It is +recommended that you either use one of the core cache engines for +your ``default`` configuration, or manually include the cache +engine class before configuring it. Furthermore any non-core cache +engine configurations should be done in +``app/config/bootstrap.php`` for the same reasons detailed above. + +Model Databases and Datasources +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +**Model** + + +- ``Model::del()`` and ``Model::remove()`` have been removed in + favor of ``Model::delete()``, which is now the canonical delete + method. +- ``Model::findAll``, findCount, findNeighbours, removed. +- Dynamic calling of setTablePrefix() has been removed. + tableprefix should be with the ``$tablePrefix`` property, and any + other custom construction behavior should be done in an overridden + ``Model::__construct()``. +- ``DboSource::query()`` now throws warnings for un-handled model + methods, instead of trying to run them as queries. This means, + people starting transactions improperly via the + ``$this->Model->begin()`` syntax will need to update their code so + that it accesses the model's DataSource object directly. +- Missing validation methods will now trigger errors in + development mode. +- Missing behaviors will now trigger a cakeError. +- ``Model::find(first)`` will no longer use the id property for + default conditions if no conditions are supplied and id is not + empty. Instead no conditions will be used +- For Model::saveAll() the default value for option 'validate' is + now 'first' instead of true + +**Datasources** + + +- DataSource::exists() has been refactored to be more consistent + with non-database backed datasources. Previously, if you set + ``var $useTable = false; var $useDbConfig = 'custom';``, it was + impossible for ``Model::exists()`` to return anything but false. + This prevented custom datasources from using ``create()`` or + ``update()`` correctly without some ugly hacks. If you have custom + datasources that implement ``create()``, ``update()``, and + ``read()`` (since ``Model::exists()`` will make a call to + ``Model::find('count')``, which is passed to + ``DataSource::read()``), make sure to re-run your unit tests on + 1.3. + +**Databases** + +Most database configurations no longer support the 'connect' key +(which has been deprecated since pre-1.2). Instead, set +``'persistent' => true`` or false to determine whether or not a +persistent database connection should be used + +**SQL log dumping** + +A commonly asked question is how can one disable or remove the SQL +log dump at the bottom of the page?. In previous versions the HTML +SQL log generation was buried inside DboSource. For 1.3 there is a +new core element called ``sql_dump``. ``DboSource`` no longer +automatically outputs SQL logs. If you want to output SQL logs in +1.3, do the following: + +:: + + element('sql_dump'); ?> + + +#. ``element('sql_dump'); ?>`` + +You can place this element anywhere in your layout or view. The +``sql_dump`` element will only generate output when +``Configure::read('debug')`` is equal to 2. You can of course +customize or override this element in your app by creating +``app/views/elements/sql_dump.ctp``. + +View and Helpers +~~~~~~~~~~~~~~~~ + +**View** + + +- ``View::renderElement`` removed. Use ``View::element()`` + instead. +- Automagic support for ``.thtml`` view file extension has been + removed either declare ``$this->ext = 'thtml';`` in your + controllers, or rename your views to use ``.ctp`` +- ``View::set('title', $var)`` no longer sets + ``$title_for_layout`` when rendering the layout. + ``$title_for_layout`` is still populated by default. But if you + want to customize it, use ``$this->set('title_for_layout', $var)``. +- ``View::$pageTitle`` has been removed. Use + ``$this->set('title_for_layout', $var);`` instead. +- The ``$cakeDebug`` layout variable associated with debug = 3 has + been removed. Remove it from your layouts as it will cause errors. + Also see the notes related to SQL log dumping and Configure for + more information. + +All core helpers no longer use ``Helper::output()``. The method was +inconsistently used and caused output issues with many of +FormHelper's methods. If you previously overrode +``AppHelper::output()`` to force helpers to auto-echo you will need +to update your view files to manually echo helper output. + +**TextHelper** + + +- ``TextHelper::trim()`` is deprecated, used ``truncate()`` + instead. +- ``TextHelper::highlight()`` no longer has: +- an ``$highlighter`` parameter. Use ``$options['format']`` + instead. +- an ``$considerHtml``parameter. Use ``$options['html']`` instead. +- ``TextHelper::truncate()`` no longer has: +- an ``$ending`` parameter. Use ``$options['ending']`` instead. +- an ``$exact`` parameter. Use ``$options['exact']`` instead. +- an ``$considerHtml``parameter. Use ``$options['html']`` + instead. + +**PaginatorHelper** + +PaginatorHelper has had a number of enhancements applied to make +styling easier. +``prev()``, ``next()``, ``first()`` and ``last()`` + +The disabled state of these methods now defaults to ```` tags +instead of ``
`` tags. + +passedArgs are now auto merged with url options in paginator. + +``sort()``, ``prev()``, ``next()`` now add additional class names +to the generated html. ``prev()`` adds a class of prev. ``next()`` +adds a class of next. ``sort()`` will add the direction currently +being sorted, either asc or desc. + +**FormHelper** + + +- ``FormHelper::dateTime()`` no longer has a ``$showEmpty`` + parameter. Use ``$attributes['empty']`` instead. +- ``FormHelper::year()`` no longer has a ``$showEmpty`` parameter. + Use ``$attributes['empty']`` instead. +- ``FormHelper::month()`` no longer has a ``$showEmpty`` + parameter. Use ``$attributes['empty']`` instead. +- ``FormHelper::day()`` no longer has a ``$showEmpty`` parameter. + Use ``$attributes['empty']`` instead. +- ``FormHelper::minute()`` no longer has a ``$showEmpty`` + parameter. Use ``$attributes['empty']`` instead. +- ``FormHelper::meridian()`` no longer has a ``$showEmpty`` + parameter. Use ``$attributes['empty']`` instead. +- ``FormHelper::select()`` no longer has a ``$showEmpty`` + parameter. Use ``$attributes['empty']`` instead. +- Default urls generated by form helper no longer contain 'id' + parameter. This makes default urls more consistent with documented + userland routes. Also enables reverse routing to work in a more + intuitive fashion with default FormHelper urls. +- ``FormHelper::submit()`` Can now create other types of inputs + other than type=submit. Use the type option to control the type of + input generated. +- ``FormHelper::button()`` Now creates `` + + + + +The ``button`` input type allows for a special ``$option`` +attribute called ``'escape'`` which accepts a bool and determines +whether to HTML entity encode the $title of the button. Defaults to +false. + +:: + + Form->button('Submit Form', array('type'=>'submit','escape'=>true)); + ?> + + +#. ``Form->button('Submit Form', array('type'=>'submit','escape'=>true));`` +#. ``?>`` + +year +~~~~ + +``year(string $fieldName, int $minYear, int $maxYear, mixed $selected, array $attributes)`` + +Creates a select element populated with the years from ``$minYear`` +to ``$maxYear``, with the $selected year selected by default. HTML +attributes may be supplied in $attributes. If +``$attributes['empty']`` is false, the select will not include an +empty option. + +:: + + Form->year('purchased',2000,date('Y')); + ?> + + +#. ``Form->year('purchased',2000,date('Y'));`` +#. ``?>`` + +Will output: + +:: + + + +month +~~~~~ + +``month(string $fieldName, mixed $selected, array $attributes)`` + +Creates a select element populated with month names. + +:: + + Form->month('mob'); + ?> + + +#. ``Form->month('mob');`` +#. ``?>`` + +Will output: + +:: + + + +You can pass in your own array of months to be used by setting the +'monthNames' attribute, or have months displayed as numbers by +passing false. (Note: the default months are internationalized and +can be translated using localization.) + +:: + + Form->month('mob', null, array('monthNames' => false)); + ?> + + +#. ``Form->month('mob', null, array('monthNames' => false));`` +#. ``?>`` + +dateTime +~~~~~~~~ + +``dateTime($fieldName, $dateFormat = 'DMY', $timeFormat = '12', $selected = null, $attributes = array())`` + +Creates a set of select inputs for date and time. Valid values for +$dateformat are ‘DMY’, ‘MDY’, ‘YMD’ or ‘NONE’. Valid values for +$timeFormat are ‘12’, ‘24’, and null. + +You can specify not to display empty values by setting +"array('empty' => false)" in the attributes parameter. You also can +pre-select the current datetime by setting $selected = null and +$attributes = array("empty" => false). + +day +~~~ + +``day(string $fieldName, mixed $selected, array $attributes, boolean $showEmpty)`` + +Creates a select element populated with the (numerical) days of the +month. + +To create an empty option with prompt text of your choosing (e.g. +the first option is 'Day'), you can supply the text as the final +parameter as follows: + +:: + + Form->day('created'); + ?> + + +#. ``Form->day('created');`` +#. ``?>`` + +Will output: + +:: + + + +hour +~~~~ + +``hour(string $fieldName, boolean $format24Hours, mixed $selected, array $attributes, boolean $showEmpty)`` + +Creates a select element populated with the hours of the day. + +minute +~~~~~~ + +``minute(string $fieldName, mixed $selected, array $attributes, boolean $showEmpty)`` + +Creates a select element populated with the minutes of the hour. + +meridian +~~~~~~~~ + +``meridian(string $fieldName, mixed $selected, array $attributes, boolean $showEmpty)`` + +Creates a select element populated with ‘am’ and ‘pm’. + +error +~~~~~ + +``error(string $fieldName, mixed $text, array $options)`` + +Shows a validation error message, specified by $text, for the given +field, in the event that a validation error has occurred. + +Options: + + +- 'escape' bool Whether or not to html escape the contents of the + error. +- 'wrap' mixed Whether or not the error message should be wrapped + in a div. If a string, will be used as the HTML tag to use. +- 'class' string The classname for the error message + +file +~~~~ + +``file(string $fieldName, array $options)`` + +Creates a file input. + +:: + + Form->create('User',array('type'=>'file')); + echo $this->Form->file('avatar'); + ?> + + +#. ``Form->create('User',array('type'=>'file'));`` +#. ``echo $this->Form->file('avatar');`` +#. ``?>`` + +Will output: + +:: + + + + +When using ``$this->Form->file()``, remember to set the form +encoding-type, by setting the type option to 'file' in +``$this->Form->create()`` +hidden +~~~~~~ + +``hidden(string $fieldName, array $options)`` + +Creates a hidden form input. Example: + +:: + + Form->hidden('id'); + ?> + + +#. ``Form->hidden('id');`` +#. ``?>`` + +Will output: + +:: + + + +isFieldError +~~~~~~~~~~~~ + +``isFieldError(string $fieldName)`` + +Returns true if the supplied $fieldName has an active validation +error. + +:: + + Form->isFieldError('gender')){ + echo $this->Form->error('gender'); + } + ?> + + +#. ``Form->isFieldError('gender')){`` +#. ``echo $this->Form->error('gender');`` +#. ``}`` +#. ``?>`` + +When using ``$this->Form->input()``, errors are rendered by +default. +label +~~~~~ + +``label(string $fieldName, string $text, array $attributes)`` + +Creates a label tag, populated with $text. + +:: + + Form->label('status'); + ?> + + +#. ``Form->label('status');`` +#. ``?>`` + +Will output: + +:: + + + +password +~~~~~~~~ + +``password(string $fieldName, array $options)`` + +Creates a password field. + +:: + + Form->password('password'); + ?> + + +#. ``Form->password('password');`` +#. ``?>`` + +Will output: + +:: + + + +radio +~~~~~ + +``radio(string $fieldName, array $options, array $attributes)`` + +Creates a radio button input. Use ``$attributes['value']`` to set +which value should be selected default. + +Use ``$attributes['separator']`` to specify HTML in between radio +buttons (e.g.
). + +Radio elements are wrapped with a label and fieldset by default. +Set ``$attributes['legend']`` to false to remove them. + +:: + + 'Male','F'=>'Female'); + $attributes=array('legend'=>false); + echo $this->Form->radio('gender',$options,$attributes); + ?> + + +#. ``'Male','F'=>'Female');`` +#. ``$attributes=array('legend'=>false);`` +#. ``echo $this->Form->radio('gender',$options,$attributes);`` +#. ``?>`` + +Will output: + +:: + + + + + + + +If for some reason you don't want the hidden input, setting +``$attributes['value']`` to a selected value or boolean false will +do just that. + +select +~~~~~~ + +``select(string $fieldName, array $options, mixed $selected, array $attributes)`` + +Creates a select element, populated with the items in ``$options``, +with the option specified by ``$selected`` shown as selected by +default. If you wish to display your own default option, add your +string value to the 'empty' key in the ``$attributes`` variable, or +set it to false to turn off the default empty option + +:: + + 'Male', 'F' => 'Female'); + echo $this->Form->select('gender', $options) + ?> + + +#. `` 'Male', 'F' => 'Female');`` +#. ``echo $this->Form->select('gender', $options)`` +#. ``?>`` + +Will output: + +:: + + + +The ``select`` input type allows for a special ``$option`` +attribute called ``'escape'`` which accepts a bool and determines +whether to HTML entity encode the contents of the select options. +Defaults to true. + +:: + + 'Male', 'F' => 'Female'); + echo $this->Form->select('gender', $options, null, array('escape' => false)); + ?> + + +#. `` 'Male', 'F' => 'Female');`` +#. ``echo $this->Form->select('gender', $options, null, array('escape' => false));`` +#. ``?>`` + +submit +~~~~~~ + +``submit(string $caption, array $options)`` + +Creates a submit button with caption ``$caption``. If the supplied +``$caption`` is a URL to an image (it contains a ‘.’ character), +the submit button will be rendered as an image. + +It is enclosed between ``div`` tags by default; you can avoid this +by declaring ``$options['div'] = false``. + +:: + + Form->submit(); + ?> + + +#. ``Form->submit();`` +#. ``?>`` + +Will output: + +:: + +
+ +You can also pass a relative or absolute url to an image for the +caption parameter instead of caption text. + +:: + + Form->submit('ok.png'); + ?> + + +#. ``Form->submit('ok.png');`` +#. ``?>`` + +Will output: + +:: + +
+ +text +~~~~ + +``text(string $fieldName, array $options)`` + +Creates a text input field. + +:: + + Form->text('first_name'); + ?> + + +#. ``Form->text('first_name');`` +#. ``?>`` + +Will output: + +:: + + + +textarea +~~~~~~~~ + +``textarea(string $fieldName, array $options)`` + +Creates a textarea input field. + +:: + + Form->textarea('notes'); + ?> + + +#. ``Form->textarea('notes');`` +#. ``?>`` + +Will output: + +:: + + + +The ``textarea`` input type allows for the ``$options`` attribute +of ``'escape'`` which determines whether or not the contents of the +textarea should be escaped. Defaults to ``true``. +:: + + Form->textarea('notes', array('escape' => false); + // OR.... + echo $this->Form->input('notes', array('type' => 'textarea', 'escape' => false); + ?> + + +#. ``Form->textarea('notes', array('escape' => false);`` +#. ``// OR....`` +#. ``echo $this->Form->input('notes', array('type' => 'textarea', 'escape' => false);`` +#. ``?>`` + +7.3.5 Form Element-Specific Methods +----------------------------------- + +The rest of the methods available in the FormHelper are for +creating specific form elements. Many of these methods also make +use of a special $options parameter. In this case, however, +$options is used primarily to specify HTML tag attributes (such as +the value or DOM id of an element in the form). + +:: + + Form->text('username', array('class' => 'users')); ?> + + +#. ``Form->text('username', array('class' => 'users')); ?>`` + +Will output: + +:: + + + + +checkbox +~~~~~~~~ + +``checkbox(string $fieldName, array $options)`` + +Creates a checkbox form element. This method also generates an +associated hidden form input to force the submission of data for +the specified field. + +:: + + Form->checkbox('done'); ?> + + +#. ``Form->checkbox('done'); ?>`` + +Will output: + +:: + + + + +It is possible to specify the value of the checkbox by using the +$options array: + +:: + + Form->checkbox('done', array('value' => 555)); ?> + + +#. ``Form->checkbox('done', array('value' => 555)); ?>`` + +Will output: + +:: + + + + +If you don't want the Form helper to create a hidden input: + +:: + + Form->checkbox('done', array('hiddenField' => false)); ?> + + +#. ``Form->checkbox('done', array('hiddenField' => false)); ?>`` + +Will output: + +:: + + + +button +~~~~~~ + +``button(string $title, array $options = array())`` + +Creates an HTML button with the specified title and a default type +of "button". Setting ``$options['type']`` will output one of the +three possible button types: + + +#. submit: Same as the ``$this->Form->submit`` method - (the + default). +#. reset: Creates a form reset button. +#. button: Creates a standard push button. + +:: + + Form->button('A Button'); + echo $this->Form->button('Another Button', array('type'=>'button')); + echo $this->Form->button('Reset the Form', array('type'=>'reset')); + echo $this->Form->button('Submit Form', array('type'=>'submit')); + ?> + + +#. ``Form->button('A Button');`` +#. ``echo $this->Form->button('Another Button', array('type'=>'button'));`` +#. ``echo $this->Form->button('Reset the Form', array('type'=>'reset'));`` +#. ``echo $this->Form->button('Submit Form', array('type'=>'submit'));`` +#. ``?>`` + +Will output: + +:: + + + + + + +The ``button`` input type allows for a special ``$option`` +attribute called ``'escape'`` which accepts a bool and determines +whether to HTML entity encode the $title of the button. Defaults to +false. + +:: + + Form->button('Submit Form', array('type'=>'submit','escape'=>true)); + ?> + + +#. ``Form->button('Submit Form', array('type'=>'submit','escape'=>true));`` +#. ``?>`` + +year +~~~~ + +``year(string $fieldName, int $minYear, int $maxYear, mixed $selected, array $attributes)`` + +Creates a select element populated with the years from ``$minYear`` +to ``$maxYear``, with the $selected year selected by default. HTML +attributes may be supplied in $attributes. If +``$attributes['empty']`` is false, the select will not include an +empty option. + +:: + + Form->year('purchased',2000,date('Y')); + ?> + + +#. ``Form->year('purchased',2000,date('Y'));`` +#. ``?>`` + +Will output: + +:: + + + +month +~~~~~ + +``month(string $fieldName, mixed $selected, array $attributes)`` + +Creates a select element populated with month names. + +:: + + Form->month('mob'); + ?> + + +#. ``Form->month('mob');`` +#. ``?>`` + +Will output: + +:: + + + +You can pass in your own array of months to be used by setting the +'monthNames' attribute, or have months displayed as numbers by +passing false. (Note: the default months are internationalized and +can be translated using localization.) + +:: + + Form->month('mob', null, array('monthNames' => false)); + ?> + + +#. ``Form->month('mob', null, array('monthNames' => false));`` +#. ``?>`` + +dateTime +~~~~~~~~ + +``dateTime($fieldName, $dateFormat = 'DMY', $timeFormat = '12', $selected = null, $attributes = array())`` + +Creates a set of select inputs for date and time. Valid values for +$dateformat are ‘DMY’, ‘MDY’, ‘YMD’ or ‘NONE’. Valid values for +$timeFormat are ‘12’, ‘24’, and null. + +You can specify not to display empty values by setting +"array('empty' => false)" in the attributes parameter. You also can +pre-select the current datetime by setting $selected = null and +$attributes = array("empty" => false). + +day +~~~ + +``day(string $fieldName, mixed $selected, array $attributes, boolean $showEmpty)`` + +Creates a select element populated with the (numerical) days of the +month. + +To create an empty option with prompt text of your choosing (e.g. +the first option is 'Day'), you can supply the text as the final +parameter as follows: + +:: + + Form->day('created'); + ?> + + +#. ``Form->day('created');`` +#. ``?>`` + +Will output: + +:: + + + +hour +~~~~ + +``hour(string $fieldName, boolean $format24Hours, mixed $selected, array $attributes, boolean $showEmpty)`` + +Creates a select element populated with the hours of the day. + +minute +~~~~~~ + +``minute(string $fieldName, mixed $selected, array $attributes, boolean $showEmpty)`` + +Creates a select element populated with the minutes of the hour. + +meridian +~~~~~~~~ + +``meridian(string $fieldName, mixed $selected, array $attributes, boolean $showEmpty)`` + +Creates a select element populated with ‘am’ and ‘pm’. + +error +~~~~~ + +``error(string $fieldName, mixed $text, array $options)`` + +Shows a validation error message, specified by $text, for the given +field, in the event that a validation error has occurred. + +Options: + + +- 'escape' bool Whether or not to html escape the contents of the + error. +- 'wrap' mixed Whether or not the error message should be wrapped + in a div. If a string, will be used as the HTML tag to use. +- 'class' string The classname for the error message + +file +~~~~ + +``file(string $fieldName, array $options)`` + +Creates a file input. + +:: + + Form->create('User',array('type'=>'file')); + echo $this->Form->file('avatar'); + ?> + + +#. ``Form->create('User',array('type'=>'file'));`` +#. ``echo $this->Form->file('avatar');`` +#. ``?>`` + +Will output: + +:: + + + + +When using ``$this->Form->file()``, remember to set the form +encoding-type, by setting the type option to 'file' in +``$this->Form->create()`` +hidden +~~~~~~ + +``hidden(string $fieldName, array $options)`` + +Creates a hidden form input. Example: + +:: + + Form->hidden('id'); + ?> + + +#. ``Form->hidden('id');`` +#. ``?>`` + +Will output: + +:: + + + +isFieldError +~~~~~~~~~~~~ + +``isFieldError(string $fieldName)`` + +Returns true if the supplied $fieldName has an active validation +error. + +:: + + Form->isFieldError('gender')){ + echo $this->Form->error('gender'); + } + ?> + + +#. ``Form->isFieldError('gender')){`` +#. ``echo $this->Form->error('gender');`` +#. ``}`` +#. ``?>`` + +When using ``$this->Form->input()``, errors are rendered by +default. +label +~~~~~ + +``label(string $fieldName, string $text, array $attributes)`` + +Creates a label tag, populated with $text. + +:: + + Form->label('status'); + ?> + + +#. ``Form->label('status');`` +#. ``?>`` + +Will output: + +:: + + + +password +~~~~~~~~ + +``password(string $fieldName, array $options)`` + +Creates a password field. + +:: + + Form->password('password'); + ?> + + +#. ``Form->password('password');`` +#. ``?>`` + +Will output: + +:: + + + +radio +~~~~~ + +``radio(string $fieldName, array $options, array $attributes)`` + +Creates a radio button input. Use ``$attributes['value']`` to set +which value should be selected default. + +Use ``$attributes['separator']`` to specify HTML in between radio +buttons (e.g.
). + +Radio elements are wrapped with a label and fieldset by default. +Set ``$attributes['legend']`` to false to remove them. + +:: + + 'Male','F'=>'Female'); + $attributes=array('legend'=>false); + echo $this->Form->radio('gender',$options,$attributes); + ?> + + +#. ``'Male','F'=>'Female');`` +#. ``$attributes=array('legend'=>false);`` +#. ``echo $this->Form->radio('gender',$options,$attributes);`` +#. ``?>`` + +Will output: + +:: + + + + + + + +If for some reason you don't want the hidden input, setting +``$attributes['value']`` to a selected value or boolean false will +do just that. + +select +~~~~~~ + +``select(string $fieldName, array $options, mixed $selected, array $attributes)`` + +Creates a select element, populated with the items in ``$options``, +with the option specified by ``$selected`` shown as selected by +default. If you wish to display your own default option, add your +string value to the 'empty' key in the ``$attributes`` variable, or +set it to false to turn off the default empty option + +:: + + 'Male', 'F' => 'Female'); + echo $this->Form->select('gender', $options) + ?> + + +#. `` 'Male', 'F' => 'Female');`` +#. ``echo $this->Form->select('gender', $options)`` +#. ``?>`` + +Will output: + +:: + + + +The ``select`` input type allows for a special ``$option`` +attribute called ``'escape'`` which accepts a bool and determines +whether to HTML entity encode the contents of the select options. +Defaults to true. + +:: + + 'Male', 'F' => 'Female'); + echo $this->Form->select('gender', $options, null, array('escape' => false)); + ?> + + +#. `` 'Male', 'F' => 'Female');`` +#. ``echo $this->Form->select('gender', $options, null, array('escape' => false));`` +#. ``?>`` + +submit +~~~~~~ + +``submit(string $caption, array $options)`` + +Creates a submit button with caption ``$caption``. If the supplied +``$caption`` is a URL to an image (it contains a ‘.’ character), +the submit button will be rendered as an image. + +It is enclosed between ``div`` tags by default; you can avoid this +by declaring ``$options['div'] = false``. + +:: + + Form->submit(); + ?> + + +#. ``Form->submit();`` +#. ``?>`` + +Will output: + +:: + +
+ +You can also pass a relative or absolute url to an image for the +caption parameter instead of caption text. + +:: + + Form->submit('ok.png'); + ?> + + +#. ``Form->submit('ok.png');`` +#. ``?>`` + +Will output: + +:: + +
+ +text +~~~~ + +``text(string $fieldName, array $options)`` + +Creates a text input field. + +:: + + Form->text('first_name'); + ?> + + +#. ``Form->text('first_name');`` +#. ``?>`` + +Will output: + +:: + + + +textarea +~~~~~~~~ + +``textarea(string $fieldName, array $options)`` + +Creates a textarea input field. + +:: + + Form->textarea('notes'); + ?> + + +#. ``Form->textarea('notes');`` +#. ``?>`` + +Will output: + +:: + + + +The ``textarea`` input type allows for the ``$options`` attribute +of ``'escape'`` which determines whether or not the contents of the +textarea should be escaped. Defaults to ``true``. +:: + + Form->textarea('notes', array('escape' => false); + // OR.... + echo $this->Form->input('notes', array('type' => 'textarea', 'escape' => false); + ?> + + +#. ``Form->textarea('notes', array('escape' => false);`` +#. ``// OR....`` +#. ``echo $this->Form->input('notes', array('type' => 'textarea', 'escape' => false);`` +#. ``?>`` diff --git a/source/core-helpers/html.rst b/source/core-helpers/html.rst new file mode 100644 index 0000000000000000000000000000000000000000..18491a8f1555997fc99ff76596d4dd5614789458 --- /dev/null +++ b/source/core-helpers/html.rst @@ -0,0 +1,109 @@ +7.4 HTML +-------- + +The role of the HtmlHelper in CakePHP is to make HTML-related +options easier, faster, and more resilient to change. Using this +helper will enable your application to be more light on its feet, +and more flexible on where it is placed in relation to the root of +a domain. + +Before we look at HtmlHelper's methods, you'll need to know about a +few configuration and usage situations that will help you use this +class. First in an effort to assuage those who dislike short tags +() or many echo() calls in their view code all methods of +HtmlHelper are passed to the output() method. If you wish to enable +automatic output of the generated helper HTML you can simply +implement output() in your AppHelper. + +:: + + function output($str) { + echo $str; + } + + +#. ``function output($str) {`` +#. ``echo $str;`` +#. ``}`` + +Doing this will remove the need to add echo statements to your view +code. + +Many HtmlHelper methods also include a $htmlAttributes parameter, +that allow you to tack on any extra attributes on your tags. Here +are a few examples of how to use the $htmlAttributes parameter: + +:: + + Desired attributes: + Array parameter: array('class'=>'someClass') + + Desired attributes: + Array parameter: array('name' => 'foo', 'value' => 'bar') + + +#. ``Desired attributes: `` +#. ``Array parameter: array('class'=>'someClass')`` +#. ```` +#. ``Desired attributes: `` +#. ``Array parameter: array('name' => 'foo', 'value' => 'bar')`` + +The HtmlHelper is available in all views by default. If you're +getting an error informing you that it isn't there, it's usually +due to its name being missing from a manually configured $helpers +controller variable. + +7.4 HTML +-------- + +The role of the HtmlHelper in CakePHP is to make HTML-related +options easier, faster, and more resilient to change. Using this +helper will enable your application to be more light on its feet, +and more flexible on where it is placed in relation to the root of +a domain. + +Before we look at HtmlHelper's methods, you'll need to know about a +few configuration and usage situations that will help you use this +class. First in an effort to assuage those who dislike short tags +() or many echo() calls in their view code all methods of +HtmlHelper are passed to the output() method. If you wish to enable +automatic output of the generated helper HTML you can simply +implement output() in your AppHelper. + +:: + + function output($str) { + echo $str; + } + + +#. ``function output($str) {`` +#. ``echo $str;`` +#. ``}`` + +Doing this will remove the need to add echo statements to your view +code. + +Many HtmlHelper methods also include a $htmlAttributes parameter, +that allow you to tack on any extra attributes on your tags. Here +are a few examples of how to use the $htmlAttributes parameter: + +:: + + Desired attributes: + Array parameter: array('class'=>'someClass') + + Desired attributes: + Array parameter: array('name' => 'foo', 'value' => 'bar') + + +#. ``Desired attributes: `` +#. ``Array parameter: array('class'=>'someClass')`` +#. ```` +#. ``Desired attributes: `` +#. ``Array parameter: array('name' => 'foo', 'value' => 'bar')`` + +The HtmlHelper is available in all views by default. If you're +getting an error informing you that it isn't there, it's usually +due to its name being missing from a manually configured $helpers +controller variable. diff --git a/source/core-helpers/html/changing-the-tags-output-by-htmlhelper.rst b/source/core-helpers/html/changing-the-tags-output-by-htmlhelper.rst new file mode 100644 index 0000000000000000000000000000000000000000..ddd2ed970fb1dd84f410e231fc89606e6bdc8d7a --- /dev/null +++ b/source/core-helpers/html/changing-the-tags-output-by-htmlhelper.rst @@ -0,0 +1,53 @@ +7.4.2 Changing the tags output by HtmlHelper +-------------------------------------------- + +The built in tag sets for ``HtmlHelper`` are XHTML compliant, +however if you need to generate HTML for HTML4 you will need to +create and load a new tags config file containing the tags you'd +like to use. To change the tags used create ``app/config/tags.php`` +containing: + +:: + + $tags = array( + 'metalink' => '', + 'input' => '', + //... + ); + + +#. ``$tags = array(`` +#. ``'metalink' => '',`` +#. ``'input' => '',`` +#. ``//...`` +#. ``);`` + +You can then load this tag set by calling +``$html->loadConfig('tags');`` + +7.4.2 Changing the tags output by HtmlHelper +-------------------------------------------- + +The built in tag sets for ``HtmlHelper`` are XHTML compliant, +however if you need to generate HTML for HTML4 you will need to +create and load a new tags config file containing the tags you'd +like to use. To change the tags used create ``app/config/tags.php`` +containing: + +:: + + $tags = array( + 'metalink' => '', + 'input' => '', + //... + ); + + +#. ``$tags = array(`` +#. ``'metalink' => '',`` +#. ``'input' => '',`` +#. ``//...`` +#. ``);`` + +You can then load this tag set by calling +``$html->loadConfig('tags');`` diff --git a/source/core-helpers/html/creating-breadcrumb-trails-with-htmlhelper.rst b/source/core-helpers/html/creating-breadcrumb-trails-with-htmlhelper.rst new file mode 100644 index 0000000000000000000000000000000000000000..e4ce121c766591536ced45f8f6517bc42ad07231 --- /dev/null +++ b/source/core-helpers/html/creating-breadcrumb-trails-with-htmlhelper.rst @@ -0,0 +1,57 @@ +7.4.3 Creating breadcrumb trails with HtmlHelper +------------------------------------------------ + +CakePHP has the built in ability to automatically create a +breadcrumb trail in your app. To set this up, first add something +similar to the following in your layout template. + +:: + + echo $this->Html->getCrumbs(' > ','Home'); + + +#. ``echo $this->Html->getCrumbs(' > ','Home');`` + +Now, in your view you'll want to add the following to start the +breadcrumb trails on each of the pages. + +:: + + echo $this->Html->addCrumb('Users', '/users'); + echo $this->Html->addCrumb('Add User', '/users/add'); + + +#. ``echo $this->Html->addCrumb('Users', '/users');`` +#. ``echo $this->Html->addCrumb('Add User', '/users/add');`` + +This will add the output of "**Home > Users > Add User**" in your +layout where getCrumbs was added. + +7.4.3 Creating breadcrumb trails with HtmlHelper +------------------------------------------------ + +CakePHP has the built in ability to automatically create a +breadcrumb trail in your app. To set this up, first add something +similar to the following in your layout template. + +:: + + echo $this->Html->getCrumbs(' > ','Home'); + + +#. ``echo $this->Html->getCrumbs(' > ','Home');`` + +Now, in your view you'll want to add the following to start the +breadcrumb trails on each of the pages. + +:: + + echo $this->Html->addCrumb('Users', '/users'); + echo $this->Html->addCrumb('Add User', '/users/add'); + + +#. ``echo $this->Html->addCrumb('Users', '/users');`` +#. ``echo $this->Html->addCrumb('Add User', '/users/add');`` + +This will add the output of "**Home > Users > Add User**" in your +layout where getCrumbs was added. diff --git a/source/core-helpers/html/inserting-well-formatted-elements.rst b/source/core-helpers/html/inserting-well-formatted-elements.rst new file mode 100644 index 0000000000000000000000000000000000000000..85facba5a4929a46a5ae23ffd4f0719455e3334b --- /dev/null +++ b/source/core-helpers/html/inserting-well-formatted-elements.rst @@ -0,0 +1,1787 @@ +7.4.1 Inserting Well-Formatted elements +--------------------------------------- + +The most important task the HtmlHelper accomplishes is creating +well formed markup. Don't be afraid to use it often - you can cache +views in CakePHP in order to save some CPU cycles when views are +being rendered and delivered. This section will cover some of the +methods of the HtmlHelper and how to use them. + +charset +~~~~~~~ + +``charset(string $charset=null)`` + +Used to create a meta tag specifying the document's character. +Defaults to UTF-8. + +:: + + + Html->charset(); ?> + + +#. ``Html->charset(); ?>`` + +Will output: + +:: + + + +Alternatively, + +:: + + Html->charset('ISO-8859-1'); ?> + + +#. ``Html->charset('ISO-8859-1'); ?>`` + +Will output: + +:: + + + +css +~~~ + +``css(mixed $path, string $rel = null, array $options = array())`` + +Creates a link(s) to a CSS style-sheet. If key 'inline' is set to +false in $options parameter, the link tags are added to the +$scripts\_for\_layout variable which you can print inside the head +tag of the document. + +This method of CSS inclusion assumes that the CSS file specified +resides inside the /app/webroot/css directory. + +:: + + Html->css('forms'); ?> + + +#. ``Html->css('forms'); ?>`` + +Will output: + +:: + + + +The first parameter can be an array to include multiple files. + +:: + + Html->css(array('forms','tables','menu')); ?> + + +#. ``Html->css(array('forms','tables','menu')); ?>`` + +Will output: + +:: + + + + + +meta +~~~~ + +``meta(string $type, string $url = null, array $attributes = array())`` + +This method is handy for linking to external resources like +RSS/Atom feeds and favicons. Like css(), you can specify whether or +not you'd like this tag to appear inline or in the head tag by +setting the 'inline' key in the $attributes parameter to false, ie +- ``array('inline' => false)``. + +If you set the "type" attribute using the $attributes parameter, +CakePHP contains a few shortcuts: + +type +translated value +html +text/html +rss +application/rss+xml +atom +application/atom+xml +icon +image/x-icon +:: + + Html->meta( + 'favicon.ico', + '/favicon.ico', + array('type' => 'icon') + );?> //Output (line breaks added)

+ + + Html->meta( + 'Comments', + '/comments/index.rss', + array('type' => 'rss')); + ?> + + //Output (line breaks added) + + + +#. ``Html->meta(`` +#. ``'favicon.ico',`` +#. ``'/favicon.ico',`` +#. ``array('type' => 'icon')`` +#. ``);?> //Output (line breaks added)

`` +#. ```` +#. ```` +#. ``Html->meta(`` +#. ``'Comments',`` +#. ``'/comments/index.rss',`` +#. ``array('type' => 'rss'));`` +#. ``?>`` +#. ```` +#. ``//Output (line breaks added)`` +#. ```` + +This method can also be used to add the meta keywords and +descriptions. Example: + +:: + + Html->meta( + 'keywords', + 'enter any meta keyword here' + );?> + //Output + // + + Html->meta( + 'description', + 'enter any meta description here' + );?> + + //Output + + +#. ``Html->meta(`` +#. ``'keywords',`` +#. ``'enter any meta keyword here'`` +#. ``);?>`` +#. ``//Output `` +#. ``//`` +#. ``Html->meta(`` +#. ``'description',`` +#. ``'enter any meta description here'`` +#. ``);?>`` +#. ``//Output `` + +If you want to add a custom meta tag then the first parameter +should be set to an array. To output a robots noindex tag use the +following code: + +:: + + echo $this->Html->meta(array('name' => 'robots', 'content' => 'noindex')); + + +#. ``echo $this->Html->meta(array('name' => 'robots', 'content' => 'noindex'));`` + +docType +~~~~~~~ + +``docType(string $type = 'xhtml-strict')`` + +Returns a (X)HTML doctype tag. Supply the doctype according to the +following table: + +type +translated value +html +text/html +html4-strict +HTML4 Strict +html4-trans +HTML4 Transitional +html4-frame +HTML4 Frameset +xhtml-strict +XHTML1 Strict +xhtml-trans +XHTML1 Transitional +xhtml-frame +XHTML1 Frameset +xhtml11 +XHTML 1.1 +:: + + Html->docType(); ?> + + + Html->docType('html4-trans'); ?> + + + +#. ``Html->docType(); ?>`` +#. ```` +#. ``Html->docType('html4-trans'); ?>`` +#. ```` + +style +~~~~~ + +``style(array $data, boolean $oneline = true)`` + +Builds CSS style definitions based on the keys and values of the +array passed to the method. Especially handy if your CSS file is +dynamic. + +:: + + Html->style(array( + 'background' => '#633', + 'border-bottom' => '1px solid #000', + 'padding' => '10px' + )); ?> + + +#. ``Html->style(array(`` +#. ``'background' => '#633',`` +#. ``'border-bottom' => '1px solid #000',`` +#. ``'padding' => '10px'`` +#. ``)); ?>`` + +Will output: + +:: + + background:#633; border-bottom:1px solid #000; padding:10px; + +image +~~~~~ + +``image(string $path, array $htmlAttributes = array())`` + +Creates a formatted image tag. The path supplied should be relative +to /app/webroot/img/. + +:: + + Html->image('cake_logo.png', array('alt' => 'CakePHP'))?> + + +#. ``Html->image('cake_logo.png', array('alt' => 'CakePHP'))?>`` + +Will output: + +:: + + CakePHP + +To create an image link specify the link destination using the +``url`` option in ``$htmlAttributes``. + +:: + + Html->image("recipes/6.jpg", array( + "alt" => "Brownies", + 'url' => array('controller' => 'recipes', 'action' => 'view', 6) + )); ?> + + +#. ``Html->image("recipes/6.jpg", array(`` +#. ``"alt" => "Brownies",`` +#. ``'url' => array('controller' => 'recipes', 'action' => 'view', 6)`` +#. ``)); ?>`` + +Will output: + +:: + + + Brownies + + +link +~~~~ + +``link(string $title, mixed $url = null, array $options = array(), string $confirmMessage = false)`` + +General purpose method for creating HTML links. Use ``$options`` to +specify attributes for the element and whether or not the +``$title`` should be escaped. + +:: + + Html->link('Enter', '/pages/home', array('class' => 'button', 'target' => '_blank')); ?> + + +#. ``Html->link('Enter', '/pages/home', array('class' => 'button', 'target' => '_blank')); ?>`` + +Will output: + +:: + + + Enter + +Specify ``$confirmMessage`` to display a javascript ``confirm()`` +dialog. + +:: + + Html->link( + 'Delete', + array('controller' => 'recipes', 'action' => 'delete', 6), + array(), + "Are you sure you wish to delete this recipe?" + );?> + + +#. ``Html->link(`` +#. ``'Delete',`` +#. ``array('controller' => 'recipes', 'action' => 'delete', 6),`` +#. ``array(),`` +#. ``"Are you sure you wish to delete this recipe?"`` +#. ``);?>`` + +Will output: + +:: + + + Delete + +Query strings can also be created with ``link()``. + +:: + + Html->link('View image', array( + 'controller' => 'images', + 'action' => 'view', + 1, + '?' => array('height' => 400, 'width' => 500)) + ); + + +#. ``Html->link('View image', array(`` +#. ``'controller' => 'images',`` +#. ``'action' => 'view',`` +#. ``1,`` +#. ``'?' => array('height' => 400, 'width' => 500))`` +#. ``);`` + +Will output: + +:: + + + View image + +HTML special characters in ``$title`` will be converted to HTML +entities. To disable this conversion, set the escape option to +false in the ``$options`` array. + +:: + + Html->link( + $this->Html->image("recipes/6.jpg", array("alt" => "Brownies")), + "recipes/view/6", + array('escape' => false) + ); + + ?> + + +#. ``Html->link(`` +#. ``$this->Html->image("recipes/6.jpg", array("alt" => "Brownies")),`` +#. ``"recipes/view/6",`` +#. ``array('escape' => false)`` +#. ``);`` +#. ``?>`` + +Will output: + +:: + + + Brownies + + +Also check +`HtmlHelper::url `_ method +for more examples of different types of urls. + +tag +~~~ + +``tag(string $tag, string $text, array $htmlAttributes)`` + +Returns text wrapped in a specified tag. If no text is specified +then only the opening is returned. + +:: + + Html->tag('span', 'Hello World.', array('class' => 'welcome'));?> + + //Output + Hello World + + //No text specified. + Html->tag('span', null, array('class' => 'welcome'));?> + + //Output + + + +#. ``Html->tag('span', 'Hello World.', array('class' => 'welcome'));?>`` +#. ```` +#. ``//Output`` +#. ``Hello World`` +#. ```` +#. ``//No text specified.`` +#. ``Html->tag('span', null, array('class' => 'welcome'));?>`` +#. ```` +#. ``//Output`` +#. ```` + +Text is not escaped by default but you may use +``$htmlOptions['escape'] = true`` to escape your text. This +replaces a fourth parameter ``boolean $escape = false`` that was +available in previous versions. + +div +~~~ + +``div(string $class, string $text, array $options)`` + +Used for creating div-wrapped sections of markup. The first +parameter specifies a CSS class, and the second is used to supply +the text to be wrapped by div tags. If the last parameter has been +set to true, $text will be printed HTML-escaped. + +If no text is specified, only an opening div tag is returned. + +:: + + + Html->div('error', 'Please enter your credit card number.');?> + + //Output +
Please enter your credit card number.
+ + +#. ``Html->div('error', 'Please enter your credit card number.');?>`` +#. `` `` +#. ``//Output`` +#. ``
Please enter your credit card number.
`` + +para +~~~~ + +``para(string $class, string $text, array $htmlAttributes, boolean $escape = false)`` + +Returns a text wrapped in a CSS-classed

tag. If no text is +supplied, only a starting

tag is returned. +:: + + Html->para(null, 'Hello World.');?> + + //Output +

Hello World.

+ + +#. ``Html->para(null, 'Hello World.');?>`` +#. ```` +#. ``//Output`` +#. ``

Hello World.

`` + +script +~~~~~~ + +script(mixed $url, mixed $options) + +Creates link(s) to a javascript file. If key ``inline`` is set to +false in $options, the link tags are added to the +$scripts\_for\_layout variable which you can print inside the head +tag of the document. + +Include a script file into the page. ``$options['inline']`` +controls whether or not a script should be returned inline or added +to $scripts\_for\_layout. ``$options['once']`` controls, whether or +not you want to include this script once per request or more than +once. + +You can also use $options to set additional properties to the +generated script tag. If an array of script tags is used, the +attributes will be applied to all of the generated script tags. + +This method of javascript file inclusion assumes that the +javascript file specified resides inside the /app/webroot/js +directory. + +:: + + Html->script('scripts'); ?> + + +#. ``Html->script('scripts'); ?>`` + +Will output: + +:: + + + +You can link to files with absolute paths as well to link files +that are not in ``app/webroot/js`` + +:: + + Html->script('/otherdir/script_file'); ?> + + +#. ``Html->script('/otherdir/script_file'); ?>`` + +The first parameter can be an array to include multiple files. + +:: + + Html->script(array('jquery','wysiwyg','scripts')); ?> + + +#. ``Html->script(array('jquery','wysiwyg','scripts')); ?>`` + +Will output: + +:: + + + + + +scriptBlock +~~~~~~~~~~~ + +scriptBlock($code, $options = array()) + +Generate a code block containing ``$code`` set +``$options['inline']`` to false to have the script block appear in +``$scripts_for_layout``. Also new is the ability to add attributes +to script tags. +``$this->html->scriptBlock('stuff', array('defer' => true));`` will +create a script tag with ``defer="defer"`` attribute. + +scriptStart +~~~~~~~~~~~ + +scriptStart($options = array()) + +Begin a buffering code block. This code block will capture all +output between ``scriptStart()`` and ``scriptEnd()`` and create an +script tag. Options are the same as ``scriptBlock()`` + +scriptEnd +~~~~~~~~~ + +scriptEnd() + +End a buffering script block, returns the generated script element +or null if the script block was opened with inline = false. + +An example of using ``scriptStart()`` and ``scriptEnd()`` would +be: + +:: + + $this->Html->scriptStart(array('inline' => false)); + + echo $this->Js->alert('I am in the javascript'); + + $this->Html->scriptEnd(); + + +#. ``$this->Html->scriptStart(array('inline' => false));`` +#. ``echo $this->Js->alert('I am in the javascript');`` +#. ``$this->Html->scriptEnd();`` + +tableHeaders +~~~~~~~~~~~~ + +``tableHeaders(array $names, array $trOptions = null, array $thOptions = null)`` + +Creates a row of table header cells to be placed inside of +tags. +:: + + Html->tableHeaders(array('Date','Title','Active'));?> + + //Output + + + + + + + Html->tableHeaders( + array('Date','Title','Active'), + array('class' => 'status'), + array('class' => 'product_table') + );?> + + //Output + + + + + + + +#. ``Html->tableHeaders(array('Date','Title','Active'));?>`` +#. `` `` +#. ``//Output`` +#. ```` +#. ```` +#. ```` +#. ```` +#. ```` +#. ```` +#. ``Html->tableHeaders(`` +#. ``array('Date','Title','Active'),`` +#. ``array('class' => 'status'),`` +#. ``array('class' => 'product_table')`` +#. ``);?>`` +#. ```` +#. ``//Output`` +#. ```` +#. ```` +#. ```` +#. ```` +#. ```` + +tableCells +~~~~~~~~~~ + +``tableCells(array $data, array $oddTrOptions = null, array $evenTrOptions = null, $useCount = false, $continueOddEven = true)`` + +Creates table cells, in rows, assigning attributes differently +for odd- and even-numbered rows. Wrap a single table cell within an +array() for specific + + + + Html->tableCells(array( + array('Jul 7th, 2007', array('Best Brownies', array('class'=>'highlight')) , 'Yes'), + array('Jun 21st, 2007', 'Smart Cookies', 'Yes'), + array('Aug 1st, 2006', 'Anti-Java Cake', array('No', array('id'=>'special'))), + )); + ?> + + //Output + + + + + Html->tableCells( + array( + array('Red', 'Apple'), + array('Orange', 'Orange'), + array('Yellow', 'Banana'), + ), + array('class' => 'darker') + ); + ?> + + //Output + + + + + +#. ``Html->tableCells(array(`` +#. ``array('Jul 7th, 2007', 'Best Brownies', 'Yes'),`` +#. ``array('Jun 21st, 2007', 'Smart Cookies', 'Yes'),`` +#. ``array('Aug 1st, 2006', 'Anti-Java Cake', 'No'),`` +#. ``));`` +#. ``?>`` +#. ```` +#. ``//Output`` +#. ```` +#. ```` +#. ```` +#. ```` +#. ``Html->tableCells(array(`` +#. ``array('Jul 7th, 2007', array('Best Brownies', array('class'=>'highlight')) , 'Yes'),`` +#. ``array('Jun 21st, 2007', 'Smart Cookies', 'Yes'),`` +#. ``array('Aug 1st, 2006', 'Anti-Java Cake', array('No', array('id'=>'special'))),`` +#. ``));`` +#. ``?>`` +#. ```` +#. ``//Output`` +#. ```` +#. ```` +#. ```` +#. ```` +#. ``Html->tableCells(`` +#. ``array(`` +#. ``array('Red', 'Apple'),`` +#. ``array('Orange', 'Orange'),`` +#. ``array('Yellow', 'Banana'),`` +#. ``),`` +#. ``array('class' => 'darker')`` +#. ``);`` +#. ``?>`` +#. ```` +#. ``//Output`` +#. ```` +#. ```` +#. ```` + +url +~~~ + +``url(mixed $url = NULL, boolean $full = false)`` + +Returns an URL pointing to a combination of controller and action. +If $url is empty, it returns the REQUEST\_URI, otherwise it +generates the url for the controller and action combo. If full is +true, the full base URL will be prepended to the result. + +:: + + Html->url(array( + "controller" => "posts", + "action" => "view", + "bar"));?> + + // Output + /posts/view/bar + + +#. ``Html->url(array(`` +#. ``"controller" => "posts",`` +#. ``"action" => "view",`` +#. ``"bar"));?>`` +#. ```` +#. ``// Output`` +#. ``/posts/view/bar`` + +Here are a few more usage examples: + +URL with named parameters + +:: + + Html->url(array( + "controller" => "posts", + "action" => "view", + "foo" => "bar")); + ?> + + // Output + /posts/view/foo:bar + + +#. ``Html->url(array(`` +#. ``"controller" => "posts",`` +#. ``"action" => "view",`` +#. ``"foo" => "bar"));`` +#. ``?>`` +#. ```` +#. ``// Output`` +#. ``/posts/view/foo:bar`` + +URL with extension + +:: + + Html->url(array( + "controller" => "posts", + "action" => "list", + "ext" => "rss")); + ?> + + // Output + /posts/list.rss + + +#. ``Html->url(array(`` +#. ``"controller" => "posts",`` +#. ``"action" => "list",`` +#. ``"ext" => "rss"));`` +#. ``?>`` +#. ```` +#. ``// Output`` +#. ``/posts/list.rss`` + +URL (starting with '/') with the full base URL prepended. + +:: + + Html->url('/posts', true); ?> + + //Output + http://somedomain.com/posts + + +#. ``Html->url('/posts', true); ?>`` +#. `` `` +#. ``//Output`` +#. ``http://somedomain.com/posts`` + +URL with GET params and named anchor + +:: + + Html->url(array( + "controller" => "posts", + "action" => "search", + "?" => array("foo" => "bar"), + "#" => "first")); + ?> + + //Output + /posts/search?foo=bar#first + + +#. ``Html->url(array(`` +#. ``"controller" => "posts",`` +#. ``"action" => "search",`` +#. ``"?" => array("foo" => "bar"),`` +#. ``"#" => "first"));`` +#. ``?>`` +#. `` `` +#. ``//Output`` +#. ``/posts/search?foo=bar#first`` + +For further information check +`Router::url `_ +in the API. + +7.4.1 Inserting Well-Formatted elements +--------------------------------------- + +The most important task the HtmlHelper accomplishes is creating +well formed markup. Don't be afraid to use it often - you can cache +views in CakePHP in order to save some CPU cycles when views are +being rendered and delivered. This section will cover some of the +methods of the HtmlHelper and how to use them. + +charset +~~~~~~~ + +``charset(string $charset=null)`` + +Used to create a meta tag specifying the document's character. +Defaults to UTF-8. + +:: + + + Html->charset(); ?> + + +#. ``Html->charset(); ?>`` + +Will output: + +:: + + + +Alternatively, + +:: + + Html->charset('ISO-8859-1'); ?> + + +#. ``Html->charset('ISO-8859-1'); ?>`` + +Will output: + +:: + + + +css +~~~ + +``css(mixed $path, string $rel = null, array $options = array())`` + +Creates a link(s) to a CSS style-sheet. If key 'inline' is set to +false in $options parameter, the link tags are added to the +$scripts\_for\_layout variable which you can print inside the head +tag of the document. + +This method of CSS inclusion assumes that the CSS file specified +resides inside the /app/webroot/css directory. + +:: + + Html->css('forms'); ?> + + +#. ``Html->css('forms'); ?>`` + +Will output: + +:: + + + +The first parameter can be an array to include multiple files. + +:: + + Html->css(array('forms','tables','menu')); ?> + + +#. ``Html->css(array('forms','tables','menu')); ?>`` + +Will output: + +:: + + + + + +meta +~~~~ + +``meta(string $type, string $url = null, array $attributes = array())`` + +This method is handy for linking to external resources like +RSS/Atom feeds and favicons. Like css(), you can specify whether or +not you'd like this tag to appear inline or in the head tag by +setting the 'inline' key in the $attributes parameter to false, ie +- ``array('inline' => false)``. + +If you set the "type" attribute using the $attributes parameter, +CakePHP contains a few shortcuts: + +type +translated value +html +text/html +rss +application/rss+xml +atom +application/atom+xml +icon +image/x-icon +:: + + Html->meta( + 'favicon.ico', + '/favicon.ico', + array('type' => 'icon') + );?> //Output (line breaks added)

+ + + Html->meta( + 'Comments', + '/comments/index.rss', + array('type' => 'rss')); + ?> + + //Output (line breaks added) + + + +#. ``Html->meta(`` +#. ``'favicon.ico',`` +#. ``'/favicon.ico',`` +#. ``array('type' => 'icon')`` +#. ``);?> //Output (line breaks added)

`` +#. ```` +#. ```` +#. ``Html->meta(`` +#. ``'Comments',`` +#. ``'/comments/index.rss',`` +#. ``array('type' => 'rss'));`` +#. ``?>`` +#. ```` +#. ``//Output (line breaks added)`` +#. ```` + +This method can also be used to add the meta keywords and +descriptions. Example: + +:: + + Html->meta( + 'keywords', + 'enter any meta keyword here' + );?> + //Output + // + + Html->meta( + 'description', + 'enter any meta description here' + );?> + + //Output + + +#. ``Html->meta(`` +#. ``'keywords',`` +#. ``'enter any meta keyword here'`` +#. ``);?>`` +#. ``//Output `` +#. ``//`` +#. ``Html->meta(`` +#. ``'description',`` +#. ``'enter any meta description here'`` +#. ``);?>`` +#. ``//Output `` + +If you want to add a custom meta tag then the first parameter +should be set to an array. To output a robots noindex tag use the +following code: + +:: + + echo $this->Html->meta(array('name' => 'robots', 'content' => 'noindex')); + + +#. ``echo $this->Html->meta(array('name' => 'robots', 'content' => 'noindex'));`` + +docType +~~~~~~~ + +``docType(string $type = 'xhtml-strict')`` + +Returns a (X)HTML doctype tag. Supply the doctype according to the +following table: + +type +translated value +html +text/html +html4-strict +HTML4 Strict +html4-trans +HTML4 Transitional +html4-frame +HTML4 Frameset +xhtml-strict +XHTML1 Strict +xhtml-trans +XHTML1 Transitional +xhtml-frame +XHTML1 Frameset +xhtml11 +XHTML 1.1 +:: + + Html->docType(); ?> + + + Html->docType('html4-trans'); ?> + + + +#. ``Html->docType(); ?>`` +#. ```` +#. ``Html->docType('html4-trans'); ?>`` +#. ```` + +style +~~~~~ + +``style(array $data, boolean $oneline = true)`` + +Builds CSS style definitions based on the keys and values of the +array passed to the method. Especially handy if your CSS file is +dynamic. + +:: + + Html->style(array( + 'background' => '#633', + 'border-bottom' => '1px solid #000', + 'padding' => '10px' + )); ?> + + +#. ``Html->style(array(`` +#. ``'background' => '#633',`` +#. ``'border-bottom' => '1px solid #000',`` +#. ``'padding' => '10px'`` +#. ``)); ?>`` + +Will output: + +:: + + background:#633; border-bottom:1px solid #000; padding:10px; + +image +~~~~~ + +``image(string $path, array $htmlAttributes = array())`` + +Creates a formatted image tag. The path supplied should be relative +to /app/webroot/img/. + +:: + + Html->image('cake_logo.png', array('alt' => 'CakePHP'))?> + + +#. ``Html->image('cake_logo.png', array('alt' => 'CakePHP'))?>`` + +Will output: + +:: + + CakePHP + +To create an image link specify the link destination using the +``url`` option in ``$htmlAttributes``. + +:: + + Html->image("recipes/6.jpg", array( + "alt" => "Brownies", + 'url' => array('controller' => 'recipes', 'action' => 'view', 6) + )); ?> + + +#. ``Html->image("recipes/6.jpg", array(`` +#. ``"alt" => "Brownies",`` +#. ``'url' => array('controller' => 'recipes', 'action' => 'view', 6)`` +#. ``)); ?>`` + +Will output: + +:: + + + Brownies + + +link +~~~~ + +``link(string $title, mixed $url = null, array $options = array(), string $confirmMessage = false)`` + +General purpose method for creating HTML links. Use ``$options`` to +specify attributes for the element and whether or not the +``$title`` should be escaped. + +:: + + Html->link('Enter', '/pages/home', array('class' => 'button', 'target' => '_blank')); ?> + + +#. ``Html->link('Enter', '/pages/home', array('class' => 'button', 'target' => '_blank')); ?>`` + +Will output: + +:: + + + Enter + +Specify ``$confirmMessage`` to display a javascript ``confirm()`` +dialog. + +:: + + Html->link( + 'Delete', + array('controller' => 'recipes', 'action' => 'delete', 6), + array(), + "Are you sure you wish to delete this recipe?" + );?> + + +#. ``Html->link(`` +#. ``'Delete',`` +#. ``array('controller' => 'recipes', 'action' => 'delete', 6),`` +#. ``array(),`` +#. ``"Are you sure you wish to delete this recipe?"`` +#. ``);?>`` + +Will output: + +:: + + + Delete + +Query strings can also be created with ``link()``. + +:: + + Html->link('View image', array( + 'controller' => 'images', + 'action' => 'view', + 1, + '?' => array('height' => 400, 'width' => 500)) + ); + + +#. ``Html->link('View image', array(`` +#. ``'controller' => 'images',`` +#. ``'action' => 'view',`` +#. ``1,`` +#. ``'?' => array('height' => 400, 'width' => 500))`` +#. ``);`` + +Will output: + +:: + + + View image + +HTML special characters in ``$title`` will be converted to HTML +entities. To disable this conversion, set the escape option to +false in the ``$options`` array. + +:: + + Html->link( + $this->Html->image("recipes/6.jpg", array("alt" => "Brownies")), + "recipes/view/6", + array('escape' => false) + ); + + ?> + + +#. ``Html->link(`` +#. ``$this->Html->image("recipes/6.jpg", array("alt" => "Brownies")),`` +#. ``"recipes/view/6",`` +#. ``array('escape' => false)`` +#. ``);`` +#. ``?>`` + +Will output: + +:: + + + Brownies + + +Also check +`HtmlHelper::url `_ method +for more examples of different types of urls. + +tag +~~~ + +``tag(string $tag, string $text, array $htmlAttributes)`` + +Returns text wrapped in a specified tag. If no text is specified +then only the opening is returned. + +:: + + Html->tag('span', 'Hello World.', array('class' => 'welcome'));?> + + //Output + Hello World + + //No text specified. + Html->tag('span', null, array('class' => 'welcome'));?> + + //Output + + + +#. ``Html->tag('span', 'Hello World.', array('class' => 'welcome'));?>`` +#. ```` +#. ``//Output`` +#. ``Hello World`` +#. ```` +#. ``//No text specified.`` +#. ``Html->tag('span', null, array('class' => 'welcome'));?>`` +#. ```` +#. ``//Output`` +#. ```` + +Text is not escaped by default but you may use +``$htmlOptions['escape'] = true`` to escape your text. This +replaces a fourth parameter ``boolean $escape = false`` that was +available in previous versions. + +div +~~~ + +``div(string $class, string $text, array $options)`` + +Used for creating div-wrapped sections of markup. The first +parameter specifies a CSS class, and the second is used to supply +the text to be wrapped by div tags. If the last parameter has been +set to true, $text will be printed HTML-escaped. + +If no text is specified, only an opening div tag is returned. + +:: + + + Html->div('error', 'Please enter your credit card number.');?> + + //Output +
Please enter your credit card number.
+ + +#. ``Html->div('error', 'Please enter your credit card number.');?>`` +#. `` `` +#. ``//Output`` +#. ``
Please enter your credit card number.
`` + +para +~~~~ + +``para(string $class, string $text, array $htmlAttributes, boolean $escape = false)`` + +Returns a text wrapped in a CSS-classed

tag. If no text is +supplied, only a starting

tag is returned. +:: + + Html->para(null, 'Hello World.');?> + + //Output +

Hello World.

+ + +#. ``Html->para(null, 'Hello World.');?>`` +#. ```` +#. ``//Output`` +#. ``

Hello World.

`` + +script +~~~~~~ + +script(mixed $url, mixed $options) + +Creates link(s) to a javascript file. If key ``inline`` is set to +false in $options, the link tags are added to the +$scripts\_for\_layout variable which you can print inside the head +tag of the document. + +Include a script file into the page. ``$options['inline']`` +controls whether or not a script should be returned inline or added +to $scripts\_for\_layout. ``$options['once']`` controls, whether or +not you want to include this script once per request or more than +once. + +You can also use $options to set additional properties to the +generated script tag. If an array of script tags is used, the +attributes will be applied to all of the generated script tags. + +This method of javascript file inclusion assumes that the +javascript file specified resides inside the /app/webroot/js +directory. + +:: + + Html->script('scripts'); ?> + + +#. ``Html->script('scripts'); ?>`` + +Will output: + +:: + + + +You can link to files with absolute paths as well to link files +that are not in ``app/webroot/js`` + +:: + + Html->script('/otherdir/script_file'); ?> + + +#. ``Html->script('/otherdir/script_file'); ?>`` + +The first parameter can be an array to include multiple files. + +:: + + Html->script(array('jquery','wysiwyg','scripts')); ?> + + +#. ``Html->script(array('jquery','wysiwyg','scripts')); ?>`` + +Will output: + +:: + + + + + +scriptBlock +~~~~~~~~~~~ + +scriptBlock($code, $options = array()) + +Generate a code block containing ``$code`` set +``$options['inline']`` to false to have the script block appear in +``$scripts_for_layout``. Also new is the ability to add attributes +to script tags. +``$this->html->scriptBlock('stuff', array('defer' => true));`` will +create a script tag with ``defer="defer"`` attribute. + +scriptStart +~~~~~~~~~~~ + +scriptStart($options = array()) + +Begin a buffering code block. This code block will capture all +output between ``scriptStart()`` and ``scriptEnd()`` and create an +script tag. Options are the same as ``scriptBlock()`` + +scriptEnd +~~~~~~~~~ + +scriptEnd() + +End a buffering script block, returns the generated script element +or null if the script block was opened with inline = false. + +An example of using ``scriptStart()`` and ``scriptEnd()`` would +be: + +:: + + $this->Html->scriptStart(array('inline' => false)); + + echo $this->Js->alert('I am in the javascript'); + + $this->Html->scriptEnd(); + + +#. ``$this->Html->scriptStart(array('inline' => false));`` +#. ``echo $this->Js->alert('I am in the javascript');`` +#. ``$this->Html->scriptEnd();`` + +tableHeaders +~~~~~~~~~~~~ + +``tableHeaders(array $names, array $trOptions = null, array $thOptions = null)`` + +Creates a row of table header cells to be placed inside of
DateTitleActive
DateTitleActive
DateTitleActive
DateTitleActive
-attributes. + +:: + + Html->tableCells(array( + array('Jul 7th, 2007', 'Best Brownies', 'Yes'), + array('Jun 21st, 2007', 'Smart Cookies', 'Yes'), + array('Aug 1st, 2006', 'Anti-Java Cake', 'No'), + )); + ?> + + //Output +
Jul 7th, 2007Best BrowniesYes
Jun 21st, 2007Smart CookiesYes
Aug 1st, 2006Anti-Java CakeNo
Jul 7th, 2007Best BrowniesYes
Jun 21st, 2007Smart CookiesYes
Aug 1st, 2006Anti-Java CakeNo
RedApple
OrangeOrange
YellowBanana
Jul 7th, 2007Best BrowniesYes
Jun 21st, 2007Smart CookiesYes
Aug 1st, 2006Anti-Java CakeNo
Jul 7th, 2007Best BrowniesYes
Jun 21st, 2007Smart CookiesYes
Aug 1st, 2006Anti-Java CakeNo
RedApple
OrangeOrange
YellowBanana
+tags. +:: + + Html->tableHeaders(array('Date','Title','Active'));?> + + //Output + + + + + + + Html->tableHeaders( + array('Date','Title','Active'), + array('class' => 'status'), + array('class' => 'product_table') + );?> + + //Output + + + + + + + +#. ``Html->tableHeaders(array('Date','Title','Active'));?>`` +#. `` `` +#. ``//Output`` +#. ```` +#. ```` +#. ```` +#. ```` +#. ```` +#. ```` +#. ``Html->tableHeaders(`` +#. ``array('Date','Title','Active'),`` +#. ``array('class' => 'status'),`` +#. ``array('class' => 'product_table')`` +#. ``);?>`` +#. ```` +#. ``//Output`` +#. ```` +#. ```` +#. ```` +#. ```` +#. ```` + +tableCells +~~~~~~~~~~ + +``tableCells(array $data, array $oddTrOptions = null, array $evenTrOptions = null, $useCount = false, $continueOddEven = true)`` + +Creates table cells, in rows, assigning attributes differently +for odd- and even-numbered rows. Wrap a single table cell within an +array() for specific + + + + Html->tableCells(array( + array('Jul 7th, 2007', array('Best Brownies', array('class'=>'highlight')) , 'Yes'), + array('Jun 21st, 2007', 'Smart Cookies', 'Yes'), + array('Aug 1st, 2006', 'Anti-Java Cake', array('No', array('id'=>'special'))), + )); + ?> + + //Output + + + + + Html->tableCells( + array( + array('Red', 'Apple'), + array('Orange', 'Orange'), + array('Yellow', 'Banana'), + ), + array('class' => 'darker') + ); + ?> + + //Output + + + + + +#. ``Html->tableCells(array(`` +#. ``array('Jul 7th, 2007', 'Best Brownies', 'Yes'),`` +#. ``array('Jun 21st, 2007', 'Smart Cookies', 'Yes'),`` +#. ``array('Aug 1st, 2006', 'Anti-Java Cake', 'No'),`` +#. ``));`` +#. ``?>`` +#. ```` +#. ``//Output`` +#. ```` +#. ```` +#. ```` +#. ```` +#. ``Html->tableCells(array(`` +#. ``array('Jul 7th, 2007', array('Best Brownies', array('class'=>'highlight')) , 'Yes'),`` +#. ``array('Jun 21st, 2007', 'Smart Cookies', 'Yes'),`` +#. ``array('Aug 1st, 2006', 'Anti-Java Cake', array('No', array('id'=>'special'))),`` +#. ``));`` +#. ``?>`` +#. ```` +#. ``//Output`` +#. ```` +#. ```` +#. ```` +#. ```` +#. ``Html->tableCells(`` +#. ``array(`` +#. ``array('Red', 'Apple'),`` +#. ``array('Orange', 'Orange'),`` +#. ``array('Yellow', 'Banana'),`` +#. ``),`` +#. ``array('class' => 'darker')`` +#. ``);`` +#. ``?>`` +#. ```` +#. ``//Output`` +#. ```` +#. ```` +#. ```` + +url +~~~ + +``url(mixed $url = NULL, boolean $full = false)`` + +Returns an URL pointing to a combination of controller and action. +If $url is empty, it returns the REQUEST\_URI, otherwise it +generates the url for the controller and action combo. If full is +true, the full base URL will be prepended to the result. + +:: + + Html->url(array( + "controller" => "posts", + "action" => "view", + "bar"));?> + + // Output + /posts/view/bar + + +#. ``Html->url(array(`` +#. ``"controller" => "posts",`` +#. ``"action" => "view",`` +#. ``"bar"));?>`` +#. ```` +#. ``// Output`` +#. ``/posts/view/bar`` + +Here are a few more usage examples: + +URL with named parameters + +:: + + Html->url(array( + "controller" => "posts", + "action" => "view", + "foo" => "bar")); + ?> + + // Output + /posts/view/foo:bar + + +#. ``Html->url(array(`` +#. ``"controller" => "posts",`` +#. ``"action" => "view",`` +#. ``"foo" => "bar"));`` +#. ``?>`` +#. ```` +#. ``// Output`` +#. ``/posts/view/foo:bar`` + +URL with extension + +:: + + Html->url(array( + "controller" => "posts", + "action" => "list", + "ext" => "rss")); + ?> + + // Output + /posts/list.rss + + +#. ``Html->url(array(`` +#. ``"controller" => "posts",`` +#. ``"action" => "list",`` +#. ``"ext" => "rss"));`` +#. ``?>`` +#. ```` +#. ``// Output`` +#. ``/posts/list.rss`` + +URL (starting with '/') with the full base URL prepended. + +:: + + Html->url('/posts', true); ?> + + //Output + http://somedomain.com/posts + + +#. ``Html->url('/posts', true); ?>`` +#. `` `` +#. ``//Output`` +#. ``http://somedomain.com/posts`` + +URL with GET params and named anchor + +:: + + Html->url(array( + "controller" => "posts", + "action" => "search", + "?" => array("foo" => "bar"), + "#" => "first")); + ?> + + //Output + /posts/search?foo=bar#first + + +#. ``Html->url(array(`` +#. ``"controller" => "posts",`` +#. ``"action" => "search",`` +#. ``"?" => array("foo" => "bar"),`` +#. ``"#" => "first"));`` +#. ``?>`` +#. `` `` +#. ``//Output`` +#. ``/posts/search?foo=bar#first`` + +For further information check +`Router::url `_ +in the API. diff --git a/source/core-helpers/javascript.rst b/source/core-helpers/javascript.rst new file mode 100644 index 0000000000000000000000000000000000000000..5374dafd53891c8d7cb631de77ada391c9f51cf1 --- /dev/null +++ b/source/core-helpers/javascript.rst @@ -0,0 +1,25 @@ +7.6 Javascript +-------------- + +The Javascript helper is used to aid in creating well formatted +related javascript tags and codeblocks. There are several methods +some of which are designed to work with the +`Prototype `_ Javascript library. + +The Javascript Helper is deprecated in 1.3 and will be removed in +future versions of CakePHP. See the new JsHelper and HtmlHelper, as +well as the migration guide for where JavascriptHelper's methods +have moved to. + +7.6 Javascript +-------------- + +The Javascript helper is used to aid in creating well formatted +related javascript tags and codeblocks. There are several methods +some of which are designed to work with the +`Prototype `_ Javascript library. + +The Javascript Helper is deprecated in 1.3 and will be removed in +future versions of CakePHP. See the new JsHelper and HtmlHelper, as +well as the migration guide for where JavascriptHelper's methods +have moved to. diff --git a/source/core-helpers/javascript/methods.rst b/source/core-helpers/javascript/methods.rst new file mode 100644 index 0000000000000000000000000000000000000000..4c58f8d256a81c9d752c61f19fc7452a7b7e7c67 --- /dev/null +++ b/source/core-helpers/javascript/methods.rst @@ -0,0 +1,301 @@ +7.6.1 Methods +------------- + +``codeBlock($script, $options = array('allowCache'=>true,'safe'=>true,'inline'=>true), $safe)`` + + +- string $script - The JavaScript to be wrapped in SCRIPT tags +- array $options - Set of options: + + - allowCache: boolean, designates whether this block is cacheable + using the current cache settings. + - safe: boolean, whether this block should be wrapped in CDATA + tags. Defaults to helper's object configuration. + - inline: whether the block should be printed inline, or written + to cached for later output (i.e. $scripts\_for\_layout). + +- boolean $safe - DEPRECATED. Use $options['safe'] instead + +codeBlock returns a formatted script element containing $script. +But can also return null if Javascript helper is set to cache +events. See JavascriptHelper::cacheEvents(). And can write in +``$scripts_for_layout`` if you set $options['inline'] to false. + +``blockEnd()`` + +Ends a block of cached Javascript. Can return either a end script +tag, or empties the buffer, adding the contents to the cachedEvents +array. Its return value depends on the cache settings. See +JavascriptHelper::cacheEvents() + +``link($url, $inline = true)`` + + +- mixed $url - String URL to JavaScript file, or an array of URLs. +- boolean $inline If true, the
DateTitleActive
DateTitleActive
DateTitleActive
DateTitleActive
-attributes. + +:: + + Html->tableCells(array( + array('Jul 7th, 2007', 'Best Brownies', 'Yes'), + array('Jun 21st, 2007', 'Smart Cookies', 'Yes'), + array('Aug 1st, 2006', 'Anti-Java Cake', 'No'), + )); + ?> + + //Output +
Jul 7th, 2007Best BrowniesYes
Jun 21st, 2007Smart CookiesYes
Aug 1st, 2006Anti-Java CakeNo
Jul 7th, 2007Best BrowniesYes
Jun 21st, 2007Smart CookiesYes
Aug 1st, 2006Anti-Java CakeNo
RedApple
OrangeOrange
YellowBanana
Jul 7th, 2007Best BrowniesYes
Jun 21st, 2007Smart CookiesYes
Aug 1st, 2006Anti-Java CakeNo
Jul 7th, 2007Best BrowniesYes
Jun 21st, 2007Smart CookiesYes
Aug 1st, 2006Anti-Java CakeNo
RedApple
OrangeOrange
YellowBanana