post by Alberto on Jul 4, 2023

Hi,

I am trying to made a custom Model in codeigniter 4, I would like to have some example.

In the Documentation page, there is only for codeigniter 3.

Can I get an example for codeigniter 4 anywhere?

Really thanks for your support.

Alberto

12 days later

post by digamarshall on Jul 17, 2023

I am looking for exactly the same. It is a pity there is no example for CI 4 in the documentation

post by Alberto on Jul 18, 2023

post by rrit on Jul 19, 2023

Sorry, but it was off topic (I misread it).

If it was helpful for anybody, I restore it here now :wink:

How it works in my project:

  • install CI4 via composer
  • install GCE 3 via composer (see manual)
  • configure app/Config/GroceryCrudEnterprise.php
  • configure db connection in CI4

Then put

in app/Libraries/ the file GroceryCrudStarter.php:

<?php

namespace App\Libraries;

use GroceryCrud\Core\GroceryCrud;

class GroceryCrudStarter extends GroceryCrud
{
    public function __construct()
    {
        $config = (new \Config\GroceryCrudEnterprise())->getDefaultConfig();
        parent::__construct($config, $this->getDbData());
    }

    private function getDbData()
    {
        $db = (new \Config\Database())->default;
        return [
            'adapter' => [
            'driver' => 'Pdo_Mysql',
            'host'     => $db['hostname'],
            'database' => $db['database'],
            'username' => $db['username'],
            'password' => $db['password'],
            'charset' => 'utf8'
            ]
        ];
    }
}

in app/Controllers/ the file ExampleController.php:

<?php

namespace App\Controllers;

use App\Libraries\GroceryCrudStarter;

class ExampleController extends BaseController
{
    public function manage()
    {
        $crud = new GroceryCrudStarter();
        $crud->unsetDeleteMultiple();
        $crud->setTable('example');
        $crud->setSubject('Example', 'Examples');
        $crud->columns(['name', 'info', 'updated_at', 'created_at']);
        $crud->fields(['name', 'info']);
        $crud->uniqueFields(['name']);

        $crud->setRule('name', 'required');

        $output = $crud->render();

        if ($output->isJSONResponse) {
            header('Content-Type: application/json; charset=utf-8');
            echo $output->output;
            exit;
        }

        return view('crud_general', (array)$output);
    }
}

(the table “example” must exists in db):


CREATE TABLE `example` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `info` varchar(200) DEFAULT NULL,
  `updated_at` datetime DEFAULT current_timestamp() ON UPDATE current_timestamp(),
  `created_at` datetime DEFAULT current_timestamp(),
  PRIMARY KEY (`id`),
  UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;

in app/Models/ the file ExampleModel.php:

<?php

namespace App\Models;

use CodeIgniter\Model;

class ExampleModel extends Model
{
    protected $DBGroup          = 'default';
    protected $table            = 'example';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $insertID         = 0;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;
    protected $protectFields    = true;
    protected $allowedFields    = ['name', 'info'];

    // Dates
    protected $useTimestamps = false;
    protected $dateFormat    = 'datetime';
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';
    //protected $deletedField  = 'deleted_at';

    // Validation
    protected $validationRules      = [];
    protected $validationMessages   = [];
    protected $skipValidation       = false;
    protected $cleanValidationRules = true;

    // Callbacks
    protected $allowCallbacks = true;
    protected $beforeInsert   = [];
    protected $afterInsert    = [];
    protected $beforeUpdate   = [];
    protected $afterUpdate    = [];
    protected $beforeFind     = [];
    protected $afterFind      = [];
    protected $beforeDelete   = [];
    protected $afterDelete    = [];
}

in app/Views/ the file crud_general.php:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
<?php
foreach ($css_files as $file) : ?>
    <link type="text/css" rel="stylesheet" href="<?php echo $file; ?>" />
<?php endforeach; ?>
<link type="text/css" rel="stylesheet" href="<?php echo base_url('assets/common/css/grocery_crud_form.css') ?>">
</head>
<body>
    <div>
          <a href='<?php echo site_url('example/manage')?>'>example</a>
    </div>
    <div style='height:20px;'></div>  
    <div style="padding: 10px">
        <?php echo $output; ?>
    </div>
    <?php foreach ($js_files as $file) : ?>
        <script src="<?php echo $file; ?>"></script>
    <?php endforeach; ?>
</body>
</html>

NOW,
you call in your Browser the URL http://your-webadress/example/manage
(f.ex. http://localhost:8080/example/manage, if you use the internal CI4 webserver with “sparc serve” for development)
and… vuala!

1 / 4
Jul 2023