CakePHP 4 How To Save Form Data in Database Table

Reading Time: 7 minutes
3,049 Views

Inside this article we will see CakePHP 4 How To Save Form Data in Database Table. This tutorial will help you to understand about saving form data to database using CakePHP forms. We will see the classified information about Processing form data including client side validation as well.

In any application where we have forms to take user data we add form validations. So in this case we will create a simple form with few form input fields like name, email, mobile_no. We will see add client side validation as well.

Learn More –

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.

Create Database

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE mydatabase;

Successfully, we have created a database.

Database Connection

Open app_local.php file from /config folder. Search for Datasources. Go to default array of it.

You can add your connection details here to connect with your database. It will be like this –

//...

'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' => 'sample@123',

            'database' => 'mydatabase',
            /*
             * 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),
        ],
  
     //...

//...

You can pass host, username, password and database.

Successfully, you are now connected with the database.

Create Migrations

Open project into terminal run this migration command.

$ bin/cake bake migration CreateEmployees

Above command will create a file 20220317154654_CreateEmployees.php inside /config/Migrations folder.

Open 20220317154654_CreateEmployees.php and write this following into it. It will create employees table into database.

<?php
declare(strict_types=1);

use Migrations\AbstractMigration;

class CreateEmployees extends AbstractMigration
{
    public function change()
    {
        $table = $this->table('employees');

        $table->addColumn("name", "string", [
            "limit" => 50,
            "null" => false
        ]);

        $table->addColumn("email", "string", [
            "limit" => 50,
            "null" => false
        ]);

        $table->addColumn("mobile_no", "string", [
            "limit" => 20,
            "null" => false
        ]);

        $table->create();
    }
}

Run Migration

Run migration to create a database table.

$ bin/cake migrations migrate

Table: employees

Create Model & Entity

Open project into terminal run this bake console command.

$ bin/cake bake model Employees --no-validation --no-rules

It will create a Model file with Entity class as well.

Open EmployeesTable.php from /src/Model/Table folder and write this following code into it.

<?php
declare(strict_types=1);

namespace App\Model\Table;

use Cake\ORM\Table;

class EmployeesTable extends Table
{
    public function initialize(array $config): void
    {
        parent::initialize($config);

        $this->setTable('employees');
        $this->setPrimaryKey('id');
    }
}

Open Employee.php from /src/Model/Entity folder and write this following code into it.

<?php
declare(strict_types=1);

namespace App\Model\Entity;

use Cake\ORM\Entity;

class Employee extends Entity
{
    protected $_accessible = [
        'name' => true,
        'email' => true,
        'mobile_no' => true,
    ];
}

Create Controller

Again, back to terminal and this bake console command to create controller class.

$ bin/cake bake controller Employees --no-actions

It will create a controller class EmployeesController.php inside /src/Controller folder. Open and write this following code into it.

<?php

declare(strict_types=1);

namespace App\Controller;

class EmployeesController extends AppController
{
    public function initialize(): void
    {
        parent::initialize();

        $this->loadModel("Employees");
    }

    public function addEmployee()
    {
        $employeeEntity = $this->Employees->newEmptyEntity();

        if ($this->request->is("post")) {

            $formData = $this->request->getData();

            $employeeEntity = $this->Employees->patchEntity($employeeEntity, $formData);

            if ($this->Employees->save($employeeEntity)) {

                $this->Flash->success("Employeed has been created successfully");
            } else {

                $this->Flash->error("Failed to create employee");
            }
        }

        $this->set(compact("employeeEntity"));
    }
}

Create Template File

Create a folder with controller name i.e Employees inside /templates folder. Create a file add_employee.php into /templates/Employees folder.

In this template file we will create Add employee form. Also we are handling validation errors and displaying error messages into it.

<!DOCTYPE html>
<html lang="en">

<head>
    <title>CakePHP 4 How To Save Form Data in Database Table</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

    <style>
        #frm-add-employee label.error {
            color: red;
        }
    </style>
</head>

<body>

    <div class="container">
        <h4>CakePHP 4 How To Save Form Data in Database Table</h4>
        <div class="panel panel-primary">
            <div class="panel-heading">Employee Form</div>
            <div class="panel-body">
                <?= $this->Flash->render() ?>
                <?= $this->Form->create($employeeEntity, ["class" => "form-horizontal", "id" => "frm-add-employee"]) ?>
                <div class="form-group">
                    <label class="control-label col-sm-2" for="name">Name:</label>
                    <div class="col-sm-10">
                        <input type="name" class="form-control" id="name" name="name" required placeholder="Enter 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" required placeholder="Enter email">
                    </div>
                </div>
                <div class="form-group">
                    <label class="control-label col-sm-2" for="mobile_no">Mobile:</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="mobile_no" name="mobile_no" required placeholder="Enter number">
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-offset-2 col-sm-10">
                        <button type="submit" class="btn btn-success">Submit</button>
                    </div>
                </div>
                <?= $this->Form->end() ?>
            </div>
        </div>
    </div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/jquery.validate.min.js"></script>
    <script>
        $(function() {
            $("#frm-add-employee").validate();
        });
    </script>

</body>

</html>
      

Disable CSRF Token

When we submit a cakephp form, it needs a CSRF token should be submitted with form submission request.

We are not interested to send CSRF token with form data. To disable it, Open Application.php from /src folder.

Remove these lines of code from middleware() method.

->add(new CsrfProtectionMiddleware([
    'httponly' => true,
]))

Create Route

Open routes.php file from /config folder. Add this route into it.

//...

$routes->connect(
    '/add-employee',
    ['controller' => 'Employees', 'action' => 'addEmployee']
);

//...

Application Testing

To execute start development server.

$ bin/cake server

URL: http://localhost:8765/add-employee

When we submit form without passing any value to it.

After passing values within input fields,

We hope this article helped you to learn CakePHP 4 How To Save Form Data in Database Table 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.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more