TIP게시판

제목 DB TABLE column comment 를 이용한 손쉬운 폼빌더
글쓴이 에반스 작성시각 2016/02/16 12:24:58
댓글 : 3 추천 : 1 스크랩 : 0 조회수 : 12963   RSS

안녕하세요.

어느덧 코드이그나이터로 8개월째 작업하면서 많은 걸 배워가는 유저입니다.

보통 Form 태그 안에 여러가지 input를 구성한 폼을 만드실텐데요. 보통 그 인풋값이 DB TABLE 의 Column 과 매칭되는 경우가 많더군요.

그래서 저는 column comment 안에 폼 빌딩에 필요한 몇가지 정보를 추가하여 사용하고 있습니다.

 

/**
	 * 컬럼정보 생성
	 * @param  String $table 디비 테이블명
	 * @return array()       Field,Type,
	 */
	function create_columns($table=""){
		if(!$table) $table = $this->table;
		$query ="show full columns from `$table`";
    	$tmps = $this->db->query($query)->result_array();

		foreach ($tmps as $tmp) {
			$this->columns[$tmp['Field']] = $this->reset_columns($tmp);		
		}
		return $this->columns;
	}
/**
	 * 디비 필드 정보들을 재조작 하여 저장
	 * @param  array $col 필드정보를 가지고 있는 배열
	 * @return array      변경된 정보
	 */
	function reset_columns($col){

			if( preg_match("/date/i", $col['Type']) ) $col['Type'] = "date"; 
			if( preg_match("/datetime/i", $col['Type']) ) $col['Type'] = "datetime";
			else if( preg_match("/여부/i", $col['Comment']) ) $col['Type'] = "switcher";  
			else if( preg_match("/파일경로/i", $col['Comment']) ) $col['Type'] = "file"; 
			else if( preg_match("/varchar/i", $col['Type']) ) $col['Type'] = "text";
			else if( preg_match("/text/i", $col['Type']) ) $col['Type'] = "textarea";
			else if( preg_match("/enum/i", $col['Type']) ){
				
				//enum 세팅 코멘드에서 셀렉트 옵션값 추출 또는 쿼리

				preg_match("/\'.*\'/i", $col['Type'], $matches);
				$values = explode(",", preg_replace("/\'|\"/i", "", $matches[0]));

				$fd = explode("|", $col['Comment']);
				$col['Comment'] = $fd[0];
				$fds = explode(",", $fd[1]);
				
				for ($n=0; $n < count($fds); $n++) { 
					$col['options'][] = array("value"=> $values[$n], "label"=> $fds[$n]); 
				}
				$col['Type'] = "select";

			}else if( preg_match("/int|float|double/i", $col['Type']) ){
				$col['vali_rules'][] = "numeric";
				if( preg_match("/int/i", $col['Type']) )
					$col['options'] = 0;
				else
					$col['options'] = 2;
				$col['Type'] = "number";
			}
			if($col['Key'] == "PRI"){
				$this->primary = $col['Field'];
				if($col['Extra'] == 'auto_increment'){
					$col['Type'] = "hidden"; 
				}
			}
			if($col['Null'] == "NO") $col['vali_rules'][] = "required";
			$this->selections[] = $col['Field'];
			

			$col['auth'] = "c,u,r,d";

			unset($col['Null']);
			unset($col['Key']);
			unset($col['Extra']);
			unset($col['Default']);
			unset($col['Collation']);
			unset($col['Privileges']);
			return $col;
	}
	

애초에 디비 테이블에 컬럼에는 자료형이 입력되어 있고 컬럼명도 있으니 여러가지로 재활용할 구석이 많습니다.

예를 들어, datetime 의 자료형의 경우, 폼 빌드할 때에 datetimepicker 같은 JS 플러그인을 달아 놓을 수 있죠.

데이터형이 varchar(10) 라면 폼검증시에 입력값의 MAX = 10 으로 검증하는 배열을 사전에 만들어 놓을 수 있습니다.

enum()의 경우, 레이블 값을 코멘트에 미리 넣어놓으면 셀렉트 박스도 쉽게 만들 수 있죠.

코멘트를 보다 표준화 해서 입력한다고 가정하면, "~~여부" 의 경우, T or F 체크 박스로 활용할 수 있습니다.

무엇보다 DB 정보를 기준으로 폼빌딩 할 수 있기 때문에 개발과정에서 DB가 변경되거나 하면 관련 폼도 동시에 적용되어 개발시간 감축에 많은 도움이 됩니다. DB 설계가 완벽하지 않으면 자주 발생하는 일이라... 저에겐...^^;;;;

이제 막 시작하신 분들에게 작은 참고가 되길 바라며 어쭙지 않은 저의 코드를 올려 봅니다.

 

감사합니다.

function render_input($col,$value="",$no=""){
	if(is_array($value)){
			// 값이 배열로 들어오면 그 배열에서 해당 값을 찾아내
			$arrValue = $value;
			$value = $value[$col['Field']];
		}
	if($col['vali_rules'] && $no != "filter"){

		foreach ( $col['vali_rules'] as $vali ) {
			if($vali=="required") 
				$required = "required = 'required'";
			else 
				$required = "";
		}

	}
	if($no == "filter"){
		$required = "";
		
	}elseif($no=="insert"){

	}else{
		
		$col['Field'] .="[$no]"; 

	}
	ob_start();
	 if(preg_match("/c|u/i", $col['auth'])){
	 	
		 if( preg_match("/date/i", $col['Type']) ){ //날짜고르기 ?>

			<?php if ($no=="filter"): ?>
				<div class="input-daterange input-group no-padding">
					<input id='<?=$col['Field']?>_datepicker_sp' type="text" name="<?=$col['Field']?>_sp" placeholder="<?=$col['Comment']?>" class="form-control" value="<?=$arrValue[$col['Field']."_sp"]?>" ><span class="input-group-addon">to</span>
					<input id='<?=$col['Field']?>_datepicker_ep' type="text" name="<?=$col['Field']?>_ep" placeholder="<?=$col['Comment']?>" class="form-control" value="<?=$arrValue[$col['Field']."_ep"]?>" >
				</div>
				<script>
					$('#<?=$col['Field']?>_datepicker_sp').datepicker({
					    format: "yyyy-mm-dd",
					    todayBtn: "linked",
					    language: "kr",
					    autoclose: true,
					    todayHighlight: true
					});
					$('#<?=$col['Field']?>_datepicker_ep').datepicker({
					    format: "yyyy-mm-dd",
					    todayBtn: "linked",
					    language: "kr",
					    autoclose: true,
					    todayHighlight: true
					});
				</script>
			<?php else: ?>
				<input id='<?=$col['Field']?>_datepicker' type="text" name="<?=$col['Field']?>" placeholder="<?=$col['Comment']?>" class="form-control" value="<?=$value?>" >
				<script>
					$('#<?=$col['Field']?>_datepicker').datepicker({
					    format: "yyyy-mm-dd",
					    todayBtn: "linked",
					    language: "kr",
					    autoclose: true,
					    todayHighlight: true
					});

				</script>
			<?php endif ?>

		<? }else if( $col['Type'] == "switcher"  ){ //스위치 ?>
			<input <?=($value)?"checked='checked'":"" ?> value='1' type="checkbox" id="<?=$col['Field']?>_switch" name="<?=$col['Field']?>" placeholder="<?=$col['Comment']?>" class="form-control i-checker">
		<? }else if( $col['Type'] == "file" ){ // 파일업로드 ?>
			
			<input value="<?=$value?>" type="file" name="<?=$col['Field']?>" placeholder="<?=$col['Comment']?>" value='' class="form-control" <?=$required?>>

		<? }else if(  $col['Type'] == "textarea" ) { //에디터 ?>
			
	    	<textarea id='<?=$col['Field']?>_editor' name="<?=$col['Field']?>" placeholder="<?=$col['Comment']?>" class="form-control" <?=$required?>>
	    		<?=$value?>
	    	</textarea>
	        <script>
	        	CKEDITOR.replace( '<?=$col['Field']?>_editor' );
	        </script>

		<? }else if( $col['Type'] == "select" && $col['options'] ) { //셀렉트박스 
			if(!is_array($col['options'])){
				$query = $this->CI->db->query($col['options']);
				$col['options'] = array();
				foreach ($query->result_array() as $row)
				{
					$col['options'][] = $row;
				}
			} ?>
			
			<select id='<?=$col['Field']?>_select' name="<?=$col['Field']?>" class="form-control" value='<?=$value?>' <?=$required?>>
	    		<option value="">선택안함</option>
	    		<? foreach ($col['options'] as $opt) {
	    			if($value == $opt['value']) $selected = "selected='selected'";
	    			else $selected='';
	    		 ?>
					<option value="<?=$opt['value']?>" <?=$selected?> ><?=$opt['label']?></option>
				<? } ?>
	    	</select>

		<? }else{ ?>

			<input value="<?=$value?>" type="text" name="<?=$col['Field']?>" placeholder="<?=$col['Comment']?>" value='' class="form-control datalist-input" <?=$required?>>

		<? } ?>
	<? } ?>
	<?
		$html = ob_get_contents();
		ob_end_clean();
		return $html;
	}

 

 

 다음글 MY_Loader 확장을 이용한 레이아웃 구조 사용
 이전글 초보팁] 모든 페이지에서 로그인여부 검사하기 (5)

댓글

변종원(웅파) / 2016/02/16 16:05:47 / 추천 0

저는 comment 이용해서 db table 생성하고 스키마에 맞는 crud 파일 생성과 api에서 필수값 유무를 전처리하도록 할때 사용했었습니다.

최초 개발시 유용하겠네요. ^^

한대승(불의회상) / 2016/02/16 21:36:26 / 추천 0

좋은 아이디어 같습니다.

테스트 해봐야 겠네요.

정보 공유 감사 드립니다.

방문넷 / 2016/02/16 21:40:01 / 추천 0
추천 +1