2014-03-25 63 views
0

我有一個視圖模型和控制器的方法:Laravel - 我知道我的ViewModel,所以我可以將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

看看錶單模型結合: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.'); 
} 

只是要注意:您需要使用在後的葉片命令打開形式:

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

的$ timeSheetViewModel是隨便什麼時候您將傳入的工作表視圖模型,以便更新。

+0

它會的!謝謝! – Jimmyt1988

相關問題