CakePHP 4 Form Model Validation with Example Part-6

Webs Codex
4 min readOct 10, 2020

In this post we will see Form Validation using CakePHP 4 Model, Validation is a common to us every application. This will be step by step with example.

Now we will see two Form validation one is Users Table and second is Posts Table. there multiple input like email ,password, username and file validation using CakePHP 4 Model validation.

If don’t know, how to install CakePHP 4 in our local system.

You can see also

CakePHP 4 Tutorial Part 2: Add, Edit and Delete Operations

CakePHP 4 Tutorial Part 3: Working with Elements and Default Layout

A Complete Login and Authentication Application Tutorial for CakePHP 4 Part-4

How to Upload File in CakePHP 4, Part-5

Application Models & Entity Settings

In Model src/Model/Table/PostsTable.php to validate form and insert date time value in created and updated using addBehavior function with Timestamp. validate file extension and required.

src/Model/Table/PostsTable.php

<?phpnamespace App\Model\Table;
use Cake\ORM\Table;
use Cake\Validation\Validator;
class PostsTable extends Table
{
public function initialize(array $config): void
{
$this->addBehavior('Timestamp', [
'events' => [
'Model.beforeSave' => [
'created' => 'new',
'updated' => 'always'
]
]
]);
}
public function validationDefault(Validator $validator): Validator { $validator
->notEmptyString('title')
->notEmptyString('description')
->requirePresence('post_image', 'create')
->notEmptyString('post_image')
->add('post_image', [
[ 'rule' => ['extension',['jpeg', 'png', 'jpg']], // default ['gif', ]
'message' => __('Only jpg jpeg and png files are allowed.')],
['rule' => ['fileSize', '<=', '1024'],
'message' => __('Image must be less than 1MB')]
]
);
return $validator;
}
}

In Model src/Model/Table/UsersTable.php to validate form and insert date time value in created and updated using addBehavior function with Timestamp. validate email, password and name required unique and maximum and minimum password.

src/Model/Table/UsersTable.php

<?phpnamespace App\Model\Table;
use Cake\ORM\Table;
use Cake\Validation\Validator;
use Cake\ORM\Rule\IsUnique;
use Cake\ORM\RulesChecker;
class UsersTable extends Table
{
public function initialize(array $config): void
{
$this->addBehavior('Timestamp', [
'events' => [
'Model.beforeSave' => [
'created' => 'new',
'updated' => 'always'
]
]
]);
}
public function buildRules(RulesChecker $rules): RulesChecker {
$rules->add($rules->isUnique(['email'], 'Email is already exists'));
$rules->add($rules->isUnique(['username'], 'Usrename is already exists'));
return $rules;
}
public function validationDefault(Validator $validator): Validator { $validator
->notEmptyString('name')
->notEmptyString('email')
->requirePresence('email')
->add('email', 'validFormat', [
'rule' => 'email',
'message' => 'Email must be valid'
])
->notEmptyString('username')
->requirePresence('password')
->notEmptyString('password')
->add('password', [
'minLength' => [
'rule' => ['minLength', 6],
'last' => true,
'message' => 'Password minmum 6 digits'
],
'maxLength' => [
'rule' => ['maxLength', 10],
'message' => 'Password minmum 10 digits'
]
]);
return $validator;
}
}

There are two Users and Posts Table validation using CakePHP 4 Model.

src/Model/Entity/User.php

<?php
namespace App\Model\Entity;
use Authentication\PasswordHasher\DefaultPasswordHasher; // Add this line
use Cake\ORM\Entity;
class User extends Entity
{
// Code from bake.
// Add this method
protected function _setPassword(string $password) : ?string
{
if (strlen($password) > 0) {
return (new DefaultPasswordHasher())->hash($password);
}
}
}

Create Controller and It’s Methods

In this post we will use the src/controller/UsersController.php controller to create a add method to Insert data in Users Table in database.

src/Controller/UsersController.php

<?php
// In src/Controller/UsersController.php
namespace App\Controller;
use App\Controller\AppController;
use Cake\Event\EventInterface;
use Cake\Datasource\FactoryLocator;
class UsersController extends AppController{ public $usersTableObj; public function beforefilter(EventInterface $event){
parent::beforefilter($event);
$this->usersTableObj = FactoryLocator::get('Table')->get('Users');
}
public function add(){
$userEnt = $this->usersTableObj->newEmptyEntity();
if ($this->request->is('post')) {
$userPost = $this->request->getData();
$users = $this->usersTableObj->patchEntity($userEnt, $userPost);
if ($this->usersTableObj->save($userEnt)) {
$this->Flash->success(__('Your user has been saved.'));
return $this->redirect(['controller'=>'Users','action' => 'index']);
}else{
$this->Flash->error(__('Unable to add your user.'));
return $this->redirect(['controller'=>'Users','action' => 'add']);
}
}
$this->set(compact('userEnt', $userEnt));
}
}

Create View File

Templates/Users/add.php view is responsible for creating the Insert Form.

Templates/Users/add.php

<div class="text-center" style="margin-top: 50px;">
<h4>User Registration Form</h4>
</div>
<div class="container">
<div class="row">
<div class="col-sm-3"></div>
<div class="col-sm-6">
<?php echo $this->Form->create($userEnt, ['name'=>'add_users', 'class'=>'was-validated']) ?>
<div class="form-group">
<?php echo $this->Form->control('name', ['type'=>'text', 'class'=>'form-control','placeholder'=>'Enter name','required'=>true]);?>
</div>
<div class="form-group">
<?php echo $this->Form->control('email', ['type'=>'email', 'class'=>'form-control','placeholder'=>'Enter email','required'=>true]);?>
</div>
<div class="form-group">
<?php echo $this->Form->control('username', ['type'=>'text', 'class'=>'form-control','placeholder'=>'Enter username','required'=>true]);?>
</div>
<div class="form-group">
<?php echo $this->Form->control('password', ['type'=>'password', 'class'=>'form-control','placeholder'=>'Enter password','required'=>true]);?>
</div>
<button type="submit" class="btn btn-primary" style="float: right;">Sign Up</button>
<?php echo $this->Form->end() ?>
</div>
</div>
</div>

CakePHP 4 Form Model Validation with Example Part-6

You can also see client side validation using Jquery Plugin Form Validation

Originally published at https://www.webscodex.com on October 10, 2020.

--

--

Webs Codex

Webs Codex is programming and web development blog