You are here

function masonry_formatter_preprocess_field in Masonry API 7

Implements hook_preprocess_HOOK() for theme_field().

File

masonry_formatter/masonry_formatter.module, line 134
Allows multi-value fields to be displayed in a jQuery Masonry grid.

Code

function masonry_formatter_preprocess_field(&$variables) {
  $element = $variables['element'];

  // Get field formatter settings
  $settings = field_formatter_settings_get_instance_display_settings($element['#entity_type'], $element['#field_name'], $element['#bundle'], $element['#view_mode']);

  // Display field items in a jQuery Masonry grid
  if (!empty($settings['masonry'])) {
    if (($library = libraries_load('masonry')) && !empty($library['loaded'])) {

      // Add default styling to make grids display properly out-of-the-box
      $css_margin = $settings['masonry_width_unit'] == 'px' ? '10px' : '2%';
      $css_width = $settings['masonry_width_unit'] == 'px' ? $settings['masonry_width'] - 20 . 'px' : $settings['masonry_width'] - 5 . '%';
      $grid_styles = '
        .field-name-' . $variables['field_name_css'] . ' .field-item {
          float: left;
          margin: ' . $css_margin . ';
          width: ' . $css_width . ';
        }
      ';
      drupal_add_css($grid_styles, 'inline');
      if ($settings['masonry_center']) {
        $center_styles = '
          .field-name-' . $variables['field_name_css'] . ' .field-items {
            margin: 0 auto;
          }
        ';
        drupal_add_css($center_styles, 'inline');
      }

      // Get column width
      if ($settings['masonry_width_unit'] == 'px') {
        $column_width = (int) $settings['masonry_width'];
      }
      else {
        $percentage = $settings['masonry_width'] / 100;
        $column_width = 'function (containerWidth) {
          return containerWidth * ' . $percentage . ';
        }';
      }

      // Initialize Masonry
      $script = '(function ($) {
        var $container = $(".field-name-' . $variables['field_name_css'] . ' .field-items");
        $container.imagesLoaded(function () {
          $container.masonry({
            itemSelector: ".field-item",
            columnWidth: ' . $column_width . ',
            isAnimated: ' . (int) $settings['masonry_animated'] . ',
            animationOptions: {
              duration: ' . (int) $settings['masonry_animated_duration'] . '
            },
            isResizable: ' . (int) $settings['masonry_resizable'] . ',
            isFitWidth: ' . (int) $settings['masonry_center'] . ',
            gutterWidth: ' . (int) $settings['masonry_gutter'] . ',
            isRTL: ' . (int) $settings['masonry_rtl'] . '
          });
        });
      })(jQuery);';
      drupal_add_js($script, array(
        'type' => 'inline',
        'scope' => 'footer',
      ));
    }
  }
}