Code your dreams into reality.
Every line of code is a step towards a better future.
Embrace the bugs, they make you a better debugger.

CodeIgniter 4 Form Submit Tutorial

Last Updated on July 6, 2024 by

In a CodeIgniter 4 application, displaying and submitting a form can be done using two methods GET and Post.

Let’s start by creating a form and submitting it to a controller method to insert data into the database:

Step 1 – Set Up Database Connection

Edit application/config/database.php file, and set up your database connection details in it:


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 Form View

Go to app/Views/ directory and create a form view named form.php in it, and create form in form.php file:

<!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 Submit Example - ItcodStuff.com</title>
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/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="<?php echo base_url(); ?>/FormController/store" method="post">
      <div class="form-group">
        <label>Name</label>
        <input type="text" name="name" class="form-control">

        <!-- Error -->
        <?php if($validation->getError('name')) {?>
            <div class='alert alert-danger mt-2'>
              <?= $error = $validation->getError('name'); ?>
            </div>
        <?php }?>
      </div>
       

      <div class="form-group">
        <label>Email</label>
        <input type="text" name="email" class="form-control">

        <!-- Error -->
        <?php if($validation->getError('email')) {?>
            <div class='alert alert-danger mt-2'>
              <?= $error = $validation->getError('email'); ?>
            </div>
        <?php }?>
      </div>

      <div class="form-group">
        <label>Phone</label>
        <input type="text" name="phone" class="form-control">

        <!-- Error -->
        <?php if($validation->getError('phone')) {?>
            <div class='alert alert-danger mt-2'>
              <?= $error = $validation->getError('phone'); ?>
            </div>
        <?php }?>
      </div>

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

  </div>
</body>

</html>

Step 3 – Create Model

Go to app/Models/ and create a model file named FormModel.php that is used to query the database table:

<?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 Controller and Method

Create a controller file called FromController.php in the app/Controllers/ directory, and create methods to handle form display and submission through it:

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

class FormController extends Controller
{

    public function index() {
        helper(['form']);
        $data = [];
        return view('form');
    }
 
    public function store() {
        helper(['form']);
        $rules = [
            'name' => 'required|min_length[3]',
            'email' => 'required|valid_email',
            'phone' => 'required|numeric|max_length[10]'
        ];
          
        if($this->validate($rules)){
            $formModel = new FormModel();

            $data = [
                'name' => $this->request->getVar('name'),
                'email'  => $this->request->getVar('email'),
                'phone'  => $this->request->getVar('phone'),
            ];

            $formModel->save($data);

            return redirect()->to('/submit-form');
        }else{
            $data['validation'] = $this->validator;
            echo view('submit-form', $data);
        }        
    }

}

Step 5 – Define Routes

Edit app/Config/Routes.php file, and define routes in it to handle form submission requests:

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

Step 6 – Test Application

Open browser and type http://localhost/project_name/index.php/submit-form url in it to test this application.

Leave a Comment