CakePHP 4 Form Validation with Example

Reading Time: 10 minutes
5,852 Views

Validating a form is common to every application. Inside this article we will see CakePHP 4 form validation. This will be step by step guide with example.

We will set an application, inside that we will create controller, model and a view file.

Let’s get started.


CakePHP 4 Installation

To create a CakePHP project, run this command into your shell or terminal. Make sure composer should be installed in your system.

$ composer create-project --prefer-dist cakephp/app:~4.0 mycakephp

Above command will creates a project with the name called mycakephp.


Settings up Database & Application Connectivity

We need to create a database. Database table is going to store form data. We have created a database in PhpMyAdmin with the name of cakephp4_form. You can choose your own custom name of database.

Either you can use Manual tool of MySQL or you can create via MySQL command.

CREATE DATABASE cakephp4_form;

So, now we have a database. We need to create a table to store data. Let’s create a table with the name of tbl_students. This table again we can create via Manual interface of creating table or we can run a command to create it.

Create Table tbl_students –

CREATE TABLE IF NOT EXISTS tbl_students (
  id int(10) unsigned NOT NULL AUTO_INCREMENT,
  name varchar(120) COLLATE utf8_unicode_ci NOT NULL,
  email varchar(120) COLLATE utf8_unicode_ci NOT NULL,
  phone_no varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

In table tbl_students we have columns as id, name, email & phone_no.

After creating database and table, now we need to configure and connect database with CakePHP 4 application.

Go to Project setup >> config (directory) >> app_local.php (file). Open this file to connect database.

'Datasources' => [
    'default' => [
      'host' => 'localhost',
      /*
               * CakePHP will use the default DB port based on the driver selected
               * MySQL on MAMP uses port 8889, MAMP users will want to uncomment
               * the following line and set the port accordingly
               */
      //'port' => 'non_standard_port_number',

      'username' => 'root',
      'password' => 'root',

      'database' => 'cakephp4_form',
      /**
               * If not using the default 'public' schema with the PostgreSQL driver
               * set it here.
               */
      //'schema' => 'myapp',

      /**
               * You can use a DSN string to set the entire configuration
               */
      'url' => env('DATABASE_URL', null),
    ],
  ]

Successfully, we have now configured database connection with CakePHP 4 application.


Configuring Application Route

We need to create now application routes.

Go to Project Setup >> config (directory) >> routes.php (file). Open this file. 

$routes->scope('/', function (RouteBuilder $builder) {

    // Student Route
    $builder->connect('/add-student', ['controller' => 'Students', 'action' => 'addStudent']);
  
});

Inside this route configuration, we can see we have created route for add student. Next, we need to create Controller. Because the actions for submitting form data we will do those stuff there.


Application Models & Entity Settings

We need to configure Model & Entity. Model contains the information of Table where we will do crud operations. Entity define the columns for value assignment.

To create a model –

Go to Project Setup >> src (directory) >> Model (directory) >> Table (directory).

Inside Table directory, create a file StudentsTable.php. Inside this file copy and paste this given code.

<?php

namespace App\Model\Table;

use Cake\ORM\Table;
use Cake\Validation\Validator;

class StudentsTable extends Table
{
    public function initialize(array $config): void
    {
        $this->setTable("tbl_students");
    }

    public function validationDefault(Validator $validator): Validator
    {
        // adding model validation for fields
        $validator
            ->requirePresence("name")
            ->notEmpty("name", "Name field value is needed")
            ->minLength("name", 10, "Name field should have minimum characters equals to 10")
            ->maxLength("name", 15, "Name field should have max chars equals to 15")
            ->requirePresence("email")
            ->notEmpty("email", "Email field value is needed")
            ->add("email", [
                "valid_email" => [
                    "rule" => ["email"],
                    "message" => "Email Address is not valid",
                ],
                "min_length" => [
                    "rule" => ["minLength", 10],
                    "message" => "Invalid min length",
                ],
                "max_length" => [
                    "rule" => ["maxLength", 25],
                    "message" => "Invalid max length",
                ],
            ])
            ->requirePresence("phone_no")
            ->numeric("phone_no");
        return $validator;
    }
}

Next, we need to set Entity for Table definition about value assignments.

To Create an Entity –

Go to Project Setup >> src (directory) >> Model (directory) >> Entity (directory).

Inside Table directory, create a file Student.php. Inside this file copy and paste this given code.

<?php

namespace App\Model\Entity;

use Cake\ORM\Entity;

class Student extends Entity
{
    protected $_accessible = [
        "name" => true,
        "email" => true,
        "phone_no" => true
    ];
}

Create Controller & It’s Methods

Controller is the file which controls the application flow. Inside this controller file we will create few methods.

To Create a Controller –

Go to Project Setup >> src (directory) >> Controller (directory)

<?php

namespace App\Controller;

use App\Controller\AppController;

class StudentsController extends AppController
{
    public function initialize(): void
    {
        parent::initialize();
        $this->loadModel("Students");
    }

    public function addStudent()
    {
        $student = $this->Students->newEmptyEntity();

        if ($this->request->is('post')) {
            $student = $this->Students->patchEntity($student, $this->request->getData());
          
            // when we submit this form via POST request type, automatically model
            // will take care of all validations what we have implemented in Model file.
            // Only you need to copy the whole code from here and apply to your project.
          
            if ($this->Students->save($student)) {
                $this->Flash->success(__('The student has been saved.'));

                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('The student could not be saved. Please, try again.'));
        }

        $this->set(compact("student"));
        $this->set("title", "Add Student");
    }
}

Creating View File

To create view files we will create a folder with the name of controller in /templates directory.

Folder name – /templates/Students. Students is the name of the controller. We will keep all views inside this folder –

Source code /templates/Student/add_student.php

<div class="panel panel-primary">

   <div class="panel-heading">
        Add Student
   </div>
    <div class="panel-body">
        <?=
          $this->Form->create($student, [
              "class" => "form-horizontal",
              "id" => "frm-add-student",
          ])
        ?>
        <div class="form-group">
            <label class="control-label col-sm-2">Name:</label>
            <div class="col-sm-10">
                <input type="text" class="form-control" id="name" name="name" placeholder="Enter name">
                            <?php
                              if ($this->Form->isFieldError('name')) {
                                  echo $this->Form->error('name');
                              }
                            ?>
            </div>
        </div>
       <div class="form-group">
            <label class="control-label col-sm-2" for="email">Email:</label>
            <div class="col-sm-10">
                <input type="email" class="form-control" id="email" name="email" placeholder="Enter email">
                <?php
                  if ($this->Form->isFieldError('email')) {
                      echo $this->Form->error('email');
                  }
                ?>
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-sm-2">Phone no:</label>
            <div class="col-sm-10">
                <input type="text" class="form-control" id="phone_no" name="phone_no" placeholder="Enter phone no">
                <?php
                  if ($this->Form->isFieldError('phone_no')) {
                      echo $this->Form->error('phone_no');
                  }
                ?>
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
                <button type="submit" class="btn btn-default">Submit</button>
            </div>
        </div>
        <?=$this->Form->end()?>
    </div>
</div>
  • $this->Form->create() & $this->Form->end() is of Form helper methods.
  • if ($this->Form->isFieldError(‘name’)) {} This code checking is any error of field “name”. If yes then we have used $this->Form->error(‘name’) to print error message

Test Application

As we have created all the needed file. To run application, back to browser and type project url into it.

Open project in terminal and start development server

$ bin/cake server -p 8765

This is the Form when you open the route http://localhost:8765/add-student

CakePHP 4 Form Layout vallidation
CakePHP 4 Form Layout

When we submit this form without filling any data then we should get errors. Still we don’t have used any CSS that’s why you will see all errors in black colored but make it some CSS for those errors.

CakePHP 4 Form Validation
CakePHP 4 Form Validation

More about validation and rules you can go to official documentation of CakePHP from validation rules here.

We hope this article helped you to learn CakePHP 4 Form Validation in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

2 thoughts on “CakePHP 4 Form Validation with Example”

Comments are closed.