Ubercart – Enforce unique SKUs in Attributes Adjustment

After you have enable the Product attribute module, you could adjust the SKU for products having different attributes. But there is no validation to check the SKU uniqueness. I try to enforce the checking by creating a custom module.

custom.module

function custom_form_alter(&$form, &$form_state, $form_id) {
  // Unique SKU check
  if ($form_id == 'uc_product_adjustments_form') {
    $form['#validate'][] = 'unique_sku_validate';
  }
}

function unique_sku_validate($form, $form_state) {
  //print_r($form_state);
  
  // Get the current SKUs
  $current_skus = array();
  $this_skus = array();
  $sql = "SELECT nid, model FROM uc_product_adjustments";
  $result = db_query($sql);
  while ($row = db_fetch_object($result)) {
    if ($row->nid != $form_state['values']['nid']) {
      $current_skus[] = $row->model;
    } else {
      $this_skus[] = $row->model;
    }
  }
  
  $message = "Some SKUs already exists:";
  $has_error = FALSE;
  $user_inputs = array();
  foreach($form_state['values']['body'] as $sku) {
    if (in_array($sku['model'], $current_skus)) {
      $message .= $sku['model'] . '; ';
      $user_inputs[] = $sku['model'];
      $has_error = TRUE;
    }
  }

  // Show error if SKUs already exist in DB
  if ($has_error) {
    form_set_error('body', $message);
  }
  
  // Show error if the user inputs have duplicated entries
  if (has_dupes($this_skus)) { 
    form_set_error('body', "Duplicated entries.");
  }
}

function has_dupes($array) {
  $dupe_array = array();
  foreach($array as $val){
    if(++$dupe_array[$val] > 1){
      return true;
    }
  }
  return false;
}

 

Done =)

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.