1

CakePHP: Validate dependent field (select dropdown + input field)

Posted July 15th, 2010 in CakePHP, PHP, Programming, Projects and tagged , , , , , , , , , , , , by Louie Miranda

Earlier this week, I was working on a project where I needed to validate two dependent fields.

<?php echo input('office', array('type' => 'select', 'options' => $nd[0])); ?>
<?php echo input('office_other', array('maxlength' => '255', 'size' => '35', 'label' => 'Other Office')); ?>

The “office” field is a select (drop down box) from my data array(). What I needed is to be able to add another data from a field and name it as “office_other” where it would initially capture and re-list again new offices if it does not exist.

I found an article on the web that seems to relate on this similar goal here (thanks).

Here’s my code for this project:

Model, where rule validation should be imposed.

var $validate = array(
'office' => array(
  'notempty' => array(
    'rule' => array('notempty'),
    'message' => 'Please select your office.',
    'allowEmpty' => false,
    'required' => true,
  ),
),
'office_other' => array(
  'validateoffice' => array(
    'rule' => array('validateOtherOffice', 'office_other'),
    'message' => 'Kindly enter new office code.'),
  ),

The key here is to add a custom validation process, mine is the validateOtherOffice() function.

function validateOtherOffice($check) {
  $valid = false;
 
  //debug($check);
  //debug($this->data['Account']);
 
  if ($this->data['Account']['office'] == 'office_new') {
    if (empty($check['office_other'])) {
      $valid = false;
    }
    else {
      $valid = true;
    }
  }
  else {
    $valid = true;
  }
 
  return $valid;
}

Now my application was able to validate two dependent fields.

One Response so far.

  1. Hélio says:

    is this the best way?

Leave a Reply