2014-01-28 96 views
0

我想要弄清楚如何在一個視圖中保存4天的日程安排,並在驗證失敗時顯示每個字段驗證消息。cakephp,保存同一模型的多行

我的方法是第一次使用$this->SomeModel->saveAll(),但無法保存,所以我嘗試了另一種方式,使用foreach並保存所有數據(通過驗證),但未顯示驗證消息。如果你們知道更好的方法來做到這一點,我願意提供任何建議。

模型

public $validate = array(
    'hour_from'=>array(
     'some mgs' => array(
      'rule' => 'good_hours', 
     ), 
    ), 
); 
public function good_hours($data) { 
    //throw new Exception(($data['hour_from'] >= $this->data['Hour']['hour_to'])); 
    if ($data['hour_from'] >= $this->data['Hour']['hour_to']) { 
     return false; 
    } 
    return true; 
} 

控制器:

if ($this->request->is('post')) { 
     $all_good = true; 
     foreach ($this->request->data['Hour'] as $day){ 

      if ($this->Hour->save($day)){ 

      }else { 
       $all_good = false; 
       $this->Session->setFlash('hours not saved'); 
      } 
     } 
     //if all saves are correct rediredt to index 
     if ($all_good) { 
      $this->Session->setFlash(__('Hours saved')); 
      return $this->redirect(array('action' => 'index')); 
     } 
    } 

查看

foreach ($days as $count => $day): 
$form_model ='Hour.'.$count. '.'; 
?> 
<fieldset> 
    <legend><?php 
    $day_array = (array) $day; 
    $day = $day_array['date']; 
    echo $day; 
    ?></legend> 
<?php 
    echo $this->Form->input($form_model.'type_holiday_id', array(
    'label'=> 'Typ urlopu', 
    'type' => 'select', 
    'options' => $type_holidays, 
    'empty' => true 
    )); 
    echo $this->Form->input($form_model.'hour_from', array('label' => 'od')); 
    echo $this->Form->input($form_model.'hour_to', array('label' => 'do')); 
    echo $this->Form->input($form_model.'date', array('type' => 'hidden', 'value' => $day)); 
    echo $this->Form->input($form_model.'subordinate_id', array('type' => 'hidden', 'value' => $user['User']['id'])); 
    echo $this->Form->input($form_model.'supervisor_id', array('type' => 'hidden', 'value' => $current_user['id'])); 

?> 
</fieldset> 

請求 - >數據陣列

Hour(array) 
0(array) 
    type_holiday_id 
    hour_from 8 
    hour_to 15 
    date 2014-01-20 
    subordinate_id 193 
    supervisor_id 557 
1(array) 
    type_holiday_id 
    hour_from 7 
    hour_to 14 
    date 2014-01-21 
    subordinate_id 193 
    supervisor_id 557 
+0

我覺得白水()方法將是你最好在這裏下注 - 同一模型的多行是這種方法的用例。 '$ day'數組是什麼樣的?我敢打賭,你的問題是數組的格式。至於視圖上的驗證顯示,您可能需要直接調用它。我似乎回想起過去有類似的問題,我最終使用validate()方法在失敗時將數據返回給視圖。 –

回答

1

好吧,我找到的解決方案,而現在一切都完美的作品在控制器我需要改變savesaveAll,功能add在控制器應該是這樣的:

if ($this->request->is('post')) { 
     if ($this->Hour->saveAll($this->request->data['Hour'], Array('validate' => 'first', 'deep' => true))){ <--- most important is that data['Hour'] 
      $this->Session->setFlash(__('Godziny robocze zapisane')); 
      return $this->redirect(array('action' => 'index')); 
     } else{ 
      $this->Session->setFlash('Godziny robocze nie zostały zapisane.'); 
     } 
    }