【问题标题】:Laravel returning values of all checkboxes everytimeLaravel 每次都返回所有复选框的值
【发布时间】:2014-07-11 11:32:18
【问题描述】:

我有一个从用户那里收集一些信息的表单中的清单。我正在尝试获取用户选择的那些复选框的值。

这是路线

Route::get('addoption', array('as' => 'getaddoption', 'uses' => 'CategoryController@getAddOption'));
Route::post('addoption', array('as' => 'postaddoption', 'uses' => 'CategoryController@postAddOption'));

这是控制器部分

public function getCategoryForm(){

    //$this->option is a model interface which deals with table named 'options' having one column 'option'

    $existing_options = $this->option->lists('option');
    return View::make('dashboard.addcategoryform')->with('existing_options', $existing_options);
}

这是处理复选框的表单部分(在dashboard.addcategory 视图中)

@foreach($existing_options as $existing_option)
    {{Form::label($existing_option, $existing_option)}}
    {{Form::checkbox($existing_option, $existing_option)}}
@endforeach

这样就创建了复选框。现在我想知道用户选择的复选框的值。

我正在通过 postAddOption 方法处理此表单

if($validator->passes()){
    $existing_option = $this->option->lists('option');          

    foreach($existing_option as $existing_opt){
            if(Input::get($existing_opt) == true){
                $selected_option[] = $existing_opt;
        }
    }

    print_r($selected_option);
}

但它给了我所有复选框的数组。

【问题讨论】:

    标签: php checkbox laravel


    【解决方案1】:

    您的所有复选框都应具有相同的名称并附加[]

    @foreach($existing_options as $existing_option)
        {{ Form::checkbox('options[]', $existing_option) }}
    @endforeach
    

    现在,当您提交时,它将作为一个数组提交,该数组将填充相应选中复选框值的每个值,因此您无需循环遍历它们。

    if($validator->passes()){
        dd(Input::get('options'));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-10
      • 1970-01-01
      • 2018-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-07
      • 2015-08-21
      相关资源
      最近更新 更多