我HotelAddress型號:條件驗證
<?php
class HotelAddress extends AppModel {
var $name = 'HotelAddress';
var $belongsTo = array(
'Hotel' => array(
'className' => 'Hotel'
)
);
var $validate = array(
'address' => array(
'rule' => 'notEmpty',
)
);
我HotelModel
<?php
class Hotel extends AppModel {
var $name = 'Hotel';
var $hasAndBelongsToMany = array(
'HotelCategory' => array(
'className' => 'HotelCategory'
)
);
var $belongsTo = array(
'Page' => array(
'className' => 'Page'
)
);
var $hasMany = array(
'HotelAddress' => array(
'className' => 'HotelAddress',
'dependent' => TRUE
),
'HotelPhone' => array(
'className' => 'HotelPhone',
'dependent' => TRUE
)
);
筆者認爲:
<div id="main">
<h2>Add Hotel</h2>
<?php echo $this->Session->flash();?>
<div>
<?php
echo $this->Form->create('Hotel');
echo $this->Form->input('Hotel.name');
echo $this->Form->input('HotelCategory', array('options' => $hotel_categories, 'multiple' => 'checkbox'));
echo $this->Form->input('HotelAddress.0.address');
echo $this->Form->input('HotelAddress.1.address');
echo $this->Form->input('HotelAddress.2.address');
echo $this->Form->input('HotelPhone.0.phone');
echo $this->Form->input('Page.meta_keywords');
echo $this->Form->input('Page.meta_description');
echo $this->Form->end('Save Hotel');
?>
</div>
<!-- main ends -->
</div>
我的問題是,我並不需要驗證對方HotelAddress
ES 。如果用戶填寫了至少一個地址,則應該進行驗證。但是,如果他沒有填滿,應該顯示一個錯誤。
我相信我應該在beforeSave
方法中添加代碼,但我不知道應該在那裏做什麼。
更新:
我現在有這樣的HotelAddress模式運作在沒有驗證的其他地址的存在(如果可用)。但是,它仍然可以節省。
var $existing_address = FALSE;
var $validate = array(
'address' => array(
'rule' => 'checkOnce',
)
);
function checkOnce($check) {
if (isset($this->data['HotelAddress']['address'])) {
if (! empty($this->data['HotelAddress']['address'])) {
return $this->existing_address = TRUE;
} else {
unset($this->data['HotelAddress']['address']);
return $this->existing_address;
}
}
return $this->existing_address;
}
這幾乎是我所做的。雖然我做了一個循環,因爲地址將由JavaScript生成,所以我不知道會有多少。 – 2011-02-10 06:51:00