2014-01-28 143 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.'); 
     } 
    }