我正在开发一个LaravelPHP应用程序,我用来创建新数据的一个表单包含一个复选框字段。 当我尝试提交表单时,未选中此复选框,出现"SQLSTATE:不能为空"错误。 我尝试使用几种解决方案来解决此问题,但它们尚未为我工作。
控制器:
public function store()
{
$input = 'Input::all();
$validation = new Validators'Video;
if($validation->passes())
{
/* Additional Controller Code for storing file path names */
return 'Redirect::route('overview');
}
else
{
return 'Redirect::back()
->withInput()
->withErrors($validation->errors)
->with('message', 'Could not create video');
}
}
我存储复选框数据的字段的名称是"video_active"。
EloquentVideoRepository:
public function create($input, $filename, $thumb_filename)
{
/* Need this structure in order for photos to actually be displayed. */
$newVideo = new Video;
/* Store Data here */
/* Using ''Input::get()' method for accepting unchecked checkboxes */
$newVideo->video_active = 'Input::get('video_active');
return $newVideo->save();
}
形式:
@section('content')
{{ Form::open(array('route' => 'store_video', 'method' => 'POST', 'files' => true)) }}
/* Additional Form Code here */
/* Code for accepting checkbox data */
<div class="form-group">
{{ Form::label('video_active', 'Active') }}
{{ Form::checkbox('video_active', 'Active') }}
</div>
<div class="form-group">
{{ Form::submit('Submit', array('class' => 'btn btn-primary')) }}
</div>
{{ Form::close() }}
@stop
我不确定为什么在表单中创建新数据时不能接受未选中的复选框。 任何帮助将不胜感激!
$newVideo->video_active = 'Input::get('video_active');
如果尚未定义'Input::get('video_active');
,它将返回 null。
使用这样的三元语句
$newVideo->video_active = ('Input::get('video_active') !== null) ? 'Input::get('video_active') : "";
这相当于
if('Input::get('video_active') !== null) {
$newVideo->video_active = 'Input::get('video_active');
} else {
$newVideo->video_active = "";
}
我建议你做的是使用1或0,而不是"活动"和"将数据库列video_active
设置为 INT(1),然后执行
{{ Form::checkbox('video_active', '1') }}
$newVideo->video_active = ('Input::get('video_active') == 1) ? 1 : 0;
然后,如果您需要检查是否设置了video_active
if($myModel->video_active == 1) {
// Video is active
}
虽然解释看起来不错,但我的实现建议是:
$newVideo->video_active = 'Input::get('video_active', false);