2013-05-01 49 views
4

我開始學習Laravel,仍然在學習曲線上。現在我開始使用Laravel 3,但是一旦我找到工作,最有可能將我的項目切換到Laravel 4。 現在的問題是,如何驗證複選框數組,我想驗證組中至少有1個是啓用(選中)。我在Laravel論壇上讀過一段,我們只是使用必要的驗證它們,但是當我dd(input::all())我沒有看到其他東西,但輸入字段和複選框不是其中的一部分...Laravel 3 - 如何驗證複選框數組,至少檢查1個?

我的刀片的一部分創建代碼對於複選框:

<label class="checkbox">{{ Form::checkbox('changeReasons[]', 'ckbCRCertification', Input::had('ckbCRCertification'), array('id' => 'ckbCRCertification')) }} Certification</label> 
<label class="checkbox">{{ Form::checkbox('changeReasons[]', 'ckbCRDesignCorrection', Input::had('ckbCRDesignCorrection'), array('id' => 'ckbCRDesignCorrection')) }} Design Correction</label> 

我控制器(REST)的代碼是:

public function post_create() 
{ 
    print "Inside the post_create()"; 
    // validate input 
    $rules = array(
     'ecoNo'    => 'min:4', 
     'productAffected' => 'required', 
     'changeReasons'  => 'required' 
    ); 

    $validation = Validator::make(Input::all(), $rules); 

    if($validation->fails()) 
    { 
     return Redirect::back()->with_input()->with_errors($validation); 
    } 

    $eco = new Eco; 

    $eco->ecoNo = Input::get('ecoNo'); 
    $eco->productAffected = Input::get('productAffected'); 

    $eco->save(); 

    return Redirect::to('ecos'); 
} 

我也想知道獲得的複選框狀態的驗證失敗後的正確的代碼,我想我看到了Input::had(checkBoxName)某處但那不是似乎工作,我可能沒有正確使用它,我有點混淆,因爲我看到的所有示例都是針對輸入而沒有其他內容。我假設L4中的驗證大致相同,是嗎?

回答

3

再回到這個項目,並做一些更多的研究,我發現這個問題的最好辦法如下。

我的刀片視圖:

<div class="control-group row-fluid"> 
    <?php $arrChangeReasons = Input::old('changeReasons', array()); // array of enable checkboxes in previous request ?> 

    <label class="checkbox">{{ Form::checkbox('changeReasons[]', 'certification', in_array('certification', $arrChangeReasons)) }} Certification</label> 
    <label class="checkbox">{{ Form::checkbox('changeReasons[]', 'designCorrection', in_array('designCorrection', $arrChangeReasons)) }} Design Correction</label> 
</div> 

葉片視圖的說明是一個2步處理,驗證之後發生,如下:

  1. 拉出複選框陣列(在我的情況'changeReasons []')與Input::old
  2. 從該數組中,我們可以搜索個別複選框,看看他們是否在那裏,如果他們然後改變支票框作爲checked狀態。這是in_array()函數的工作,返回true/false會改變複選框的狀態。

我的控制器(REST)代碼與我在開頭提到的問題完全一樣。有關更多信息,定義$rules = array('changeReasons' => 'required');將確保至少有一個複選框是checked

0

請記住複選框需要一個值。 它的複選框被選中Input :: get('foo')將返回1,但是如果它未被選中,它將不會返回任何內容,因爲它不在後置數組中。

我使用這個代碼:

if(Input::get('foo')){ 
    $bar->is_foo = 1; 
} 
else{ 
    $bar->is_foo = 0; 
} 
+1

或者你可以像使用Input :: get('foo',0);' – 2013-05-02 06:39:40

+2

那樣使用默認的回退,但是我怎樣才能讓我的'Validator'檢查並通過'return Redirect: :back_() - > with_input() - > with_errors($ validation);'我希望它成爲我的驗證的一部分,而不是作爲額外的輸入,如果可能的話我不能在同一時間返回 – ghiscoding 2013-05-02 13:27:24

+0

我想我我開始明白你爲什麼要這樣使用它,現在你寫的代碼可以用於單個複選框名稱,但在我的情況下,我使用複選框數組,所以如何檢索我的複選框的代碼1生活檢查?我嘗試了一些類似於'Input :: get('changeReasons [ckbCRCertification]',0)'的方法,但是這樣做不起作用,因爲'get'只能用單鍵而不用數組。那麼如何知道我的複選框是否啓用呢? – ghiscoding 2013-05-02 22:23:09

相關問題