drupal_set_message不起作用

时间:2015-03-10 11:41:23

标签: php drupal checkbox drupal-7

我有这些复选框:

   $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);
    }

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

2 个答案:

答案 0 :(得分:0)

这是因为foreach循环中的continue。 <{1}}条件下continue下的所有代码都不会被执行。

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

if

答案 1 :(得分:0)

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

只需将标记设置为FALSE,然后迭代所有复选框,并将标记设置为TRUE(如果有)。循环完成后,如果标志仍为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);
  }
}