2014-11-14 17 views
2

나는 지금 사용자 레지스트리 양식을 만들고 있는데, 나는 상태와 도시를 연관 짓고있다. 그래서 나는 사용자가 선택한 상태에 따라 선택 필드 값을 변경해야한다. .상태 도시에서로드로드

나는 형태로 뭔가가 : 내가 {를 사용하는 경우

{{양식 :: 선택 ('도시', $ 도시, 배열 ('ID', '도시')}}

을 {Form :: Select}} 필드는 모든 도시를 한 상태에서 요금을 부과하기 때문에 사용자가 상태를 선택하면 선택 필드의 도시 목록을 변경해야합니다.

무엇을 찾을 수 있습니까? 어떻게 할 수 있습니까?

감사합니다.

+1

클라이언트 쪽 코드 + Ajax 요청을 사용하여 t 업데이트를 고려해야합니다. 그는 비행 중에 선택합니다. –

+0

고마워, 할게 –

답변

2

jQuery와 함께 ajax를 사용할 수 있습니다.

$(document).on('change', '#state_id', function (e) { 

     // empty the select with previous cities if we have. 
     $('#cities').empty();    

     $.ajax({ 
       type: "POST", 
       dataType: "json", 
       // actions is a controller 
       // cities is a method of actions controller 
       url : "{{ URL::to('actions/cities') }}", 
       //here we set the data for the post based in our form 
       data : $('#MyFormID').serialize(), 
       success:function(data){      
         if(data.error === 0){ // all was ok         

         for (var i = 0; i < data.cities.length; i++) { 
          $('#cities').append("<option value='"+data.cities[i].id+"'>"+data.cities[i].city_name+"</option>") 
         } 

         }else{ 
          alert(data); 
         } 
       }, 
       timeout:10000 
     });       
    }); 

행동/도시 컨트롤러

//remember, this is a post method 
public function postCities(){ 

    // validate    
    $validator = Validator::make(Input::all(), 
     array(
      'state_id' => 'required|integer' 
    ));   

    if ($validator->fails()) { 
     return Response::json(array('error' => 1, 'message' => 'State is required')); 
    } 

    //City is your model, I assumes that you pkey is ID and the city name is city_name and your fkey is state_id 
    $cities = City::where('state_id', '=', Input::get('state_id'))->get(); 

    return Response::json(array('error' => 0, 'cities' => $cities)); 

} 
0
public function getCities($province_id) 
    { 
     $cities = Cities::where('province_id', '=', $province_id)->get(['id', 'name']); 
     return Response::json(array('error' => 0, 'cities' => $cities)); 
    } 
+2

이 코드는 질문에 대답 할 수 있지만 이유에 대한 추가 컨텍스트를 제공하거나이 코드가 질문에 대답하는 방식이 장기적인 가치를 향상시킵니다. –

0

당신은 sample vue component 그 선박을 확인 할 수 있습니다 :보기에

이 같은 상태 변화가 때 이벤트를 설정 빌드하고자하는 것을 정확히 수행하는 패키지 Laravel Cities.

이 패키지는 geonames.org에서 제공하는 세계 모든 국가의 도시를 지역화하고 제공되는 Eloquent 모델로 모든 쿼리를 수행 할 수있는 간단한 패키지입니다. HTTP API와 vue 구성 요소를 통해 일련의 단계를 통해 도시를 선택할 수 있습니다.

당신은 어떤 다른 입력 필드와 같은 양식에 삽입 할 수 있습니다 : 당신은이 같은 쿼리를 수행 할 수 있습니다

<form action="post-url" method="POST"> 
    <geo-select></geo-select> 
    <!-- Add more form fields here... --> 
    <input type="submit"> 
</form> 

제공된 웅변의 모델 :

// Get the States of USA in aplhabetic order 
Geo::getCountry('US') 
    ->children() 
    ->orderBy('name') 
->get(); 

죄송합니다, 데모 아직 하지만 github page에서 일부 소식을 확인할 수 있습니다 ...