簡體   English   中英

試圖從窗體到控制器獲取復選框的值

[英]Trying to get value of checkbox from form to controller

我正在嘗試做一些事情,以便在選中復選框控件時可以上傳照片。 我讓客戶端正常工作,以便選中此復選框時,將顯示上載控件,並且表單可以正確驗證。

但是,在我的控制器中,如果我的復選框已選中(true),則調用某種方法需要采取一些措施。 如果未選中(假),則執行其他操作。

在我的html頁面中,我有以下內容:

<form action="/supplier/submit/plan" method="post" role="form" id="plan-form">
...   
   <input name="checkingPhotos" type="checkbox" id="chkPhotos" />
   <label for="chkPhotos">I want to include photos in this plan.</label>
...
</form>

但是,在控制器中,我現在只想看看是否在復選框中得到了正確的值。 為此,我做了一些簡單的事情:

 public function submitPlan(Request $request)
    {
        $checkboxValue = $request->input('checkingPhotos');
        dd($checkboxValue);
    }

無論是否選中此復選框,結果均為null 我的路線也如下所示:

Route::post('/submit/plan', 'SupplierController@submitPlan');

有人可以告訴我我在做什么錯嗎? 我只想在控制器方法中看到值1 / True或0 / False。

如果是復選框,則應將輸入名稱修改為

<input name="checkingPhotos[]" type="checkbox" id="chkPhotos" />

然后,您應該能夠隨心所欲地獲得價值

$request->input('checkingPhotos');

看來您的問題出在您的路線上,將其更改為

Route::post('/supplier/submit/plan', 'SupplierController@submitPlan');

真正的問題是您的復選框沒有值。 添加一個值,您的問題就解決了。 它應該是:

<input name="checkingPhotos" type="checkbox" id="chkPhotos" value="1" />

[]創建一個數組

Dylan Kas提交了有關更改名稱以添加[]的答案,但這並不是出於您的考慮。 讓我們來看看:

<input name="checkingPhotos[]" type="checkbox" id="chkPhotos" />

將傳遞帖子字符串:

 checkingPhotos[]=On

在PHP中, 它將自動變成一個array

參照框架挑戰

為什么首先要有一個復選框? 是否需要復選框? 為什么不檢查文件是否存在。

$validated = $request->validate([
    //... other fields here.
    'image' => 'mime:png,gif,jpeg|max:10000' //set max to file size limit you want
]);
$plan = new SupplierPlan($validated);
if($request->has('image')){
   $plan->image = $request->image->store();
}
$plan->save();
// ... flash message, return view or redirect

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM