Laravel - 我知道我的ViewModel,所以我可以将ViewModel传递给控制器​​参数吗?

时间:2014-03-25 15:06:56

标签: php laravel

我有一个ViewModel和一个控制器方法:

class TimesheetViewModel
{
    public /* TimesheetTotals */ $TimesheetTotals;
    public /* TimesheetEntry[] */ $Timesheets = array();   
    public /* int */ $AmountOfTimesheetEntries = 1;
}

...
public /* void */ function GetCreate()
{
    ...
    $timesheetViewModel = new TimesheetViewModel();
    ...            

    $timesheetViewModel->TimesheetTotals = $timesheetLogic->ColumnSum( $timesheetEntries );
    $timesheetViewModel->AmountOfTimesheetEntries = count( $timesheetEntries );
    $timesheetViewModel->Timesheets = $timesheetEntries;
    return View::make( 'Timesheet/Create', array( "Model" => $timesheetViewModel ) );
}
...

我的视图中有一个表单,它在我的视图模型中具有完美的属性复制功能...... 有没有办法在我的控制器中有这样的东西:

...
public /* void */ function PostCreate( TimesheetViewModel $timesheetViewModel )
{
    // This will help because I do not have to do Input::all
    // and then map it (Or not map it at all and stick with 
    // an array that could change when someone is working on 
    // the form fields mucking things up) ?
}
...

1 个答案:

答案 0 :(得分:1)

看看表单模型绑定:http://laravel.com/docs/html#form-model-binding

由于您的表单在模型中具有完美的属性复制功能,因此您可以在控制器中执行以下操作:

public function update($id)
{
    $timesheetViewModel = TimeSheetViewModel::find($id);

    if (!$timesheetViewModel->update(Input::all())) {
        return Redirect::back()
                ->with('message', 'Your time sheet was unable to be saved')
                ->withInput();
    }

    return Redirect::route('timesheet.success')
                ->with('message', 'Your timesheet was updated.');
}

需要注意的一点是:您需要使用以下Blade命令打开表单:

{{ Form::model($timeSheetViewModel, array('route' => array('timeSheetViewModel.update', $timeSheetViewModel->id))) }}

$ timeSheetViewModel只是您要传递的任何时间表视图模型,以便更新。