2012-04-10 7 views
0

미션 :CakePHP는 2.1 및 jQuery를 UI 자동 완성

부서라는 직원의 양식 필드에서 (부서 테이블에 저장) 부서의 자동 완성을 구현합니다. 사용자가 부서 이름의 철자를 입력하십시오. 부서와 일치하는 이름의 목록을 표시합니다. 사용자가 하나를 선택하면됩니다.

플랫폼

  1. CakePHP는 2.1
  2. JQUERY UI 자동 완성

데이터베이스 모델

Emplyee (ID (JQUERY UI 라이브러리 버전 1.8.18의 일부), first_name, last_name, department_id) departmen t (ID, 이름) 내 add.ctp 파일 아약스 호출 너무

 $("#auto_complete").autocomplete({ 
     source: function(request, response) { 
      $.ajax({ 
       url: "/employees/showDepartment", 
       dataType: "json", 
       data: { 
        featureClass: "P", 
        style: "full", 
        maxRows: 12, 
        name_startsWith: request.term 
       }, 
       success: function(data) { 
        alert("success--"); 
        response($.map(data, function(item) { 
        //alert(item); 
         return { 
          label: item.name, 
          value: item.id 
         } 
        })); 
       } 
      }); 
     }, 
     minLength: 2, 
     select: function(event, ui) { 
      log(ui.item ? 
       "Selected: " + ui.item.label : 
       "Nothing selected, input was " + this.value); 
     }, 
     open: function() { 
      $(this).removeClass("ui-corner-all").addClass("ui-corner-top"); 
     }, 
     close: function() { 
      $(this).removeClass("ui-corner-top").addClass("ui-corner-all"); 
     } 
    }); 

같은 일이 내가 원하는 해달라고

public function getAddress() { 
     $this->autoRender = false;// I do not want to make view against this action. 
     $this->log($this->params->query['name_startsWith'] , 'debug'); 
     $str = $this->params->query['name_startsWith']; 
     $this->log($str, 'debug'); 
     $this->layout = 'ajax'; 
     $departments = $this->Employee->Department->find('all', array('recursive' => -1, 
      'conditions'=>array('Department.name LIKE'=>$str.'%'), 
    'fields'=>array('name', 'id'))); 
     //$this->set('departments',$departments); 
     $this->log($departments, 'debug'); 
     echo json_encode($departments); 
} 

내에는 EmployeeController라는 show_depatment의 조치를()가있다 show_department 어떤 뷰를 가지고 있기 때문에 내가 만든 것입니다. $ this-> autoRender = false;

예상대로 작동하지 않습니다. 내가 응답 HTLM 섹션에 불을 지르고를 사용하여 응답을 디버깅 할 때

그것은

  [{"Department":{"name":"Accounting","id":"4"}}] // when i type "acc" in input field 

질문을 보여준다는 양식 필드에 표시 할 수 있도록하는 방법

  1. .
  2. echo json_encode ($ departments); json 형식으로 응답을 보내는 올바른 방법입니까? 내가 아약스 호출 (경고 (항목))의 성공 부분적으로 경고 할 때
  3. 그것은 "정의"로 오류를 제공

답변

2

내 컨트롤러 액션이

처럼 보이는 그래서 지방 모델과 마른 컨트롤러의 친구 해요
public function getAddress() 
{ 
    if($this->RequestHandler->isAjax()) { 
     Configure::write('debug', 0); 
     $this->layout = 'ajax'; 
     $this->autoRender = false; 
     echo json_encode($this->Employee->Department->getAddress($this->params['url']['term'])); 
     exit; 
    } 
} 

내 부서 모델 방법 :

public function getAddress($str) 
{ 

    $rs = array(); 
    $search = $this->find('all', array( 
     'recursive' => -1, 
     'conditions'=>array('Department.name LIKE'=>$str.'%'), 
     'fields'=>array('name', 'id') 
    )); 


    if (!empty($search)) 
    { 
     //the jquery ui autocomplete requires object with label/value so we need to traverse the query results and create required array 

     foreach ($search as $key => $val) 
     { 
      $rs[] = array('label' => $val['Department']['name'], 
       'value' => $val['Department']['id']); 
     } 
    } 
    return $rs; 
} 

그리고 마침내 내보기 항목은 다음과 같다 :

$("#auto_complete").autocomplete({ 
    minLength: 2, 
    source: function(request, response) { 
     var term = request.term; 
     if (term in cache) { 
      response(cache[ term ]); 
      return; 
     } 

     lastXhr = $.getJSON("/employees/showDepartment", request, function(data, status, xhr) { 
      cache[ term ] = data; 
      if (xhr === lastXhr) { 
       response(data); 
      } 
     }); 
    } 
}); 

희망이 도움이됩니다.