cakephp - Conditional validation -
my hoteladdress model:
<?php class hoteladdress extends appmodel { var $name = 'hoteladdress'; var $belongsto = array( 'hotel' => array( 'classname' => 'hotel' ) ); var $validate = array( 'address' => array( 'rule' => 'notempty', ) );
my 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 ) );
my view:
<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>
my problem don't need validate other hoteladdress
es. if user fills @ least 1 of addresses, should validate. however, if doesn't fill any, error should show.
i believe should adding code on beforesave
method don't have idea on should there this.
update:
i have in hoteladdress model works not validating existence of other addresses if 1 available. however, still saves.
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; }
i'd go in controller before calling save
:
if (empty($this->data['hoteladdress'][1]['address'])) { unset($this->data['hoteladdress'][1]['address']); } if (empty($this->data['hoteladdress'][2]['address'])) { unset($this->data['hoteladdress'][2]['address']); }
Comments
Post a Comment