Category Archives: cakephp3

Cakephp3 make a field unique

23666To do this, simple open your table model file and add the following;

public function validationDefault(Validator $validator)
{

//the below code makes the field "title" validate as unique
$validator
->requirePresence('title', 'create')
->add('title', 'unique', ['rule' => 'validateUnique', 'provider' => 'table','message'=>'Error: Title already exists.'])
->notEmpty('title');

return $validator;
}

 Manual:
http://book.cakephp.org/3.0/en/core-libraries/validation.html

Cakephp3 How to pass a variable to an element

cake-logoSometimes its very handy to pass a variable to an Element in Cakephp3.

This allows you to customize the element if needed;
To do so simply;

in your view file;

echo $this->element('helpbox', [
    "helptext" => "Oh, this text is very helpful."
]);

What does it do?
This will load the element called “helpbox” and pass the value “Oh, this text is very helpful.” to the variable called “helptext” in the element.

CakePHP3 Book:
http://book.cakephp.org/3.0/en/views.html#passing-variables-into-an-element 

How to add REST features to your Cakephp 3 App

23666To add REST features to your CakePHP 3 you simply need to add two lines of code to your controller;

This will allow any action in the controller to be viewed as JSON or XML .

To view your action index as JSON simply;

http://localhost/mycakeapp/mycontroller/index.json

Rest Examples:
http://localhost/mycakeapp/mycontroller/view/1.json

http://localhost/mycakeapp/mycontroller/view/1.xml

 

public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
}

 

Then in routes.php file /config/routes.php add;

Router::extensions(['json', 'xml']); //ensure this is before the below line.
Router::scope('/', function (RouteBuilder $routes) {

More info from the manual:
http://book.cakephp.org/3.0/en/development/routing.html#resource-routes