laravel 如何设置 HTML 数字输入类型的默认值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43714965/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:53:56  来源:igfitidea点击:

How would I set a default value of HTML number input type?

phphtmllaravel

提问by hoolakoola

I'm using Laravel and am currently trying to pass form data to a database, but I'm getting an error that the fields I am trying to enter may not be null:

我正在使用 Laravel 并且目前正在尝试将表单数据传递到数据库,但我收到一个错误,即我尝试输入的字段可能不为空:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'assists' cannot be null 

The way the form is set up, there will regularly be times where certain inputs are null,

表单的设置方式,经常会出现某些输入为空的情况,

<tr>
    <input type="hidden" name="player_id" value="{{ $player->id }}">
    <input type="hidden" name="game_id" value="{{ $game->id }}">
    <td>{{ $player->fn }} {{ $player->ln }}</td>
    <td><input type="number" name="goals" placeholder="goals"></td>
    <td><input type="number" name="assists" placeholder="assists"></td>
    <td><input type="number" name="tackles" placeholder="tackles"></td>
    <td><input type="number" name="saves" placeholder="saves"></td>
    <td><input type="number" name="yellows" placeholder="yellows"></td>
    <td><input type="checkbox" name="red" placeholder="red"></td>
</tr>

and that it almost the expected behavior. I figured the easiest way to fix this is to set the number input types default to 0, so it is passed to the database unless otherwise specified. How can I accomplish this?

并且它几乎是预期的行为。我认为解决此问题的最简单方法是将数字输入类型默认设置为 0,因此除非另有说明,否则将其传递给数据库。我怎样才能做到这一点?

回答by Ason

As mplungjansuggested, the simplest and most efficient is to use one of an inputelement's default attributes, value

正如mplungjan建议的那样,最简单和最有效的是使用input元素的默认属性之一,value

<input type="number" name="goals" placeholder="goals" value="0">

回答by Rhythm garg

There are many different ways you can achieve this.

有许多不同的方法可以实现这一目标。

Explicitly specify default column value in the model

在模型中显式指定默认列值

class Game extends Model {
   protected $attributes = [
       'assists' => '0'
   ];
}