drupal_set_message 无效

drupal_set_message do not work

我有这些复选框:

   $severity_levels = variable_get('severity_levels', array());

      // Declare empty options array
      $severity_options = array();

      // Loop through each severity level and push to options array for form
      foreach (watchdog_severity_levels() as $severity) {
        $severity_options[$severity] = t('@description', array(
          '@description' => drupal_ucfirst($severity),
        ));
      }
    $form['severity']['severity_levels'] = array(
          '#type' => 'checkboxes',
          '#options' => $severity_options,
          '#default_value' => array_values($severity_levels),
      );

我打电话给他们,我想在没有检查任何内容时发出此错误消息:

$severity_levels = variable_get('severity_levels', array());

  foreach ($severity_levels as $level => $selected) {
    if (!$selected) {
      continue;
      $message = 'You must select at least one severity';
      $type = 'error';
      drupal_set_message($message, $type);
      watchdog($type, $message);
    }

但它不起作用.....我的错在哪里?

这是因为foreach循环中的continueif条件下continue下的所有代码都不会执行。

此代码可以进一步帮助您。它基本上是在未选择安全级别时设置消息。

$has_error = null;
foreach ($severity_levels as $level => $selected) {
    if (!$selected) {
        $has_error = $has_error === null || $has_error === true 
            ? true : false;

        continue;
    }

    $has_error = false;
}

if ($has_error) {
    $message = 'You must select at least one severity';
    $type = 'error';

    drupal_set_message($message, $type);
    watchdog($type, $message);
}

尝试使用 continue 语句优化这样的循环不值得增加复杂性。

只需将标志设置为 FALSE,然后遍历所有复选框并将标志设置为 TRUE(如果选中)。循环完成后,如果flag还是FALSE,则触发错误

试试这个:

function yourform_validate($form, &$form_state) {
  $checked = FALSE;

  $severity_levels = $form_state['values']['severity_levels'];
  foreach ($severity_levels as $level => $selected) {
    if ($selected) { $checked = TRUE; }
  }

  if ($selected === FALSE) {
    $message = 'You must select at least one severity.';
    $type = 'error';
    drupal_set_message($message, $type);
    watchdog($type, $message);
  }
}