Advertisement
Guest User

Untitled

a guest
Feb 29th, 2016
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 7.59 KB | None | 0 0
  1. <?php
  2.  
  3. /*
  4.  * Модуль, отображающий список выбора города
  5.  */
  6.  
  7. function cityfilters_init()
  8. {
  9.     drupal_add_library('system', 'jquery.cookie');
  10.     drupal_add_css(drupal_get_path('module', 'cityfilters') . '/css/cityfilters_style.css');
  11.     drupal_add_js(drupal_get_path('module', 'cityfilters') . '/js/cityfilters_jfunctions.js');
  12. }
  13.  
  14. /**
  15.  *  Implementation of hook_menu()
  16.  */
  17. function example_menu() {
  18.     $items = array();
  19.  
  20.     $items['cityfilters/%ctools_js/select'] = array(
  21.         'title' => t('Select your city'),
  22.         'page callback' => 'cityfilters_callback',
  23.         'page arguments' => array(1),
  24. //        'access arguments' => array('access site-wide contact form'),
  25.         'delivery callback' => 'ajax_deliver',
  26.         'theme callback' => 'ajax_base_page_theme',
  27.     );
  28.  
  29.     return $items;
  30. }
  31. /**
  32.  * @param null $js
  33.  * @return array
  34.  */
  35. function cityfilters_callback($js = NULL) {
  36.  
  37.     // Если у пользователя выключен JavaScript в браузере, то отправляют его на обычную форму обратной связи.
  38.     if (!$js) {
  39.         drupal_goto('#');
  40.     }
  41.  
  42.     // Подключаем библиотеку для работы с модальным окном с помощью ajax команд.
  43.     ctools_include('modal');
  44.     ctools_include('ajax');
  45.  
  46.  
  47.     $commands = array();
  48.  
  49.     // Формируем форму в модальном окне.
  50.     $commands = ctools_modal_command_display(t('Select your city'), 'привет!');
  51.  
  52. //    // Если форма была успешно отправлена, то выводим сообщение об этом и закрываем модальное окно.
  53. //    if (!empty($form_state['executed'])) {
  54. //        $commands = array();
  55. //
  56. //        // Выводим сообщение об успешной отправке формы.
  57. //        $commands[] = ajax_command_html('#messages-wrapper', theme('status_messages'));
  58. //
  59. //        // Закрываем модальное окно.
  60. //        $commands[] = ctools_modal_command_dismiss();
  61. //    }
  62.     $result = ajax_render( $commands);
  63.     dpm($result);
  64.     return  $result;
  65. }
  66.  
  67. function cityfilters_block_info()
  68. {
  69.     $blocks['city_filter'] = array(
  70.         'info' => t('City filter'),
  71.         'cache' => DRUPAL_NO_CACHE,
  72.     );
  73.     $blocks['city_select_popup'] = array(
  74.         'info' => t('Select your City (Popup)'),
  75.         'cache' => DRUPAL_NO_CACHE,
  76.     );
  77.  
  78.     return $blocks;
  79. }
  80.  
  81. /**
  82.  * @param string $delta
  83.  * @return array|bool
  84.  */
  85. function cityfilters_block_view($delta = '')
  86. {
  87.     $block = array();
  88.     if (user_access('access content')) {
  89.         switch ($delta) {
  90.             case 'city_filter':
  91.                 $block['subject'] = t('Select your city');
  92.                 $block['content'] = drupal_get_form('cityfilters_select_city_form');
  93.                 return $block;
  94.             case 'city_select_popup':
  95.                 $block['subject'] = t('Select your city');
  96. //                $block['content'] = cityfilters_select_popup();
  97.                 // В этой функции подключаются необходимые библиотеки, js и css файлы (если нужны), а так же устанавливаются
  98.                 // настройки для модального окна. Эту функцию мы опишем позже
  99.                 _example_include_modal();
  100.                 $block['content'] = ctools_modal_text_button(
  101.                     t('Contact'),
  102.                     'cityfilters/nojs/select',
  103.                     t('Contact'),
  104.                     'ctools-modal-select-city'
  105.                 );
  106.                 return $block;
  107.         }
  108.     }
  109.     return false;
  110. }
  111. function _example_include_modal() {
  112.  
  113.     static $added = FALSE;
  114.     if ($added == FALSE) {
  115.         $added = TRUE;
  116.  
  117.         // Include the CTools tools that we need.
  118.         ctools_include('modal');
  119.         ctools_include('ajax');
  120.         ctools_modal_add_js();
  121.  
  122.         // Создаем массив с настройками для модального окна.
  123.         $example_style = array(
  124.             'example-contact-style' => array(
  125.                 'modalSize' => array(
  126.                     'type' => 'fixed', // Тип модального окна. фиксированный или резиновый.
  127.                     'width' => 420, // Ширина модального окна.
  128.                     'height' => 'auto', // Высота модального окна.
  129.                 ),
  130.                 'modalOptions' => array(
  131.                     'opacity' => (float) 0.3, // Прозрачность фона.
  132.                     'background-color' => '#000000', // Цвет фона.
  133.                 ),
  134.                 'closeText' => '', // Текст для закрытия модального окна.
  135.                 'loadingText' => '', // Текст, отображаемый в момент загрузки модального окна.
  136.                 'animation' => 'fadeIn', // Эффект появления модального окна.
  137.                 'animationSpeed' => 'fast', // Скорость анимации.
  138.             ),
  139.         );
  140.  
  141.         // Подключаем настройки для модального окна.
  142.         drupal_add_js($example_style, 'setting');
  143.     }
  144. }
  145. /**
  146.  * @return mixed
  147.  */
  148. function cityfilters_select_popup()
  149. {
  150.     $cities = cityfilters_get_cities();
  151.     $build['your_city'] = [
  152.         '#type' => 'link',
  153.         '#title' => $cities[$_COOKIE['clicat_city']],
  154.     ];
  155.  
  156.     return $build;
  157. }
  158.  
  159. /**
  160.  * Form constructor for city select form.
  161.  *
  162.  */
  163. function cityfilters_select_city_form($form, &$form_state)
  164. {
  165.     $cities = cityfilters_get_cities();
  166.  
  167.     $form['widget'] = [
  168.         '#type' => 'container',
  169.         '#attributes' => ['class' => ['container-inline']],
  170.     ];
  171.     $form['widget']['city'] = [
  172.         '#type' => 'select',
  173.         '#title' => t('Выберите город'),
  174.         '#title_display' => 'attribute',
  175.         '#options' => $cities,
  176.         '#default_value' => $_COOKIE['clicat_city'],
  177.         '#required' => TRUE,
  178.  
  179.     ];
  180.     $form['widget']['actions'] = ['#type' => 'actions'];
  181.     $form['widget']['actions']['submit'] = [
  182.         '#type' => 'submit',
  183.         '#value' => t('Select'),
  184.         '#id' => 'selectcity-submit',
  185.     ];
  186.     return $form;
  187. }
  188.  
  189. function cityfilters_select_city_form_submit($form, &$form_state)
  190. {
  191. // установка coocies в JS.
  192. //    dpm($_COOKIE);
  193. }
  194.  
  195. /*
  196.  *  Выбираем список городов
  197.  */
  198. function cityfilters_get_cities()
  199. {
  200.     $query = db_select('node', 'n');
  201.     $query->leftJoin('field_data_field_address', 'a', 'n.nid = a.entity_id');
  202.     $query->fields('a', ['field_address_locality']);
  203.     $query->addExpression('COUNT(*)', 'count');
  204.     $query->condition('n.status', '1');
  205.     $query->condition('n.type', 'clinic');
  206.     $query->groupBy('a.field_address_locality');
  207.     $query->orderBy('count', 'DESC');
  208.     $all = $query->execute()->fetchAll();
  209.     $cities = [];
  210.     foreach ($all as $city) {
  211.         $city_name = $city->field_address_locality . ' (' . $city->count . ')';
  212.         $cities[$city->field_address_locality] = $city_name;
  213.     }
  214.     return $cities;
  215. }
  216.  
  217.  
  218. //    $block['subject'] = t('City filter');
  219. //    // Load the view.
  220. //    $view = views_embed_view('catalog', 'attachment_cities');
  221. //    if ($view) {
  222. //      $block['content'] = $view;
  223. //    }
  224. //    else {
  225. //      $block['content'] = t('The view is empty');
  226. //    }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement