Codeigniter 4 Form Submit Tutorial Example

Throughtout this Codeigniter 4 Form Submit Tutorial we’ll show you how to integrate form submit codeigniter 4 application step by step easy way. We will use the get and post methods to submit a form. The get method will show the form while post method will use for submit the data in request and save the data in database.

Form Submit Codeigniter 4 Example

Here’s a step-by-step guide to create and handle a form, including storing data into a database:

Step 1 – Configure Database Connection

First, you need to set up your database connection in the application/config/database.php file:

public $default = [
'DSN' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => 'root',
'database' => 'demo',
'DBDriver' => 'MySQLi',
'DBPrefix' => '',
'pConnect' => false,
'DBDebug' => (ENVIRONMENT !== 'development'),
'cacheOn' => false,
'cacheDir' => '',
'charset' => 'utf8',
'DBCollat' => 'utf8_general_ci',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port' => 3306,
];

Step 2 – Create the Form View

Navigate to the app/Views/ directory and create a file named form.php. Add the following HTML and PHP code for the form in form.php:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>CodeIgniter 4 Form Submission Example</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<style>
.container {
max-width: 550px;
}
</style>
</head>
<body>
<div class="container mt-5">
<?php $validation = \Config\Services::validation(); ?>

<form action="<?= base_url('/FormController/store') ?>" method="post">
<div class="form-group">
<label for="name">Name</label>
<input type="text" id="name" name="name" class="form-control">
<!-- Error -->
<?php if ($validation->getError('name')): ?>
<div class='alert alert-danger mt-2'>
<?= $validation->getError('name'); ?>
</div>
<?php endif; ?>
</div>

<div class="form-group">
<label for="email">Email</label>
<input type="text" id="email" name="email" class="form-control">
<!-- Error -->
<?php if ($validation->getError('email')): ?>
<div class='alert alert-danger mt-2'>
<?= $validation->getError('email'); ?>
</div>
<?php endif; ?>
</div>

<div class="form-group">
<label for="phone">Phone</label>
<input type="text" id="phone" name="phone" class="form-control">
<!-- Error -->
<?php if ($validation->getError('phone')): ?>
<div class='alert alert-danger mt-2'>
<?= $validation->getError('phone'); ?>
</div>
<?php endif; ?>
</div>

<div class="form-group">
<button type="submit" class="btn btn-primary btn-block">Submit</button>
</div>
</form>
</div>
</body>
</html>

Step 3 – Create the Model

Create a model file named FormModel.php in the app/Models/ directory. This model will handle the database operations:

<?php 
namespace App\Models;
use CodeIgniter\Model;

class FormModel extends Model
{
protected $table = 'users';
protected $primaryKey = 'id';
protected $allowedFields = ['name', 'email', 'phone'];
}

Step 4 – Create the Controller

Create a controller named FormController.php in the app/Controllers/ directory. Define methods for displaying the form and handling form submissions:

<?php 
namespace App\Controllers;
use App\Models\FormModel;
use CodeIgniter\Controller;

class FormController extends Controller
{
public function index() {
helper(['form']);
return view('form');
}

public function store() {
helper(['form']);
$validationRules = [
'name' => 'required|min_length[3]',
'email' => 'required|valid_email',
'phone' => 'required|numeric|max_length[10]'
];

if ($this->validate($validationRules)) {
$formModel = new FormModel();
$formData = [
'name' => $this->request->getVar('name'),
'email' => $this->request->getVar('email'),
'phone' => $this->request->getVar('phone'),
];
$formModel->save($formData);
return redirect()->to('/submit-form');
} else {
$data['validation'] = $this->validator;
return view('submit-form', $data);
}
}
}

Step 5 – Define Routes

Update the app/Config/Routes.php file to set up the routes for the form handling:

$routes->get('submit-form', 'FormController::index');
$routes->match(['get', 'post'], 'FormController/store', 'FormController::store');

Step 6 – Test the Application

Open your browser and visit http://localhost/project_name/index.php/submit-form to test the form functionality.