2011-10-21 47 views
0

我有一個表單,它從幾個模型中收集信息,這些模型在它們的關聯中分開幾層。出於這個原因,我必須單獨保存每一個,並且如果有任何失敗,則向視圖報告以便顯示錯誤消息。由於連續保存,我假設,任何錯誤都不正確顯示,我也不會發現方法正在捕捉錯誤的存在。從視圖中訪問invalidFields

任何想法如何在視圖級別訪問這些數據來檢查錯誤?我想驗證所有3個模型,以便我可以同時顯示所有錯誤,並避免爲此創建手動數據結構和測試。是否有我可以訪問的本機Cake功能/數據,因此這不是一個完全自定義的解決方案,我無法在更傳統的實例中使用它?

# Controller snippet 
if($this->Proposal->Requestor->saveField('phone_number', $this->data['Requestor']['phone_number']) && $this->Proposal->Requestor->Building->saveAll($this->data)) { 
    # Save off the proposal and message record. 
    exit('saved'); 
}  
else { 
    $this->Session->setFlash('We can\'t send your quote just yet. Please correct the errors below.', null, null, 'error'); 
    # At this point, I may have 2 or more models with validation errors to display 
} 

# Snippet from an element loaded into the view 
# $model = Requestor, but the condition evaluates to false 
<?php if($this->Form->isFieldError($model . '.phone_number')): ?> 
    <?php echo $this->Form->error($model . '.phone_number') ?> 
<?php endif; ?> 

謝謝。

回答

0

這是開源軟件的神奇之處。有一點在源代碼中發現,$this->Form->isFieldError最終從名爲$validationErrors的視圖變量中讀取。在進行獨立保存時,我只需在我的控制器操作中通過相同名稱寫入本地變量並手動設置。因此,非常規過程被映射到常規結果,並且視圖代碼不需要識別任何類型的定製結構。

# Compile our validation errors from each separate 
$validationErrors = array(); 
if(!$this->Proposal->Requestor->validates(array('fieldList' => array_keys($this->data['Requestor'])))) { 
    $validationErrors['Requestor'] = $this->Proposal->Requestor->validationErrors; 
} 
if(!$this->Proposal->Requestor->Building->saveAll($this->data)) { 
    $validationErrors = Set::merge($validationErrors, $this->Proposal->Requestor->Building->validationErrors); 
} 

if(empty($validationErrors)) { 
    # TODO: perform any post-save actions 
} 
else { 
    # Write the complete list of validation errors to the view 
    $this->set(compact('validationErrors')); 
} 

如果有更好的方法來做到這一點,請讓我知道。至少目前來看,這似乎是正確的。