728x90


이제 간단한 웹페이지를 만들기 위해서 해볼것은 form값으로 데이터를 받는것이다.

즉 request를 받고 response를 하는 과정인데 이를 codeigniter로 한번 해보자.

이과정은 2개의 php controller와 2개의 php view로 구성되어 있다.


<?php //form_test_view.php?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>for test view</title>
</head>
<body>
<h1>form으로 parameter 넘기기</h1>
<form action="formreceive" method="post" id="myform">
문자열 입력1 : <input type="text" name="str1"><br>
문자열 입력2 : <input type="text" name="str2"><br>
<input type="submit" name="submit">
</form>
</body>
</html>

우리가 일반적이게 생각하는 view예제이다. 이 경우 당연하지만 formreceive경로가 있어야한다.

그 외에는 특이할게 없는 코드이지만 사실 codeigniter에서는 아래처럼 쓰는 경우도 있다.


<?php //form_test_view.php?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>for test view</title>
</head>
<body>
<h1>form으로 parameter 넘기기</h1>
<?php
$attributes = array('method'=>'post','id'=>'myform');
echo form_open('formreceive',$attributes); ?>
문자열 입력1 : <input type="text" name="str1"><br>
문자열 입력2 : <input type="text" name="str2"><br>
<input type="submit" name="submit">
<?php echo form_close(); ?>
</body>
</html>

인터넷 에제에서는 아래와 같이 쓰는 경우도 많다.

왜 굳이 저렇게 써야하는지는 필자도 잘 모르겠다. 가독성만 심하게 해치는것 같다.

어쨋던 두 사례 역시 알아둬야 남의 코드를 이해하기 편할 것이다.


class FormTest extends CI_Controller
{

public function index()
{
$this->load->view('form_test_view');
}
}

그리고 form test를 보여줄 controller의 예제이다.

이 컨트롤러는 단순히 보여주는게 전부이기 때문에 복잡한 로직은 존재치 않는다.


class FormReceive extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper('form');
$this->load->helper('url');
}
public function index()
{
if ($this->input->post('submit') == true) {
$data['value1'] = $this->input->post('str1');
$data['value2'] = $this->input->post('str2');
$data['method'] = 'post';
}
else if($this->input->get('submit') == true){
$data['value1'] = $this->input->get('str1');
$data['value2'] = $this->input->get('str2');
$data['method'] = 'get';
}
$this->load->view('form_receive_view',$data);
}
}

위의 form_test_view는 보면 알겠지만 마지막에 formreceive를 호출하는 것을 확인할 수 있다.

따라서 우리는 거기에 관련된 controller를 시행해보려한다.

여기서 생성자를 보면 새로운 개념인 helper가 등장한다.

핼퍼라는 것은 일종의 라이브러리이다. 위의 행위는 라이브러리를 import시켰다고 생각해도 무방하다.

url과 관련된 작업을 하려면 url핼퍼를, form과 관련된 작업을 하려면 form핼퍼를 호출하여아한다.

우리는 둘다 하기 때문에 둘다 호출 하는 것이다.


index페이지를 보면 post로 접속했는지 get으로 접속했는지를 확인해서 각각 처리한다.

만약 따로 처리하고 싶지 않다면 if문을 쓰지 않으면된다.

그리고 값을 받을 때는 $this->input->post혹은 $this->input->get을 사용한다.

이를 연관배열에 저장하고 그 값을 $this->load->view의 두번째 파라메터로 전달한다.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<?php echo 'first : '.$value1;?><br>
<?php echo 'second : '.$value2;?><br>
<?php echo 'third : '.$method;?><br>
</body>
</html>

마지막으로 form_receive_view.php를 보자.

여기서 전달한 변수의 이름은 FormReceiver 컨트롤러에서 넣었던 연관배열 키 이름을 사용하면된다.

이제 실행하여 테스트 해보자.



해당 예제를 웹에서 실행해보자.



제대로 실행되는걸 확인할 수 있다.

+ Recent posts