php Laravel 刀片“旧输入或默认变量”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33652814/
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
Laravel blade "old input or default variable"?
提问by Jeton Tha?i
I want to show the old input in input value. If there isn't old input, than show other variable:
我想在输入值中显示旧输入。如果没有旧输入,则显示其他变量:
value="{{ old('salary_' . $employee->id) or 'Default' }}"
But when there is no old input, it gives me 1 instead of the default value!
但是当没有旧输入时,它给我 1 而不是默认值!
I think the problem has something to do with the concatenation, but I don't know how to fix it!?
我认为问题与串联有关,但我不知道如何解决!?
回答by Adunahay
or
is a comparison operator in PHP, so your code is evaluating to true
, or 1. What you want is a ternary if
statement.
or
是 PHP 中的比较运算符,因此您的代码计算结果为true
或 1。您想要的是三元if
语句。
As mentioned, or
can be used in blade as shorthand for a ternary if statement.
如前所述,or
可以在刀片中用作三元 if 语句的简写。
But you can (and should) just pass the default value as the second argument to the function, like so:
但是您可以(并且应该)将默认值作为第二个参数传递给函数,如下所示:
value="{{ old('salary_' . $employee->id, 'Default') }}"
回答by Alex
As described in the Laravel doc: "If you are displaying old input within a Blade template, it is more convenient to use the old helper:". So if you need add/edit data form (when you need to use edit form for add and edit in edit mode you need to use loaded data from model (database)) to show values from the model (through controller) you can use following:
如 Laravel 文档中所述:“如果您在 Blade 模板中显示旧输入,使用旧助手会更方便:”。因此,如果您需要添加/编辑数据表单(当您需要使用编辑表单在编辑模式下进行添加和编辑时,您需要使用从模型(数据库)加载的数据)来显示模型中的值(通过控制器),您可以使用以下内容:
name="some_value" value="{{ $some_value or old('some_value', $the_value) }}"
where is "some_value_from_model" variable name in view array. In this case it should be at first $some_value will be used to set in the "value" and, if no, it will try to use old (value from request from name "some_value") and if not old then '' should be used.
视图数组中的“some_value_from_model”变量名在哪里。在这种情况下,它应该首先 $some_value 将用于设置“值”,如果不是,它将尝试使用旧的(来自名称“some_value”的请求的值),如果不是旧的,则 '' 应该是用过的。
Thanks WoodyDRN for comment.
感谢 WoodyDRN 的评论。
回答by Антон Баранов
You can use the code (for PHP 7):
您可以使用代码(对于 PHP 7):
{{ old('field_name') ?? $model->field_name ?? 'default' }}
For checkbox checked attribute use the code (if default value is false):
对于复选框选中的属性,使用代码(如果默认值为 false):
{{ (old() ? old('field_name', false) : $model->field_name ?? false) ? 'checked' : '' }}
Construction {{ $something or 'default'}}
works only for variables
构造{{ $something or 'default'}}
仅适用于变量
回答by Bayu Nugraha
Try this:
尝试这个:
<textarea name="alamat" id="" class="form-control" placeholder="Alamat">{{ old('alamat').@$biodata->alamat }}</textarea>