2016-11-09 26 views
2

我正在使用Laravel並且正在創建一個表單,用戶可以先選擇一個類別,然後選擇一個相關的子類別。PHP獲取選定表格的選定值

一個類別都有一個id和一個名稱,一個子類別都有一個id和名稱,以及一個PARENT_ID(所以這是父類的ID)。

現在我嘗試以下方法: 用戶可以選擇一個類別,之後他做了,第二select出現,並且用戶可以從所屬的父類(也只有這些!)的子類別選擇的子類別。

因此,視圖從控制器獲取所有類別和所有子類別。

然後,類別我這樣做:

<div class="form-group{{ $errors->has('category') ? ' has-error' : '' }}"> 
           <label for="category" class="col-md-4 control-label">Kategorie</label> 

           <div class="col-md-6"> 
            <select> 
             @foreach($categories as $category) 
              <option value="<?php echo $category['id'];?>">{{$category->name}}</option> 
             @endforeach 
            </select> 
           </div> 
          </div> 

而對我有相同的,只是子類別的子類別:

<div class="form-group{{ $errors->has('subCategory') ? ' has-error' : '' }}"> 
           <label for="subCategory" class="col-md-4 control-label">Unterkategorie</label> 

           <div class="col-md-6"> 
            <select> 
             @foreach($subCategories as $subCategory) 
              <option value="<?php echo $subCategory['id'];?>">{{$subCategory->name}}</option> 
             @endforeach 
            </select> 
           </div> 
          </div> 

現在的問題是:我需要做什麼是(在子類別的foreach)一個@if並檢查category select,然後所選擇的option的值檢查if($subcategory->parent_id == $chosenOptionID),說它在僞代碼。我怎樣才能做到這一點?我不想發送表單或什麼的,以前有人沒有選擇子類別以及....當然,我也許可以發送一個Ajax請求,只要選擇一個類別控制器,然後檢查的價值控制器中的選項併發回該ID。但是,這會導致非常多的流量,並會propably不是最好的解決辦法,所以我想這樣做只是,如果我沒有得到一個更好的方式做....

PS:現在的問題是而不是在沒有選擇類別時隱藏子類別,那是基本的js,我知道該怎麼做。我只想知道,如果可以在表單尚未發送的情況下讀取category select的值。

編輯:我現在嘗試了AJAX的事情,但似乎有一點錯誤... 我改變什麼:

<div class="form-group{{ $errors->has('subCategory') ? ' has-error' : '' }}"> 
           <label for="subCategory" class="col-md-4 control-label">Unterkategorie</label> 

           <div class="col-md-6"> 
            <select class="form-control" id="subCategorySelect"> 

            </select> 
           </div> 
          </div> 

的選擇現在是空的,並有一個ID。然後在同一文件中,我有以下JS:

<script> 
    $().ready(function(){ 
     $('#categorySelect').change(function(){ 
      var selectedOption = $('#categorySelect').find(":selected").val(); 
      $.ajax({ 
       url: '/getSubCategories', 
       data: {'id': selectedOption}, 
       type: 'GET', 
       success: function (data) { 
        $('#subCategorySelect').html(data); 
       } 
      }); 
     }); 
    }); 
</script> 

/getSubcategories路由指向下面的函數在我的控制器:

public function returnSubCategories(Request $request){ 
     $subCategories = Subcategory::where('parent_id', '=', $request->id); 
     foreach($subCategories as $subCategory){ 
      echo "<option value='$subCategory->id'>$subCategory->name</option>"; 
     } 
    } 

但它不工作.. Ajax請求被髮送defintely在選擇一個選項時,也會發送正確的ID。但不知何故沒有輸出......任何想法爲什麼?

+0

在你的' Blueblazer172

+0

和@foreach不在php標籤中:P – Blueblazer172

+0

@ Blueblazer172Í沒有輸入來添加選中的內容,那該怎麼辦? '@ foreach'是刀片語法,laravel – nameless

回答

1

我終於得到它使用AJAX工作。這是我最初的subCategorySelect

<div class="form-group{{ $errors->has('subCategory') ? ' has-error' : '' }}"> 
           <label for="subCategory" class="col-md-4 control-label">Unterkategorie</label> 

           <div class="col-md-6"> 
            <select class="form-control" id="subCategorySelect"> 

            </select> 
           </div> 
          </div> 

select現在是空的並且有一個ID。然後在同一文件中,我有以下JS:

<script> 
    $().ready(function(){ 
     $('#categorySelect').change(function(){ 
      var selectedOption = $('#categorySelect').find(":selected").val(); 
      $.ajax({ 
       url: '/getSubCategories', 
       data: {'id': selectedOption}, 
       type: 'GET', 
       success: function (data) { 
        $('#subCategorySelect').html(data); 
       } 
      }); 
     }); 
    }); 
</script> 

/getSubcategories路由指向在我的控制器以下功能:

public function returnSubCategories(Request $request){ 
     $subCategories = Subcategory::where('parent_id', '=', $request->id)->get(); 
     foreach($subCategories as $subCategory){ 
      echo "<option value='$subCategory->id'>$subCategory->name</option>"; 
     } 
    } 

而且它完美的作品。

+0

你確定它是正常工作嗎?你有一個類型GET,但你張貼數據 –

+0

也許我看起來你的請求似乎在處理它:P –

+0

@PuyaSarmidani是的,它的請求也在處理它,這個函數('returnSubCategories')完全獨立於稍後處理髮布表單數據的函數 – nameless

0

希望這將幫助你瞭解它是如何與PHP的工作,無論如何,一個選擇的選項:

<div class="form-group"> 
    <label class="control-label" for="country">Country:<span>*</span></label> 
    <select name="country" type="text" class="form-control" id="country"> 
     <option value="">--Country--</option> 
     <?php 
     include "../db/db.php"; //db-connection cause i want to load a country list 
     $sql = "SELECT id, country_name FROM apps_countries ORDER BY country_name ASC"; 
     $result = $conn->query($sql); 

     if ($result->num_rows > 0) { //check if an entry is there 
      while($row = $result->fetch_assoc()) { //get the values from the db 

       //now this is the part you have to implement in your script 
       if(isset($_POST["country"]) && $row["id"] == $_POST["country"]) { //check if country isset so if the user selected something 

        $optionSelected = "selected='selected'"; 

       } else{ 

        $optionSelected = ""; 

       } 

       //your foreache loop goes here/add the value that is selected here 
       /*@foreach($categories as $category) 
         <option value="<?php echo $category['id']; ?>">{{$category->name}}</option> // get the associative array with "" and change it to $category["id"] 
       @endforeach*/ 

       /**for my attempt it was this 
           {the id like as your category[id]} {set the selected here inside the option tag} 
                ↓     ↓      */ 
       $countrySet = "<option value='" .$row["id"]. "' ".$optionSelected.">".$row["country_name"]."</option>"; 
       echo $countrySet; 
      } 
     } 
     $conn->close(); 
     ?> 
    </select> 
</div> 
+0

我想知道的是:如果你以前沒有提交表單,你如何訪問'$ _POST [「country']'? – nameless

+0

@nameless查找AJAX,這是它加載它的唯一方法,如果不是提交 – Blueblazer172

+0

這將只適用於如果您提交絕對正確 – Blueblazer172