简体   繁体   English

如何在用于编辑/创建的Laravel Blade模板中显示下拉列表的“选定”值?

[英]How to display 'selected' value of dropdown in Laravel Blade template used for both edit/create?

I'm using Blade templating in a Laravel 4 view to display a form for both create and edit, it all works fine until I have to render a select input type - it's ok when editing, but when creating a new record I get an error message Undefined variable: data , which is triggered by the 'selected' value in the second last line (last parameter passed to Form::select() ) 我在Laravel 4视图中使用Blade模板来显示用于创建和编辑的表单,在我必须呈现select输入类型之前,一切工作正常-编辑时可以,但是在创建新记录时出现错误消息Undefined variable: data ,由最后第二行中的“ selected”值触发(最后一个参数传递给Form::select()

@if( isset( $data) )
    {{ Form::model( $data ) }}
@else
    {{ Form::open() }}
@endif

    {{ Form::label( 'foo', 'label text' ) }}
    {{ Form::select( 'foo' , array('0' => 'No', '1' => 'Yes'), $data->foo ); }}
{{ Form::close() }}

is there a standard way in Laravel to avoid this when $data is not defined, using model binding as I have so far? Laravel中有没有一种标准方法来避免在没有定义$data时使用我到目前为止使用的模型绑定? Or do I need to simply use a variable to check in advance if $data is not undefined? 还是我需要简单地使用变量来预先检查$data是否未定义?

The whole purpose of Form Model Binding is that you don't have to set the values on your input fields yourself. 表单模型绑定的全部目的是您不必自己在输入字段上设置值。 You can just leave the value argument blank and Laravel will fill the value(s) in based on the name of the select, input, etc. 您只需将value参数保留为空白,Laravel就会根据选择,输入等的name来填充值。

{{ Form::select( 'foo' , array('0' => 'No', '1' => 'Yes')); }}

Also you can even remove your isset($data) check because Laravel will do that as well: 您也可以删除isset($data)检查,因为Laravel也可以这样做:

{{ Form::model( $data ) }}
    {{ Form::label( 'foo', 'label text' ) }}
    {{ Form::select( 'foo' , array('0' => 'No', '1' => 'Yes')); }}
{{ Form::close() }}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM