PHPackages                             codekanzlei/cake-cktools - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. codekanzlei/cake-cktools

ActiveCakephp-plugin[Utility &amp; Helpers](/categories/utility)

codekanzlei/cake-cktools
========================

codekanzlei Tools &amp; Utilities collection

v4.1.0(10mo ago)472.0k↓39.2%75MITPHPPHP &gt;=7.2.0CI failing

Since Feb 9Pushed 10mo ago4 watchersCompare

[ Source](https://github.com/scherersoftware/cake-cktools)[ Packagist](https://packagist.org/packages/codekanzlei/cake-cktools)[ Docs](https://github.com/scherersoftware/cake-cktools)[ RSS](/packages/codekanzlei-cake-cktools/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (9)Versions (73)Used By (5)

CakePHP 3 cake-cktools
======================

[](#cakephp-3-cake-cktools)

[![License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE.txt)[![Build Status](https://camo.githubusercontent.com/c85216856a9d0914763a2930b052332bd81c6640b11928a16415414bbcb465a4/68747470733a2f2f7472617669732d63692e6f72672f73636865726572736f6674776172652f63616b652d636b746f6f6c732e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/scherersoftware/cake-cktools)

Requirements
------------

[](#requirements)

- [cake-frontend-bridge](https://github.com/scherersoftware/cake-frontend-bridge) for easy js-based interaction with the backend
- [cake-api-baselayer](https://github.com/scherersoftware/cake-api-baselayer) for REST apis
- [Font Awesome](https://fortawesome.github.io/Font-Awesome/) for icons

Installation
------------

[](#installation)

#### 1. require the plugin

[](#1-require-the-plugin)

```
$ composer install codekanzlei/cake-cktools

```

Open a terminal in your project-folder and run these commands:

```
$ composer update

```

#### 3. Setup Appcontroller.php

[](#3-setup-appcontrollerphp)

**`$helpers`**

```
public $helpers =  [
	'CkTools.CkTools'
]

```

Usage
-----

[](#usage)

### 1. CkToolsHelper

[](#1-cktoolshelper)

Being one of CkTools' core features, CkToolsHelper provides many useful functionalities, most of them aimed at generating powerful view elements such as form- and navigation buttons, often with as much as one line of code. Here's an overview of its actions. See `CkToolsHelper.php` for further details.

- `countries(array $countryCodes = null)`Returns a map of countries with their translations. Use an array `$countryCodes` to limit the returned list according to your needs. See `/cake-cktools/config/countries.php` for a full list of country names. @return array
- `country($country)`Returns the translated version of the given country via `$country`, e.g. 'en' @return string
- `function datepickerInput($field, array $options = [])`Creates a neat datepicker input field which is very handy in edit or add views. @return string
- `mailtoLink($email, array $options = [])`Creates a mailto link to the email address given in `$email`. `$options` include `'body'`, `'subject'` and `'caption'`. @return string
- `editButton(EntityInterface $entity, array $options = [])`Renders an edit button for given database record `$entity`. By default, this button will link to the entity's Controller's edit action but this can be overwritten using the `'url'` field of the `$options` array. @return string
- `viewButton(EntityInterface $entity, array $options = [])`Renders a details button for given database record `$entity`. By default, this button will link to the entity's Controller's view action but this can be overwritten using the `'url'` field of the `$options` array. @return string
- `addButton($title = null, array $options = [])`Renders an add button for the current Model. For example, use this in a `Users` index view file to render a button that will create a new record of type `User`@return string
- `deleteButton(EntityInterface $entity, array $options = [])`Renders an delete button for given database record `$entity`. You can define a custom confirm message in the `$options` array's `'confirm'` field. @return string
- `formButtons(array $options = [])`Renders form buttons 'Save' and 'Cancel'. `$options` include `'cancelButton'` which controls wether the cancel button will be rendered or not and `'useReferer'` which controls wether or not the referring address for the request will be returned. @return void
- `button($title, $url = false, array $options = [])`Renders a button. Pass an url object in the `'$url'` param to link to any Controller action you desire. `$options` include `'icon'` (use Font Awesome), `'class'`, and `'additionalClasses'`. Use Twitter Bootstrap for the latter two options. @return string
- `definitionList($data, array $options = [])`Renders a HTML definition list element. Param `$data` holds Keys and values in array strucutre. Use the following line in a view file to get a glimpse of the results of this action.

    ```

    ```

@return string

- `nestedList($data, $content, $level = 0, $isActiveCallback = null)`Renders a nested list. The param `$data` holds the data to be displayed in associative array structure, `$content` is a String template for each node. See `CkToolsHelper.php` for an example call. @return string
- `historyBackButton(array $options = [])`Renders a div with an onclick handler which uses the history API of the Browser. @return string
- `displayStructuredData(array $data, array $options = [])`Display an array in human-readable format. The `'$options'` array includes a field `'expanded'` which, if set true renders a button that toggles display of the list. @return string
- `arrayToUnorderedList(array $array)`Rercursively converts an array to an unordered list. @return string

### 2. MenuHelper

[](#2-menuhelper)

The MenuHelper aims at config-based rendering of hierarchical navigation menus in the UI. Here's an overview of its actions. See `MenuHelper.php` for further details.

- `renderSidebarMenuItems($config)`Creates HTML markup for a menu-bar based on a given menu configuration. The config can be passed as a string or you can create a file `/config/menu.php` that holds the structure of the menu. Use this config file to define a 2-level menu structure consisting of menu items and sub-items for each of them. See `menu.php.default` in the CkTools folder for reference. Use an additional field called `children` in any of the menu fields if you want to use sub-items. If you chose to use a menu config file, use the following call in your default view file: ``@return string
- `prepareMenuConfig($config)`Processes the given menu config, structures it and checks for permissions. Checks menu items as well as their children for URLs that are not allowed. Ignores menu items which have a field `'shouldrender'` with value FALSE. @return array
- hasAllowedChildren(array $children) Uses CakePHP's AuthComponent to check if given array of items 'children' contains at least one URL that is allowed to the current user. @return bool
- isItemActive($item) Compares the current URL with given menu item to determine wether it should be highlighted or not. @return bool

#### `config.php` - a closer look

[](#configphp---a-closer-look)

Here's an example of what `config.php` could look like, explaining more possibilities:

```
$config = [
    'menu' => [
        'dashboard' => [            // first menu item
            'title' => 'Dashboard', // title to be displayed in the menu bar
            'icon' => 'dashboard',  // Font Awesome icon
            'url' => [              // URL object
                'plugin' => false,
                'controller' => 'Dashboard',
                'action' => 'index'
            ],
         ],
        'examples' => [             // second menu item
            'title' => 'Examples',
            'hideForRoles' => [ 	// disable rendering for certain groups
                User::ROLE_USER 	// of users
            ],
            'children' => [         // field 'children'. Note that this item
                [                   // does not have an URL object.
                    'title' => 'foo',  // first child item (menu sub-item)
                    'url' => [
                        'plugin' => false,
                        'controller' => 'Examples',
                        'action' => 'actionFoo'
                    ]
                ],
                [
                    'title' => 'bar',  // second child item (menu sub-item)
                    'url' => [
                        'plugin' => false,
                        'controller' => 'Examples',
                        'action' => 'actionBar'
                    ]
                ],
                // further sub-items for menu item 'examples'
            ]
        ],
        // further menu items

```

Create a PDF using CakePHP Views
--------------------------------

[](#create-a-pdf-using-cakephp-views)

CkTools includes a simple wrapper for the [MPDF library](http://www.mpdf1.com/mpdf/index.php). For detailed instructions on how to use it, see the github repository here:

#### Usage

[](#usage-1)

Here's an example use in a Cake Controller but you can use this feature wherever you want. See `/cake-cktools/src/Lib/PdfGenerator.php` for a closer look at the functionalities used.

```
use CkTools\Lib\PdfGenerator;

$pdfGenerator = new PdfGenerator([
    'pdfSourceFile' => '/path/to/your/template.pdf' // optional
]);
$pdfGenerator->render('my_element', [
    'viewVars' => [
        'foo' => 'bar'
    ],
    'target' => PdfGenerator::TARGET_BROWSER,
    'cssFile' => '/path/to/your/styles.css',
    'cssStyles' => 'body { font-size: 20px }'
]);

```

In your Cake View file you can use the passed viewVars and the `$mpdf` variable for manipulating the PDF.

```

```

Sort table fields with SortableBehavior
---------------------------------------

[](#sort-table-fields-with-sortablebehavior)

CkTools provides a behavior that allows manipulation of the (displayed) order of the records of a table. If you change the position of one field, the behavior will automatically change all the other fields' positions accordingly. To manipulate the positions you can use an ordinary form field or for example the Cake Frontend Bridge to enable JavaScript-based drag-and-drop interaction in the browser UI.

Strict Passwords with StrictPasswordBehavior
--------------------------------------------

[](#strict-passwords-with-strictpasswordbehavior)

Activate the strict password requirements by setting the StrictPasswordBehavior in UsersTable; default Configuration is set in this example

$this-&gt;addBehavior('CkTools.StrictPassword', \[ // minimal password length 'minPasswordLength' =&gt; 10, // fistname and surname are not allowed in password (case insensitive) 'noUserName' =&gt; true, // at least one special char is needed in password 'specialChars' =&gt; true, // at least one char in upper case is needed in password 'upperCase' =&gt; true, // at least one char in lower case is needed in password 'lowerCase' =&gt; true, // at least one numeric value is needed in password 'numericValue' =&gt; true, // reuse of old passwords is not allowed: number of old passwords to preserve 'oldPasswordCount' =&gt; 4 \]);

#### Usage

[](#usage-2)

Add the SortableBehavior to the Table you want to use it in:

```
public function initialize(array $config)
{
	$this->addBehavior('CkTools.Sortable', [
	    'sortField' => 'sort',
	    'columnScope' => ['mediatype_id'],
	    'defaultOrder' => ['sort' => 'ASC']
	]);
}

```

The current 'position' of the record will be stored as an integer in the field `'sort'`. You need to have this field in your Model. If it's not called 'sort', you can configure the behavior accordingly here.

Here's what the table field you wish to allow sorting by could look like in CakePHP schema.

```
'sort' => ['type' => 'integer', 'length' => 6, 'unsigned' => false, 'null' => false, 'default' => null, 'comment' => '', 'precision' => null, 'autoIncrement' => null],

```

Manipulate database records with TableUtilitiesTrait
----------------------------------------------------

[](#manipulate-database-records-with-tableutilitiestrait)

The TableUtilitiesTrait contains an action that allows for manually updating the value of a field in a table. Using `updateField()` bypasses cake validation and patching of the object. The given value is directly written to the database via a SQL query.

#### Setting up a Model

[](#setting-up-a-model)

Add the Trait in **`YourTable.php`**:

```
