Notice
Recent Posts
Recent Comments
Link
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
Archives
Today
Total
관리 메뉴

미디어 온 연구실

예제1. CodeIgniter 4 입력 폼 본문

예제로 배우는 코드이그나이터4

예제1. CodeIgniter 4 입력 폼

미디어ON 2021. 7. 6. 01:27

 

1 단계 : Codeigniter 4 새 프로젝트 만들기

새 프로젝트를 만들기 위해 Composer를 사용할 것입니다. Composer를 사용하여 Codeigniter 4 프로젝트를 만들 수도 있습니다. 따라서 터미널을 열고 아래 명령을 누르십시오.

composer create-project codeigniter4/appstarter form-validation

 

2 단계 : 테이블을 사용하여 데이터베이스 생성

MySQL에서 새 데이터베이스를 만듭니다. 아래 명령을 복사여 데이터베이스를 만들 수 있습니다.

CREATE DATABASE ci4_form;

데이터베이스를 생성 한 후 Codeigniter 프로젝트를 편집기로 엽니 다. 그런 다음 아래 단계를 따르십시오.
env 파일의 이름을 .env로 바꿉니다. 환경을 프로덕션에서 개발로 변경하십시오. 이제 데이터베이스 섹션에서 기본 데이터베이스 구성을 찾을 수 있습니다.

#--------------------------------------------------------------------
# APP
#--------------------------------------------------------------------

app.baseURL = 'http://mydomain'
app.domain = 'mydomain'
# app.forceGlobalSecureRequests = false

#--------------------------------------------------------------------
# DATABASE
#--------------------------------------------------------------------

database.default.hostname = localhost
database.default.database = ci4_form
database.default.username = database username
database.default.password = database password
database.default.DBDriver = MySQLi

 

3 단계 : 테이블 마이그레이션 생성

다음 단계에서는 users 테이블에 대한 마이그레이션을 생성합니다. 사실 기본 사용자 등록 양식을 작성하겠습니다. 그런 다음 양식 유효성 검사를 구현합니다.
Codeigniter 4에서 테이블 스키마에 대한 마이그레이션을 생성 할 수 있습니다. 지난 Codeigniter 4 자습서에서 이미 보여 드렸습니다. 따라서 프로젝트 내에서 터미널을 열고 아래 명령을 입력하세요.

php spark make:migration users --table


여기에 양식 유효성 검사에 필요한 필드를 추가했습니다. 필요한 경우 더 많은 필드를 추가 할 수 있습니다. 양식 유효성 검사에 대한 기본 개념을 보여 드리겠습니다.

timestamp_Users.php

<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class Users extends Migration
{
    public function up()
    {
        $this->forge->addField([
            'id' => [
                'type' => 'INT',
                'auto_increment' => true
            ],
            'name' => [
                'type' => 'VARCHAR',
                'constraint' => '30'
            ],
            'email' => [
                'type' => 'VARCHAR',
                'constraint' => '50'
            ],
            'password' => [
                'type' => 'VARCHAR',
                'constraint' => '20'
            ],
            'phone' => [
                'type' => 'VARCHAR',
                'constraint' => '15'
            ],
            'address' => [
                'type' => 'TEXT'
            ],
            'created_at datetime default current_timestamp',
            'updated_at datetime default current_timestamp on update current_timestamp'
        ]);
        $this->forge->addKey('id', true);
        $this->forge->createTable('users');
    }

    public function down()
    {
        $this->forge->dropTable('users');
    }
}

사용자 마이그레이션 스키마를 입력 한 후 아래 명령어를 사용하여 마이그레이션 해 보겠습니다.

php spark migrate

 

4 단계 : 모델 생성

Codeigniter 4에서는 spark를 사용하여 모델을 생성 할 수 있습니다. 따라서 프로젝트에 따라 사용자를위한 하나의 모델을 만들 것입니다. 실제로 사용자 테이블에 대한 마이그레이션을 이미 만들었습니다. 따라서 터미널을 열고 새 모델 파일을 만듭니다.

php spark make:model User

모델을 만든 후에는 다음과 같이 만드십시오.

User.php

<?php

namespace App\Models;

use CodeIgniter\Model;

class User extends Model
{
    protected $DBGroup              = 'default';
    protected $table                = 'users';
    protected $primaryKey           = 'id';
    protected $useAutoIncrement     = true;
    protected $protectFields        = true;
    protected $allowedFields        = ['name', 'email', 'password', 'phone', 'address'];

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

}

 

5 단계 : 컨트롤러 생성

양식에서 입력을 얻으려면 컨트롤러가 필요했습니다. 양식 데이터를 읽은 후 해당 입력에 대한 유효성 검사 규칙을 설정합니다. Codeigniter 4에서는 spark 명령을 사용하여 컨트롤러를 생성 할 수 있습니다.

php spark make:controller UserController

ㅊ여기에서 UserController가 생성되었습니다. 이제 여기에 기능을 추가하겠습니다.

UserController.php

<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\User;

class UserController extends BaseController
{
    /**
     * constructor
     */
    public function __construct()
    {
        helper(['form', 'url']);
    }

    /**
     * User Registration form
     *
     * @return void
     */
    public function index()
    {
        return view('registration');
    }

    /**
     * Register User
     *
     * @return void
     */
    public function create() {
        
        // validate inputs
        $inputs = $this->validate([
            'name' => [
                'label' => 'Name',
                'rules' => 'required|min_length[5]',
                'errors' => [
                    'required' => 'Please enter your name.',
                    'min_length' => 'Name must be atleast 5 characters long.'
                ]
            ],
            'email' => [
                'label' => 'Email',
                'rules' => 'required|valid_email',
                'errors' => [
                    'required' => 'Enter your email.',
                    'valid_email' => 'Please enter a valid email address.'
                ]
            ],
            'password' => [
                'label' => 'Password',
                'rules' => 'required|min_length[5]|alpha_numeric',
                'errors' => [
                    'required' => 'Enter your password.',
                    'min_length' => 'Password must be atleast 5 digits.',
                    'alpha_numeric' => 'Password must contain alpha numeric'
                ]
            ],
            'confirm_password' => [
                'label' => 'Confirm Password',
                'rules' => 'required|matches[password]',
                'errors' => [
                    'required' => 'Re-enter your password.',
                    'matches' => 'Confirm password and password must be same.'
                ],
            ],
            'phone' => [
                'label' => 'Mobile number',
                'rules' => 'required|numeric|regex_match[/^[0-9]{10}$/]',
                'errors' => [
                    'required' => 'Enter your mobile number.',
                    'numeric' => 'Mobile number must be a number.',
                    'regex_match' => 'Mobile number must be a valid mobile number.'
                ]
            ],
            'address' => [
                'label' => 'Address',
                'rules' => 'required|min_length[10]',
                'errors' => [
                    'required' => 'Enter your address.',
                    'min_length' => 'Address must be atleast 10 characters long.'
                ]
            ]
        ]);

        if (!$inputs) {
            return view('registration', [
                'validation' => $this->validator
            ]);
        }

        // insert data 
        $user = new User;
        $user->save([
            'name' => $this->request->getVar('name'),
            'email'  => $this->request->getVar('email'),
            'password'  => password_hash($this->request->getVar('password'), PASSWORD_DEFAULT),
            'phone'  => $this->request->getVar('phone'),
            'address'  => $this->request->getVar('address')
        ]);

        session()->setFlashdata('success', 'Success! registration completed.');
        return redirect()->to(site_url('/user'));
    }
}

 

6 단계 : 라우트 설정하기

경로를 생성하려면 app/Config/Routes.php 파일을 엽니 다. 이제 아래 경로를 거기에 넣으십시오.

$routes->get('user', 'UserController::index'); $routes->post('user', 'UserController::create');

 

7 단계 : 뷰 만들기

입력 유효성 검사를위한 양식을 만들어야합니다. 따라서 양식을 작성하려면 양식을 포함 할보기가 필요합니다. 따라서 app/Views 폴더 안에 보기를 만듭니다. registration.php라는 이름으로 뷰를 저장하겠습니다.

<!doctype html>
<html lang="en">
  <head>
    <title>Codeigniter 4 Form Validation Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.4.1/font/bootstrap-icons.css">
  </head>
  <body>
      <div class="container py-4">
      <?php $validation =  \Config\Services::validation(); ?>
        <div class="row">
            <div class="col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12 m-auto">
                <form method="POST" action="<?= base_url('user') ?>">
                    <?= csrf_field() ?>

                    <!-- display flash data message -->
                    <?php
                        if(session()->getFlashdata('success')):?>
                            <div class="alert alert-success alert-dismissible">
                                <button type="button" class="btn-close" data-bs-dismiss="alert">&times;</button>
                                <?php echo session()->getFlashdata('success') ?>
                            </div>
                        <?php elseif(session()->getFlashdata('failed')):?>
                            <div class="alert alert-danger alert-dismissible">
                                <button type="button" class="btn-close" data-bs-dismiss="alert">&times;</button>
                                <?php echo session()->getFlashdata('failed') ?>
                            </div>
                    <?php endif; ?>

                    <div class="card shadow">
                        <div class="card-header">
                            <h5 class="card-title">Register User</h5>
                        </div>

                        <div class="card-body p-4">
                        
                            <div class="form-group mb-3 has-validation">
                                <label class="form-label">Name</label>
                                <input type="text" class="form-control <?php if($validation->getError('name')): ?>is-invalid<?php endif ?>" name="name" placeholder="Name" value="<?php echo set_value('name'); ?>"/>
                                <?php if ($validation->getError('name')): ?>
                                    <div class="invalid-feedback">
                                        <?= $validation->getError('name') ?>
                                    </div>                                
                                <?php endif; ?>
                            </div>

                            <div class="form-group mb-3">
                                <label class="form-label">Email</label>
                                <input type="text" class="form-control <?php if($validation->getError('email')): ?>is-invalid<?php endif ?>" name="email" placeholder="Email" value="<?php echo set_value('email'); ?>"/>
                                    <?php if ($validation->getError('email')): ?>
                                    <div class="invalid-feedback">
                                        <?= $validation->getError('email') ?>
                                    </div>                                
                                <?php endif; ?>
                            </div>

                            <div class="form-group mb-3">
                                <label class="form-label">Password</label>
                                <input type="password" class="form-control <?php if($validation->getError('password')): ?>is-invalid<?php endif ?>" name="password" placeholder="Password" value="<?php echo set_value('password'); ?>"/>
                                    <?php if ($validation->getError('password')): ?>
                                    <div class="invalid-feedback">
                                        <?= $validation->getError('password') ?>
                                    </div>                                
                                <?php endif; ?>
                            </div>

                            <div class="form-group mb-3">
                                <label class="form-label">Confirm Password</label>
                                <input type="password" class="form-control <?php if($validation->getError('confirm_password')): ?>is-invalid<?php endif ?>" name="confirm_password" placeholder="Confirm Password" value="<?php echo set_value('confirm_password'); ?>"/>
                                    <?php if ($validation->getError('confirm_password')): ?>
                                    <div class="invalid-feedback">
                                        <?= $validation->getError('confirm_password') ?>
                                    </div>                                
                                <?php endif; ?>
                            </div>

                            <div class="form-group mb-3">
                                <label class="form-label">Phone</label>
                                <input type="text" class="form-control <?php if($validation->getError('phone')): ?>is-invalid<?php endif ?>" name="phone" placeholder="Phone" value="<?php echo set_value('phone'); ?>"/>
                                    <?php if ($validation->getError('phone')): ?>
                                    <div class="invalid-feedback">
                                        <?= $validation->getError('phone') ?>
                                    </div>                                
                                <?php endif; ?>
                            </div>

                            <div class="form-group">
                                <label class="form-label">Address</label>
                                <textarea class="form-control <?php if($validation->getError('address')): ?>is-invalid<?php endif ?>" name="address" placeholder="Address"><?php echo set_value('address'); ?></textarea> 
                                    <?php if ($validation->getError('address')): ?>
                                    <div class="invalid-feedback">
                                        <?= $validation->getError('address') ?>
                                    </div>                                
                                <?php endif; ?>
                            </div>

                        </div>

                        <div class="card-footer">
                            <button type="submit" class="btn btn-success">Save</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
      </div>
  </body>
</html>

결과를 보려면 응용 프로그램을 저장하고 실행하십시오.

8 단계 : 개발 서버 시작

즐겨 찾는 브라우저를 열고 Codeigniter 프로젝트를 실행합니다. http://localhost : 8080/user로 이동합니다. 아래와 같이 등록 양식이 표시됩니다.

 

Study01_source.zip
0.00MB

Comments