使用Laravel 4,如果会话密钥是指定值,如何将单选按钮标记为已选中?

时间:2015-02-13 03:48:49

标签: php forms laravel radio-button blade

我有一个多页表单,带有两个具有相同名称属性的单选按钮。当我选择一个并单击下一步按钮时,我将该单选按钮的值保存到具有表单字段名称和所选值的会话数组中。如果用户回到页面,我想要检查先前选择的单选按钮。

这就是我提出的:

查看:choose-listing-type.blade.php

<div class="form-group">
  <?php $checked_status = Session::get('listing_form_data.type') === 'property' ? true : false; ?>
  {{ Form::radio('type', 'property', $checked_status) }} Create Property Listing
</div>

<div class="form-group">
  <?php $checked_status = Session::get('listing_form_data.type') === 'room' ? true : false; ?>
  {{ Form::radio('type', 'room', $checked_status) }} Create Room Listing
</div> 

这很有效,但看起来很草率。首先,我不认为检查会话值的if语句应该在视图中,我希望在刀片中找到一种方法。

使用Laravel 4,根据指定会话密钥的值,将radiobutton标记为已检查的最佳做法是什么?

2 个答案:

答案 0 :(得分:2)

为什么不直接将条件权限与表单助手一起使用,如下所示:

<div class="form-group">
  {{ Form::radio('type', 'room', (Session::get('listing_form_data.type') === 'room') ? true : false) }} Create Room Listing
</div>

我个人认为从视图中检查会话设置没有任何问题......

答案 1 :(得分:2)

由于您提到您想在控制器中执行此操作:

$type = Session::get('listing_form_data.type');
return View::make('view')->with('type', $type);

查看:

{{ Form::radio('type', 'property', $type === 'property') }} Create Property Listing
{{ Form::radio('type', 'room', $type === 'room') }} Create Room Listing

甚至:

$type = Session::get('listing_form_data.type');
$isProperty = ($type === 'property');
$isRoom = ($type === 'room');
return View::make('view')->with(compact('isProperty', 'isRoom'));

查看:

{{ Form::radio('type', 'property', $isProperty) }} Create Property Listing
{{ Form::radio('type', 'room', $isRoom) }} Create Room Listing