Checkboxes with watchdog_severity_levels()

﹥>﹥吖頭↗ 提交于 2020-01-17 12:23:09

问题


I have this code that gets me out some checkboxes with the watchdog severities:

  /**
   * Checkbox for errors, alerts, e.t.c
   */
  foreach (watchdog_severity_levels() as $severity => $description) {
    $key = 'severity_errors' . $severity;
    $form['severity_errors'][$key] = array(
      '#type' => 'checkbox',
      '#title' => t('@description', array('@description' => drupal_ucfirst($description))),
      '#default_value' => variable_get($key, array()),  
    );
    return system_settings_form($form);
  }

I set this $key in my code as:

$key = array_filter(variable_get($key,array()));

I think this set is wrong as the drupal gets me out error. After that set of $key I call it with the following foreach statement could someone help me with that thing?

foreach ($key as $value) {
  if ($value == 'warning') {
    blablblablabla....
  }
  elseif ($value == 'notice') {
    blablablbalbal....
  }
}

回答1:


Using your logic, you would store following keys severity_errors0, severity_errors1, severity_errors2, ... in the variable table because the $severity key of your foreach is just the index.

Wouldn't it be easier to store an array of selected severity levels as one entry in the variable table?

Here some example code which does the job for you:

// Retrieve store variable
$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),
    ));
}

// Generate checkbox list for given severity levels
$form['severity_levels'] = array(
    '#type' => 'checkboxes',
    '#options' => $severity_options,
    '#default_value' => array_values($severity_levels),
);

return system_settings_form($form);

Now to retrieve the selected severity levels, you do something like this:

// Retrieve store variable
$severity_levels = variable_get('severity_levels', array());

foreach ($severity_levels as $level => $selected) {
    if (!$selected) {
        // Severity level is not selected
        continue;
    }

    // Severity level is selected, do your logic here
    // $level
}



回答2:


You need to add some debugging to figure out where exactly it's going wrong. Would recommend using dpm() to inspect the code at some of the key stages like 1) after building the form, 2) when you assign the array to $key and 3) before starting the final foreach loop so you can pinpoint where it's going wrong and address it.



来源:https://stackoverflow.com/questions/28896332/checkboxes-with-watchdog-severity-levels

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!