Как создать один плагин в пользовательском модуле drupal 7? - PullRequest
0 голосов
/ 12 февраля 2019

Я пытаюсь создать собственный плагин для модуля в drupal 7, но у меня возникли проблемы, которые я не могу решить.

Ранее я создал другие плагины, но это провоцирует меня больше проблем, которые я предполагал.

Ну, я создаю любые графики с помощью библиотеки Progressbar.js.Идея состоит в том, чтобы сгенерировать одну диаграмму для каждого плагина, заполнив поля формы из page_manager, например, если я хочу создать 3 диаграммы на любой странице моего сайта, я должен вызвать 3 плагина.

Проблема заключается в том, что когдая захожу на страницу, где должны отображаться диаграммы, генерирую только один график (последний плагин, который я вызываю из панели).

Логика работы заключается в том, что я вводю значения полей через формуплагин.Эти значения отправляются в скрипт для генерации графики с помощью библиотеки ProgressBar.js и, таким образом, визуализации графики в html.

Я заметил, что плагин не отправляет данные в скрипт javascript.Просто отправьте данные в скрипт последнего плагина, который я создал.Предыдущие два нет.Когда я использую console.log в скрипте, получаю значения только из последнего плагина, когда он должен показывать 3 журнала с соответствующими значениями.

Это каталог моего пользовательского модуля.

├── obs_home_page.features.inc
├── obs_home_page.info
├── obs_home_page.module
├── obs_home_page.pages_default.inc
├── plugins
│   └── content_types
│       ├── obs_home_page_show.inc
└── scripts
    └── ProgressBar.js

obs_home_page.module:

<?php
/**
 * @file
 * Code for the Home page feature.
 */

include_once 'obs_home_page.features.inc';

function obs_home_page_ctools_plugin_directory($owner, $plugin) {
    return 'plugins/' . $plugin;
}

obs_home_page_show.inc:

<?php

$plugin = array(
  'single' => TRUE,  // Just do this one, it is needed.
  'title' => t('Relojes'),  // Title to show up on the pane screen.
  'description' => t('Reloj de derecho ipara la portada home'), // Description to show up on the pane screen.
  'category' => t('Custom'), // A category to put this under.
  'edit form' => 'obs_home_page_show_edit_form', // A function that will return the settings form for the pane.
  'render callback' => 'obs_home_page_show_render', // A function that will return the renderable content.
  'admin info' => 'obs_home_page_show_admin_info', // A function that will return the information displayed on the admin screen (optional).
  'defaults' => array( // Array of defaults for the settings form.
    'right' => '',
    'maxValue' => '33',
    'value' => '',
    'description' => ''
  ),
  'all contexts' => TRUE, // This is NEEDED to be able to use substitution strings in your pane.
);

/**
 * An edit form for the pane's settings.
 */
function obs_home_page_show_edit_form($form, &$form_state) {
  $conf = $form_state['conf'];

  $form['right'] = array(
    '#title' => t('Right'),
    '#description' => t('Right ID'),
    '#type' => 'textfield',
    '#required' => TRUE,
    '#default_value' => !empty($conf['right']) ? $conf['right'] : '',
  );

  $form['description'] = array(
    '#title' => t('Description'),
    '#description' => t('Right description'),
    '#type' => 'textfield',
    '#default_value' => !empty($conf['description']) ? $conf['description'] : '',
  );

  $form['maxValue'] = array(
    '#title' => t('Max value'),
    '#description' => t('Max value'),
    '#type' => 'textfield',
    '#size' => 11,
    '#default_value' => !empty($conf['maxValue']) ? $conf['maxValue'] : '',
  );

  $form['value'] = array(
    '#title' => t('Value'),
    '#description' => t('Value'),
    '#type' => 'textfield',
    '#size' => 11,
    '#required' => TRUE,
    '#default_value' => !empty($conf['value']) ? $conf['value'] : '',
  );

  return $form;
}

/**
 * Submit function, note anything in the formstate[conf] automatically gets saved
 * Notice, the magic that automatically does that for you.
 */
function obs_home_page_show_edit_form_submit(&$form, &$form_state) {
  foreach (array_keys($form_state['plugin']['defaults']) as $key) {
    if (isset($form_state['values'][$key])) {
      $form_state['conf'][$key] = $form_state['values'][$key];
    }
  }
}

/**
 * Run-time rendering of the body of the block (content type)
 * See ctools_plugin_examples for more advanced info
 */
function obs_home_page_show_render($subtype, $conf, $panel_args, $context) {
  //Check context and validates input for each config field.

  if (!empty($context) && !empty($conf['right']) && check_plain($conf['right'])) {
    $right = ctools_context_keyword_substitute($conf['right'], array(), $context);
  } else {
    $right = arg(1); //fallback, uses the current nid
  }

  if (!empty($context) && !empty($conf['description']) && check_plain($conf['description'])) {
    $description = ctools_context_keyword_substitute($conf['description'], array(), $context);
  } else {
    $description = null;
  }

  if (!empty($context) && !empty($conf['maxValue']) && check_plain($conf['maxValue'])) {
    $maxValue = ctools_context_keyword_substitute($conf['maxValue'], array(), $context);
  } else {
    $maxValue = null;
  }

  if (!empty($context) && !empty($conf['value']) && check_plain($conf['value'])) {
    $value = ctools_context_keyword_substitute($conf['value'], array(), $context);
  } else {
    $value = null;
  }

  $right = intval($conf['right']);
  $maxValue = intval($conf['maxValue']);
  $value = intval($conf['value']);

  $tid = taxonomy_term_load($right);
  $right_name = $tid->name;
  $right_description = $tid->description;

  if (empty($conf['description'])) {
    $description = $right_description;
  } else {
    $description = $conf['description'];
  }

  $settings = array();
  $settings['clock']['right'] = $right;
  $settings['clock']['maxValue'] = $maxValue;
  $settings['clock']['value'] = $value;

  dsm($settings);
  drupal_add_js($settings, 'setting');

  drupal_add_js(drupal_get_path('module', 'obs_home_page') . '/scripts/ProgressBar.js');
  dsm(drupal_get_path('module', 'obs_home_page') . '/scripts/ProgressBar.js');

  $output = array(
    '#type' => 'markup',
    '#markup' => '<div class="home_page_progressbar">
                  <a href="'. base_path() .'taxonomy/term/'. $right .'">
                    <div id="progressbar-'. $right .'"></div>
                    <h2>'. $right_name .'</h2>
                  </a>
                  <div class="descripcion_clock_right_home">'. $description .'</div>
                  </div>',
  );

  $block = new stdClass();
  $block->title = '';
  $block->content = $output;
  return $block;

}


/**
 * 'admin info' callback for panel pane.
 */
function obs_home_page_show_admin_info($subtype, $conf, $contexts) {
  if (!empty($conf)) {
    $block = new stdClass;
    $block->title = $conf['override_title'] ? $conf['override_title_text'] : '';
    $block->content = t('<strong>Max Value:</strong> @maxValue<br />
      <strong>Value:</strong> @value</p>', 
      array(
        '@maxValue' => $conf['maxValue'],
        '@value' => $conf['value'],
       ));    
    return $block;
  }
}

ProgressBar.js:

/**
 * @file Creacion de relojes para la portada home con libreria ProgressBar
 *
 */

(function ($) {

  Drupal.behaviors.obs_home_page = {
    attach: function (context, settings) {
      GenerarReloj(settings);
    }
  };

  var GenerarReloj = function (settings) {

    var right   = parseInt(settings.clock.right);
    var nominator   = parseInt(settings.clock.value);
    var denominator = parseInt(settings.clock.maxValue);

    var bar_information = new ProgressBar.Circle('#progressbar-' + right, {
    color: '#aaa',
    // This has to be the same size as the maximum width to
    // prevent clipping
    strokeWidth: 10,
    trailWidth: 10,
    easing: 'easeInOut',
    duration: 2000,
    text: {
      autoStyleContainer: false
    },
    from: { color: '#C5DC70', width: 10 },
    to: { color: '#728530', width: 10 },
    // Set default step function for all animate calls
    step: function(state, circle) {
      circle.path.setAttribute('stroke', state.color);
      circle.path.setAttribute('stroke-width', state.width);

      var value = Math.round(circle.value() * denominator);
      if (value === 0) {
        circle.setText('');
      } else {
        circle.setText(value);
      }

    }
  });
  // bar.text.style.fontFamily = '"Raleway", Helvetica, sans-serif';
  bar_information.text.style.fontSize = '3rem';

  var quotient =  nominator / denominator;  

  bar_information.animate(quotient);  // Number from 0.0 to 1.0

  }

})(jQuery);
...