[英]Laravel-4 Blade: making a form select box using values in an object
I wish to make a select box of city names for a form. 我希望为表格填写一个城市名称选择框。 I have been able to create and pass to my view an object $city whose values I can correctly list on my view if I simply display them outside of a form. 我已经能够创建一个对象$ city并将其传递到我的视图中,如果我将其值简单地显示在表单外部,则可以在视图中正确列出它们。 The two properties of $city that are needed for the select box are: $city->id and $city->name. 选择框所需的$ city的两个属性是:$ city-> id和$ city-> name。
My attempts to do this using Blade are failing. 我使用Blade进行此操作的尝试失败。 The issue boils down to: how do I nest @foreach inside of the Blade Form::select statement? 问题归结为:如何在Blade Form :: select语句中嵌套@foreach? For example, without the @foreach, just plunking in a couple of cities, this works perfectly, including a choice of blank, and a default of Albuquerque: 例如,如果没有@foreach,仅在几个城市中乱弹,这将非常有效,包括选择空白和默认的Albuquerque:
{{ Form::open() }}
{{ Form::Label('city_bldg_id','City:') }}
{{ Form::select('city_bldg_id', array(
'',
'2'=>'Albuquerque',
'11'=>'Bernalillo'
),'2') }}
{{ Form::close() }}
In order to populate the select box with all of the values in $city, it would seem that I need to use @foreach inside of the Form::select array. 为了用$ city中的所有值填充选择框,似乎我需要在Form :: select数组中使用@foreach。 Is this possible to do? 这可能吗? If so, how? 如果是这样,怎么办? All of my attempts yield syntax errors. 我所有的尝试都产生语法错误。 Or, must $city be an array and not an object? 还是$ city必须是数组而不是对象?
I am so close I can taste it, but I can't figure out the last step. 我是如此亲密,我可以品尝到它,但是我不知道最后一步。 Any suggestions for the appropriate code would be greatly appreciated. 对于适当的代码的任何建议,将不胜感激。 Thanks! 谢谢!
I generally prefer creating the select data before going to the view. 通常,我更喜欢先创建选择数据,然后再进入视图。 It's easier to read if it's just 如果只是,它更容易阅读
{{ Form::select('city_bldg_id', $cities, '2' }}
(Side note: not sure if you need to enclose the 2
in quotes. Probably not.) (旁注:不确定是否需要将2
括在引号中。可能不需要。)
That way, you can do foreaches all you want in order to create the array, and you can do it in pure PHP instead of in Blade. 这样,您就可以为创建数组所需的所有操作做foreach,并且可以用纯PHP而不是Blade来完成。
One simply way to create the array if you're getting the data from an Eloquent model, eg City
, is the lists()
method: 如果您要从Eloquent模型(例如City
获取数据,则创建数组的一种简单方法是lists()
方法:
$cities = City::lists('name', 'id');
If you need to filter out specific cities, you just do it the normal way: 如果您需要过滤掉特定的城市,则可以按照常规方法进行:
$cities = City::where('somefield', '=', 'value')-> etc... ->lists('name', 'id');
(I hope I'm not assuming too much about what you know already. If this seems too beginnerish and it doesn't help you, I apologise.) (我希望我对您已经知道的事情不承担太多的责任。如果这看起来太入门,并且对您没有帮助,我深表歉意。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.