2017-02-17 66 views
0

我正在使用的應用程序(訂單)允許用戶在iframe中輸入多個子記錄。這些子記錄通過外鍵連接到主記錄。CakePHP:在提交父表單前檢查iframe中的訂單項

main_records    line_items 
-----------     ----------  
id int(11) PK etc.   id int(11) PK etc. 
          main_record_id (FK) 

我需要應用程序來檢查表單提交之前是否至少有一個訂單項存在於此iframe中。我想利用模型中的$ validate功能,但我不確定如何繼續。以下是我在主要模型中試過的內容:

App::uses('AppModel', 'Model', 'LineItem'); 

public $hasMany = array(
    'LineItem' => array(
     'className' => 'LineItem', 
     'foreignKey' => 'main_record_id', 
     'dependent' => false 
    ) 
); 

public $validate = array(
    'main_record_id' = array(
     'allowEmpty' => false, 
     'rule' => 'checkForLineItem', 
     'message' => 'You must enter at least one line item!' 
    ) 
); 

//Check to make sure there is at least one line item before saving changes/submitting for approval 
function checkForLineItem($id) { 
    $lines = $this->LineItem->find('all', array(
     'fields' => array('LineItem.main_record_id'), 
     'conditions' => array('LineItem.main_record_id'=>$id, 'LineItem.deleted_record'=>0)) 
    ); 
    if(!empty($lines)) { 
     return true; 
    } else { 
     return false; 
    } 
} 

我還會跟蹤訂單項是否已被刪除。如果有,那麼它不會被添加到$行。

我知道我可以在控制器中完成這項工作,但據我所知,這將需要表單發佈,並且用戶在回發時將失去任何更改(我尚未在此表單上實現jQuery) 。我在正確的軌道上如何做到這一點?我應該做些什麼才能使其發揮作用?

回答

0

你的代碼看起來是正確的,但驗證確實發生在表單提交中。如果你想在之前檢查它,你必須在JavaScript(jQuery)中做。例如。創建一個控制器動作,如果給定的主記錄ID存在現有行項目並通過AJAX調用它,則返回該動作。