2

The code add settings for commerce_mymodule (for example) commerce payment module. Can I validate 'mymodule_deadline' variable and how?

/**
 * Payment method callback: settings form.
 */
function commerce_mymodule_settings_form($settings = NULL) {
  $settings = (array) $settings + array(
    'mymodule_min' => '',
    'mymodule_secret' => '',
    'site_mode' => 'DEMO_MODE'
  );

  $form = array();

  $form['mymodule_deadline'] = array(
    '#type' => 'textfield',
    '#title' => t('Order payment deadline'),
    '#description' => t('Deadline for payment - default 7 days (max. 30 days).'),
    '#default_value' => $settings['mymodule_deadline'],
  );

  return $form;
}
2

I found a solution - because it is a FORM I using the FORMAPI. More accurate hook_form_alter() to add my custom validation handler and next is trivial. Code:

/**
 * Implements hook_form_alter()
 */
function commerce_mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'rules_ui_edit_element') {
    if ($form_state['element_settings']['payment_method']['method_id'] == 'commerce_mypaymentmethod') {
      $form['#validate'][] = 'commerce_mypaymentmethod_settings_validate';
    }
  }
}

and validation function

function commerce_mymodule_settings_validate(&$form, &$form_state) {  
  $deadline = (int) $form_state['values']['parameter']['payment_method']['settings']['payment_method']['settings']['mymodule_deadline'];

  if ($deadline < 1 || $deadline > 30) {
    form_set_error('', t('Enter only digit positive value between 1 -30 (days) in Order payment deadline. @value', array('@value' => $deadline)));
  }
}
1

The easiest way to validate an individual form element is to use the #element_validate property:

$form['application_login'] = array(
  '#type' => 'textfield',
  '#title' => t('Application Login'),
  '#default_value' => decrypt($settings['application_login']),
  '#required' => TRUE,
  '#element_validate' => array('_commerce_qbms_element_validate_encrypt'),
);

/**
 * Validates form elements.
 */
function _commerce_qbms_element_validate_encrypt($element, &$form_state, $form) {
  form_set_value($element, encrypt($element['#value']), $form_state);
}

In this specific case of validating a Drupal Commerce payment method setting element, the solution provided by @svetlio was not adequate for my needs. This was due to the fact that I needed to encrypt my element's value before sending to the database, and for whatever reason (I suspect the Rules module), this was not possible using his solution.

This is also the solution provided by the creators of Drupal Commerce: https://drupal.org/node/1179626

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.