How do I create a link to a view in Commerce Order listing?

I needed to call views_embed_view in my own page callback because I needed to pass the commerce order id for my contextual filter.  Here is what I did:

I first defined the menu item.  Note that the path has %commerce_order instead of just %. This is needed to access the order object which has the id.

When creating the view, I put in in a separate path, not the path I used for the $items.  When I tried to use the same path, it didn't work.  I think it is because the $items path is needed to create the listing in the dropdown menu.

I defined the path of my view as something that was not admin/commerce/orders/%commerce_order/takehomeitems
It is important that your view have a contextual filter which takes the order id. My path was /admin/hubadmin/takehomeitems/%

See the bottom of my posted answer for the exported view example.

Then in hook_menu, i defined the following:

 $items['admin/commerce/orders/%commerce_order/takehomeitems'] = array(
   'title' => 'Take Home Items',
   'page callback' => '_bh_donate_takehome_lineitems',
   'page arguments' => array(3),
   'access callback' => 'bh_donate_takehomeorder_access',
   'access arguments' => array(3),
   'type' => MENU_LOCAL_TASK,
   'weight' => 10,
   'context' => MENU_CONTEXT_INLINE,
 );

I then defined the page callback which calls views_embed_view and by passing in the %commerce_order, I am able to get the order id

function _bh_donate_takehome_lineitems($order) {
  return views_embed_view('YOURVIEWNAME', 'YOURDISPLAYID', $order->order_id);
} //DISPLAYID is usually default. To find this out, choose to export your view and look at $handler = $view->new_display('default', 'Master', 'default'); The last parameter is the display id.

This creates a item in the dropdown menu of the order which links to a view. The breadcrumb path points to the order.

Here is my exported view that worked for an example.

$view = new view();
    $view->name = 'bh_view_customer_donation_line_item';
    $view->description = '';
    $view->tag = 'default';
    $view->base_table = 'commerce_order';
    $view->human_name = 'BH View: Customer Take Home Line Items';
    $view->core = 7;
    $view->api_version = '3.0';
    $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

    /* Display: Master */
    $handler = $view->new_display('default', 'Master', 'default');
    $handler->display->display_options['title'] = 'Customer Take Home Line Items';
    $handler->display->display_options['use_more_always'] = FALSE;
    $handler->display->display_options['access']['type'] = 'none';
    $handler->display->display_options['cache']['type'] = 'none';
    $handler->display->display_options['query']['type'] = 'views_query';
    $handler->display->display_options['exposed_form']['type'] = 'basic';
    $handler->display->display_options['pager']['type'] = 'full';
    $handler->display->display_options['pager']['options']['items_per_page'] = '10';
    $handler->display->display_options['style_plugin'] = 'table';
    $handler->display->display_options['style_options']['columns'] = array(
        'vendor_user_reference' => 'vendor_user_reference',
        'commerce_product' => 'commerce_product',
        'quantity' => 'quantity',
        'commerce_unit_price' => 'commerce_unit_price',
        'commerce_total' => 'commerce_total',
    );
    $handler->display->display_options['style_options']['default'] = '-1';
    $handler->display->display_options['style_options']['info'] = array(
        'vendor_user_reference' => array(
            'sortable' => 0,
            'default_sort_order' => 'asc',
            'align' => '',
            'separator' => '',
            'empty_column' => 0,
        ),
        'commerce_product' => array(
            'sortable' => 0,
            'default_sort_order' => 'asc',
            'align' => '',
            'separator' => '',
            'empty_column' => 0,
        ),
        'quantity' => array(
            'sortable' => 0,
            'default_sort_order' => 'asc',
            'align' => '',
            'separator' => '',
            'empty_column' => 0,
        ),
        'commerce_unit_price' => array(
            'sortable' => 0,
            'default_sort_order' => 'asc',
            'align' => '',
            'separator' => '',
            'empty_column' => 0,
        ),
        'commerce_total' => array(
            'sortable' => 0,
            'default_sort_order' => 'asc',
            'align' => '',
            'separator' => '',
            'empty_column' => 0,
        ),
    );
    $handler->display->display_options['style_options']['empty_table'] = TRUE;
    /* Relationship: Commerce Order: Referenced line items */
    $handler->display->display_options['relationships']['commerce_line_items_line_item_id']['id'] = 'commerce_line_items_line_item_id';
    $handler->display->display_options['relationships']['commerce_line_items_line_item_id']['table'] = 'field_data_commerce_line_items';
    $handler->display->display_options['relationships']['commerce_line_items_line_item_id']['field'] = 'commerce_line_items_line_item_id';
    /* Relationship: Commerce Line item: Referenced products */
    $handler->display->display_options['relationships']['commerce_product_product_id']['id'] = 'commerce_product_product_id';
    $handler->display->display_options['relationships']['commerce_product_product_id']['table'] = 'field_data_commerce_product';
    $handler->display->display_options['relationships']['commerce_product_product_id']['field'] = 'commerce_product_product_id';
    $handler->display->display_options['relationships']['commerce_product_product_id']['relationship'] = 'commerce_line_items_line_item_id';
    /* Field: Commerce Product: Vendor User Reference */
    $handler->display->display_options['fields']['vendor_user_reference']['id'] = 'vendor_user_reference';
    $handler->display->display_options['fields']['vendor_user_reference']['table'] = 'field_data_vendor_user_reference';
    $handler->display->display_options['fields']['vendor_user_reference']['field'] = 'vendor_user_reference';
    $handler->display->display_options['fields']['vendor_user_reference']['relationship'] = 'commerce_product_product_id';
    $handler->display->display_options['fields']['vendor_user_reference']['label'] = 'Vendor ';
    $handler->display->display_options['fields']['vendor_user_reference']['element_type'] = '0';
    $handler->display->display_options['fields']['vendor_user_reference']['element_label_colon'] = FALSE;
    $handler->display->display_options['fields']['vendor_user_reference']['element_wrapper_type'] = '0';
    $handler->display->display_options['fields']['vendor_user_reference']['element_default_classes'] = FALSE;
    $handler->display->display_options['fields']['vendor_user_reference']['field_api_classes'] = TRUE;
    /* Field: Commerce Line item: Product */
    $handler->display->display_options['fields']['commerce_product']['id'] = 'commerce_product';
    $handler->display->display_options['fields']['commerce_product']['table'] = 'field_data_commerce_product';
    $handler->display->display_options['fields']['commerce_product']['field'] = 'commerce_product';
    $handler->display->display_options['fields']['commerce_product']['relationship'] = 'commerce_line_items_line_item_id';
    $handler->display->display_options['fields']['commerce_product']['element_type'] = '0';
    $handler->display->display_options['fields']['commerce_product']['element_label_colon'] = FALSE;
    $handler->display->display_options['fields']['commerce_product']['element_wrapper_type'] = '0';
    $handler->display->display_options['fields']['commerce_product']['element_default_classes'] = FALSE;
    $handler->display->display_options['fields']['commerce_product']['type'] = 'commerce_product_reference_sku_link';
    $handler->display->display_options['fields']['commerce_product']['settings'] = array(
        'show_quantity' => 0,
        'default_quantity' => '1',
        'combine' => 1,
        'show_single_product_attributes' => 0,
        'line_item_type' => 'product',
    );
    $handler->display->display_options['fields']['commerce_product']['field_api_classes'] = TRUE;
    /* Field: Commerce Line Item: Quantity */
    $handler->display->display_options['fields']['quantity']['id'] = 'quantity';
    $handler->display->display_options['fields']['quantity']['table'] = 'commerce_line_item';
    $handler->display->display_options['fields']['quantity']['field'] = 'quantity';
    $handler->display->display_options['fields']['quantity']['relationship'] = 'commerce_line_items_line_item_id';
    /* Field: Commerce Line item: Unit price */
    $handler->display->display_options['fields']['commerce_unit_price']['id'] = 'commerce_unit_price';
    $handler->display->display_options['fields']['commerce_unit_price']['table'] = 'field_data_commerce_unit_price';
    $handler->display->display_options['fields']['commerce_unit_price']['field'] = 'commerce_unit_price';
    $handler->display->display_options['fields']['commerce_unit_price']['relationship'] = 'commerce_line_items_line_item_id';
    $handler->display->display_options['fields']['commerce_unit_price']['element_type'] = '0';
    $handler->display->display_options['fields']['commerce_unit_price']['element_label_colon'] = FALSE;
    $handler->display->display_options['fields']['commerce_unit_price']['element_wrapper_type'] = '0';
    $handler->display->display_options['fields']['commerce_unit_price']['element_default_classes'] = FALSE;
    $handler->display->display_options['fields']['commerce_unit_price']['click_sort_column'] = 'amount';
    $handler->display->display_options['fields']['commerce_unit_price']['settings'] = array(
        'calculation' => FALSE,
    );
    $handler->display->display_options['fields']['commerce_unit_price']['field_api_classes'] = TRUE;
    /* Field: Commerce Line item: Total */
    $handler->display->display_options['fields']['commerce_total']['id'] = 'commerce_total';
    $handler->display->display_options['fields']['commerce_total']['table'] = 'field_data_commerce_total';
    $handler->display->display_options['fields']['commerce_total']['field'] = 'commerce_total';
    $handler->display->display_options['fields']['commerce_total']['relationship'] = 'commerce_line_items_line_item_id';
    $handler->display->display_options['fields']['commerce_total']['element_type'] = '0';
    $handler->display->display_options['fields']['commerce_total']['element_wrapper_type'] = '0';
    $handler->display->display_options['fields']['commerce_total']['element_default_classes'] = FALSE;
    $handler->display->display_options['fields']['commerce_total']['click_sort_column'] = 'amount';
    $handler->display->display_options['fields']['commerce_total']['settings'] = array(
        'calculation' => FALSE,
    );
    $handler->display->display_options['fields']['commerce_total']['field_api_classes'] = TRUE;
    /* Contextual filter: Commerce Line Item: Order ID */
    $handler->display->display_options['arguments']['order_id']['id'] = 'order_id';
    $handler->display->display_options['arguments']['order_id']['table'] = 'commerce_line_item';
    $handler->display->display_options['arguments']['order_id']['field'] = 'order_id';
    $handler->display->display_options['arguments']['order_id']['relationship'] = 'commerce_line_items_line_item_id';
    $handler->display->display_options['arguments']['order_id']['default_action'] = 'empty';
    $handler->display->display_options['arguments']['order_id']['title_enable'] = TRUE;
    $handler->display->display_options['arguments']['order_id']['title'] = 'Order %1';
    $handler->display->display_options['arguments']['order_id']['default_argument_type'] = 'fixed';
    $handler->display->display_options['arguments']['order_id']['summary']['number_of_records'] = '0';
    $handler->display->display_options['arguments']['order_id']['summary']['format'] = 'default_summary';
    $handler->display->display_options['arguments']['order_id']['summary_options']['items_per_page'] = '25';
    /* Filter criterion: Commerce Product: Vendor User Reference (vendor_user_reference) */
    $handler->display->display_options['filters']['vendor_user_reference_uid']['id'] = 'vendor_user_reference_uid';
    $handler->display->display_options['filters']['vendor_user_reference_uid']['table'] = 'field_data_vendor_user_reference';
    $handler->display->display_options['filters']['vendor_user_reference_uid']['field'] = 'vendor_user_reference_uid';
    $handler->display->display_options['filters']['vendor_user_reference_uid']['relationship'] = 'commerce_product_product_id';
    $handler->display->display_options['filters']['vendor_user_reference_uid']['operator'] = 'not empty';
    /* Filter criterion: Commerce Line Item: Type */
    $handler->display->display_options['filters']['type']['id'] = 'type';
    $handler->display->display_options['filters']['type']['table'] = 'commerce_line_item';
    $handler->display->display_options['filters']['type']['field'] = 'type';
    $handler->display->display_options['filters']['type']['relationship'] = 'commerce_line_items_line_item_id';
    $handler->display->display_options['filters']['type']['value'] = array(
        'product' => 'product',
    );

    /* Display: Page */
    $handler = $view->new_display('page', 'Page', 'page');
    $handler->display->display_options['path'] = 'admin/hubadmin/takehome-items/%';


Different domain names to site languages

the simple way will be to use .htaccess

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{HTTP_HOST} ^litebook.de$ [OR]
  RewriteCond %{HTTP_HOST} ^www.litebook.de$
  RewriteRule (.*)$ http://litebook.de/de/$1 [R=301,L]
  RewriteCond %{HTTP_HOST} ^litebook.co.uk$ [OR]
  RewriteCond %{HTTP_HOST} ^www.litebook.co.uk$
  RewriteRule (.*)$ http://litebook.eu/en/$1 [R=301,L]
</IfModule>


How to use FULL Jquery.com files in Drupal content item?

All you need is to enable the jQuery Update module, which provides support for all jQuery UI versions for Drupal 7 to jQuery 1.5.x, 1.7.x, 1.8.x, 1.9.x, 1.10.x, 2.1.x and jQuery UI 1.10.2.


A 502 Bad Gateway error can mean a lot of things, however, if you had the site working OK and then it stopped after changing things in the database, then it basically points to a problem with the way PHP is interpreting things in the database.

You'll need to look at your PHP configuration to find where the PHP error log is on the server and then look into that error log to understand what the problem is.
There is a chance that the error is being recorded into Drupal's watchdog, usually available at admin/reports/dblog - if you can't view that inside the website you could use drush with the drush ws command to see items in watchdog, or just use SELECT * FROM watchdog ORDER BY wid DESC LIMIT 20; at a sql client to see the contents of the watchdog table.

The 502 error indicates there is a problem, but doesn't indicate the specific problem. If you post more details from your PHP error log it will be easier to help you fix it.


Changing the path of jQuery to use a CDN instead of the local file system

Add the following code in the template.php file of your theme. (Replace mytheme with the actual short name of your theme.)

function mytheme_js_alter(&$javascript) {
  $javascript['misc/jquery.js']['type'] = 'external';
  $javascript['misc/jquery.js']['data'] = 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js';
}

As you are replacing the copy of the jQuery library with the same version copy hosted on Google, it doesn't make much sense to do it for just a theme. It would make sense to change it independently from the theme used from Drupal.

If you plan to use a different version of the library, you should first check there aren't incompatibilities with the jQuery version, and JavaScript code used from Drupal, or third-party modules. In case of incompatibilities, some JavaScript files used by Drupal could need to be replaced (using hook_js_alter()). That is what the jQuery Update module does.


The D8 equivalent is cache tags and it kind of works in the reversed way.

What exactly is changing that requires you to invalidate the cache? Identify that, if it has a cache tag (e.g. a config object or an entity) then just make sure your block adds the cache tag for it and you're done.

To figure out if a cache tag invalidation happens, you can truncate the cachetags table, then make the change and check that table for new entries.

If there is no cache tag yet for that event, then you can define one yourself, add it to the render array or getCacheTags() of the block plugin and invalidate it with Cache::invalidateTags().

I would not recommend to do what @Clive suggested because unlike 7.x, your  block plugin (assuming it is a plugin not just one specific block instance) can be re-used many times, even with page_manager/panels.


Why is my custom module giving a "page not found" message when using https?

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

or take a look at this article


Remember View results on a browser back button click

The answer to this question should include a "non-Drupal" part since what happens when you click the "Back" button is browser-related.

What happens on the browser

I'm not an expert on the subject, but basically all browsers add the last request that you did in a "history cache" and pressing the "Back" and "Forward" buttons moves you backward or forward in this "cache".

In general, AJAX requests are not included in this cache but this is browser specific (I think that I have read somewhere that Safari in some cases does store AJAX requests). You can find various resources on how this works for different browsers if you look it up on google (keywords could be: "back button ajax calls", along with the name of the browser that you are looking for).

Views' "Remember last selection" setting

For your specific question there are 2 things that you should notice:

Views do allow you to store the last selection by the user in the Exposed Filters' settings. The setting's name is: "Remember the last selection". This setting also allows you to limit the roles for which the last selection will be remembered.
The browser does not really care what Views do and, at least in the case of Chrome (probably other browsers do the same too), returns its cached version of the page (aka minus ajax calls).

You can test the above-mentioned assertion by setting the last selection option, hitting the back button (you will see the browser-cached version of the page) and then hitting the refresh button (browser will request the page again and views will kick-in and enforce the application of the last used filters).

Solution

The google search "back button ajax calls" could give you a lot of relevant results but if you want to test the famous Drupal notion: "There is a module for that", there actually is and its name is "Views AJAX History". It depends on the history.js javascript library and the Libraries API module.

Proof of concept

I have quickly created a dev site that I can use for my answers here and added 50 nodes with devel generate. You can see a sample view here that has AJAX enabled. After you have filtered the view using the "Body contains" exposed filter with a sample string like "oppeto" you will instantly see what Views AJAX History does: the call is being made through AJAX but the URL on your browser changes to include the exposed filters' values and is stored in your browser's history cache.

Now, when you click on a node link and then hit the "Back" browser button, you get returned to the correct, filtered version of the view (tested it on Chrome but you can test it on any browser that you want to make sure that it works as expected).

Important Warnings

I have used this module on a couple of sites that I have built and the thing that bothered me the most is the fact that it has a known, unsolved conflict with the core Overlay module. It was not a very big deal for me since I could afford to disable Overlay at these specific cases but you should definitely consider this if you rely heavily on Overlay. For example, if you rely on Overlay Paths to show colorbox-like popups, you will find yourself in a world of hurt.

I am considering using Views AJAX History on one of my core projects but in order to do this, I will have to take a stab at the issue that I mentioned before. In any case, you can monitor the progress of the specific issue or even try to create a patch yourself.


Display entity images with thumbnails and 1 large image

<?php

/**
 * @file
 * Contains \Drupal\mymodule\Plugin\Field\FieldFormatter\SlickMyentityGalleryFormatter.
 */

namespace Drupal\mymodule\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Component\Utility\Html;

/**
 * @FieldFormatter(
 *   id = "slick_myentity_gallery",
 *   label = @Translation("Slick Myentity Gallery"),
 *   field_types = {
 *     "image"
 *   }
 * )
 */
class SlickMyentityGalleryFormatter extends FormatterBase {

  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    return [
      'visible_slides' => 3,
      'image_style' => 'thumbnail',
      'arrows' => TRUE,
      'dots' => TRUE,
      'fade' => FALSE,
      'standalone_image' => TRUE,
      'standalone_location' => 'above',
      'standalone_style' => 'xlarge',
      'vertical' => FALSE,
      'lazy_load' => 'ondemand',
      'hide_single_navigator' => TRUE
    ] + parent::defaultSettings();
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $element = parent::settingsForm($form, $form_state);
    $field_name = $this->fieldDefinition->getName();

    $image_style_entities = \Drupal::entityManager()
      ->getStorage('image_style')
      ->loadMultiple();

    $image_styles = array_map(function($image_style) {
      return $image_style->label();
    }, $image_style_entities);

    $image_styles = ['_original' => '- ' . $this->t('Original') . ' -'] + $image_styles;

    $element['visible_slides'] = [
      '#type' => 'number',
      '#title' => $this->t('Number of visible slides'),
      '#default_value' => $this->getSetting('visible_slides'),
      '#min' => 1,
      '#max' => 10,
      '#description' => $this->t('Number of images visible at once.')
    ];

    $element['image_style'] = [
      '#type' => 'select',
      '#title' => $this->t('Image style'),
      '#default_value' => $this->getSetting('image_style'),
      '#options' => $image_styles,
      '#description' => $this->t('Image style to display the images with.')
    ];

    $element['arrows'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Show arrows'),
      '#default_value' => $this->getSetting('arrows'),
      '#description' => $this->t('Display the navigation arrows.')
    ];

    $element['dots'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Paging'),
      '#default_value' => $this->getSetting('dots'),
      '#description' => $this->t('Display the paging dots.')
    ];

    $element['fade'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Fade'),
      '#default_value' => $this->getSetting('fade'),
      '#description' => $this->t('Fade between transitions.')
    ];

    $element['vertical'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Vertical slider'),
      '#default_value' => $this->getSetting('vertical'),
      '#description' => $this->t('Display slider vertically instead of horizontally.')
    ];

    $element['lazy_load'] = [
      '#type' => 'select',
      '#title' => $this->t('Lazy load'),
      '#options' => [
        'none' => '- ' . $this->t('None') . ' -',
        'ondemand' => $this->t('On demand'),
        'progressive' => $this->t('Progressive')
      ],
      '#default_value' => $this->getSetting('lazy_load'),
      '#description' => $this->t('Lazy load the images to increase page performance.')
    ];

    $element['standalone_image'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Standalone active image'),
      '#default_value' => $this->getSetting('standalone_image'),
      '#description' => $this->t('Display the active image separately.')
    ];

    $element['standalone_style'] = [
      '#type' => 'select',
      '#title' => $this->t('Standalone image style'),
      '#default_value' => $this->getSetting('standalone_style'),
      '#options' => $image_styles,
      '#description' => $this->t('Image style to display the standalone image with.'),
      '#states' => [
        'visible' => [
          "input[name=\"fields[$field_name][settings_edit_form][settings][standalone_image]\"]" => [
            'checked' => TRUE
          ]
        ]
      ]
    ];

    $element['standalone_location'] = [
      '#type' => 'select',
      '#title' => $this->t('Standalone image location'),
      '#default_value' => $this->getSetting('standalone_location'),
      '#options' => [
        'above' => $this->t('Above'),
        'below' => $this->t('Below'),
        'left' => $this->t('Left'),
        'right' => $this->t('Right')
      ],
      '#description' => $this->t('Display slider vertically instead of horizontally.'),
      '#states' => [
        'visible' => [
          "input[name=\"fields[$field_name][settings_edit_form][settings][standalone_image]\"]" => [
            'checked' => TRUE
          ]
        ]
      ]
    ];

    $element['hide_single_navigator'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Hide single item carousel'),
      '#default_value' => $this->getSetting('hide_single_navigator'),
      '#description' => $this->t('If standalone image is displayed and there is only one image, the carousel will be hidden.'),
      '#states' => [
        'visible' => [
          "input[name=\"fields[$field_name][settings_edit_form][settings][standalone_image]\"]" => [
            'checked' => TRUE
          ]
        ]
      ]
    ];

    return $element;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsSummary() {
    $summary = parent::settingsSummary();

    if ($this->getSetting('standalone_image')) {
      $standalone_style = $this->getSetting('standalone_style');
      if ($standalone_style == '_original') {
        $summary[] = $this->t('Display standalone image without image style.');
      } else {
        $style = \Drupal::entityManager()->getStorage('image_style')->load($standalone_style);
        $summary[] = $this->t('Display standalone image with %style image style.', [
          '%style' => $style ? $style->label() : 'original'
        ]);
      }

      $location = $this->getSetting('standalone_location');
      $location_labels = [
        'above' => $this->t('above'),
        'below' => $this->t('below'),
        'left' => $this->t('left'),
        'right' => $this->t('right')
      ];
      $summary[] = $this->t('Standalone image position: %position.', [
        '%position' => $location_labels[$location]
      ]);

      if ($this->getSetting('hide_single_navigator')) {
        $summary[] = $this->t('Hide carousel with single image.');
      }
    }

    $image_style = $this->getSetting('image_style');
    if ($image_style == '_original') {
      $summary[] = $this->t('Display images without image style.');
    } else {
      $style = \Drupal::entityManager()->getStorage('image_style')->load($image_style);
      $summary[] = $this->t('Display images with %style image style.', [
        '%style' => $style ? $style->label() : 'original'
      ]);
    }

    if ($this->getSetting('vertical')) {
      $summary[] = $this->t('Display slider vertically.');
    }

    switch ($this->getSetting('lazy_load')) {
      case 'ondemand':  $summary[] = $this->t('Use on demand lazy loading.'); break;
      case 'progressive':  $summary[] = $this->t('Use progressive lazy loading.'); break;
    }

    return $summary;
  }

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {
    // Skip if there are no items to display.
    if ($items->isEmpty()) {
      return [];
    }

    $standalone_html_id = Html::getUniqueId($items->getName() . '-standalone');
    $carousel_id = Html::getUniqueId($items->getName() . '-nav');
    $lazy_load = $this->getSetting('lazy_load');
    $use_lazy_load = $lazy_load != 'none';

    // Retrieve file IDs.
    $fids = [];
    foreach ($items->getIterator() AS $item) {
      $fids[] = $item->get('target_id')->getValue();
    }

    // Load files so we can get their URIs.
    $files = \Drupal::entityManager()->getStorage('file')->loadMultiple($fids);

    // Make a list of all URIs.
    $uris = array_map(function($file) {
      return $file->getFileUri();
    }, $files);

    // Set up the render element.
    $element = [
      '#attached' => [
        'library' => [
          'mymodule/slick_myentity_gallery'
        ]
      ]
    ];

    // Create carousel for the standalone image if needed.
    if ($this->getSetting('standalone_image')) {
      $element['#attributes']['class'][] = 'with-standalone';

      $element['standalone'] = [
        '#theme' => 'item_list',
        '#items' => [],
        '#weight' => 0,
        '#attributes' => [
          'id' => $standalone_html_id,
          'class' => [
            'slick-myentity-gallery',
            'slider-standalone',
            'location-' . $this->getSetting('standalone_location')
          ],
          'data-slick-settings' => json_encode([
            'slidesToShow' => 1,
            'slidesToScroll' => 1,
            'arrows' => FALSE,
            'fade' =>  TRUE,
            'asNavFor' => '#' . $carousel_id,
            'lazyLoad' => $lazy_load,
            'mobileFirst' => TRUE
          ])
        ]
      ];

      foreach ($uris AS $uri) {
        $element['standalone']['#items'][] = $this->getImageItem($uri, $this->getSetting('standalone_style'), $use_lazy_load);
      }
    }

    // Create the main image carousel.
    $element['carousel'] = [
      '#theme' => 'item_list',
      '#items' => [],
      '#weight' => 1,
      '#attributes' => [
        'id' => $carousel_id,
        'class' => [
          'slick-myentity-gallery',
          'slider-navigation',
          $this->getSetting('vertical') ? 'vertical' : 'horizontal'
        ],
        'data-slick-settings' => json_encode([
          'slidesToShow' => (int) $this->getSetting('visible_slides'),
          'slidesToScroll' => 1,
          'asNavFor' => '#' . $standalone_html_id,
          'dots' => (bool) $this->getSetting('dots'),
          'arrows' => (bool) $this->getSetting('arrows'),
          'fade' => (bool) $this->getSetting('fade'),
          'vertical' => (bool) $this->getSetting('vertical'),
          'verticalSwiping' => (bool) $this->getSetting('vertical'),
          'focusOnSelect' => TRUE,
          'lazyLoad' => $lazy_load,
          'mobileFirst' => TRUE,
          'rtl' => \Drupal::languageManager()->getCurrentLanguage()->getDirection() == 'rtl',
          'infinite' => FALSE
        ])
      ]
    ];

    foreach ($uris AS $uri) {
      $element['carousel']['#items'][] = $this->getImageItem($uri, $this->getSetting('image_style'), $use_lazy_load);
    }

    // Display the carouse first if the standalone image is visible and
    // is positioned below the carousel or to the right next to it.
    if ($this->getSetting('standalone_image') && in_array($this->getSetting('standalone_location'), ['below', 'right'])) {
      $element['carousel']['#weight'] = -1;
    }

    // Hide navigator if standalone image is displayed and there is only
    // one image.
    if ($this->getSetting('standalone_image') && $this->getSetting('hide_single_navigator') && $items->count() == 1) {
      unset($element['carousel']);
    }

    return [$element];
  }

  /**
   * Helper method to generate image for provided style
   * that takes the lazy load setting into account.
   *
   * @param string $uri
   *   The original image uri.
   * @param string $image_style
   *   The image style name.
   * @param bool $lazy_load
   *   If TRUE the lazy slick load image will be returned.
   *
   * @return array
   *   Renderable array for a single image.
   */
  function getImageItem($uri, $image_style, $lazy_load = FALSE) {
    if ($lazy_load) {
      $style = \Drupal::entityManager()
        ->getStorage('image_style')
        ->load($image_style);

      return [
        '#type' => 'inline_template',
        '#template' => '',
        '#context' => [
          'path' => $style ? $style->buildUrl($uri) : file_create_url($uri)
        ]
      ];
    } else {
      return [
        '#theme' => 'image_style',
        '#uri' => $uri,
        '#style_name' => $image_style
      ];
    }
  }

}

(function($) {

  Drupal.behaviors.slickMyentityGallery = {
    attach: function(context) {
      // Initialize the Slick Carousel on all appropriate elements.
      $('.slick-myentity-gallery[data-slick-settings]', context).once('slick-myentity-gallery-init').each(function() {
        var $this = $(this);
        var settings = $this.data('slick-settings');

        // Adjust behavior if this is a Field API field.
        var $fapi_items = $this.find('.field__item');
        if ($fapi_items.length != 0) {
          $fapi_items.parent().slick( settings );
        } else {
          $this.slick( settings );
        }
      });
    }
  }

})(jQuery);


How to make Localization update believe that the translation of a local .po-file is not up to date?

Figured it out!

After changing the last updated timestamp for, you need to refresh the information.  The following sequence of commands works:

$ touch my_project.7.x-1.x.nb.po
$ drush l10n-update-refresh
$ drush l10n-update-status
…
my_project (7.x-1.x)   Local update available
…

Editing the embedded timestamps POT-Creation-Date and PO-Revision-Date is not required and have no effect.


How to add an image gallery to content type

This might be of interest to you. It uses a content type and views for each user.
Add a gallery for every user in a block If you require further assistance please let me know. The answer is quite detailed and is broken up step by step. What version of Drupal are you using.


Gmap won't show infobubbles when clicking markers (with View Module)

I just found the issue myself through googling better. Sorry

https://www.drupal.org/node/2241573#comment-10493640

Some bad code at line 999 of the gmap.module file, remove this and it will work :)


How to integrate the Piwik web statistics tracking system in a Drupal site?

Even better, use the drupal module that does all the hard work - Piwik Web Analytics.
Here is a quote about it (from the module's project page):

... Adds the Piwik web statistics tracking system to your website.
The module allows you to add the following statistics features to your site:

Single/multi domain tracking
Selectively track/exclude certain users, roles and pages
Monitor what type of links are tracked (downloads, outgoing and mailto)
Monitor what files are downloaded from your pages
Cache the Piwik code on your local server for improved page loading times
Custom variables support with tokens (D7 only)
Custom code snippets
Site Search
Drupal messages tracking
Modal dialog tracking (Colorbox)
Access denied (403) and Page not found (404) tracking
User ID tracking across devices
DoNotTrack support


Get submitted value of a select list error on #options - Drupal 7

Thanks to tenken and Clive I was able to figure it out.

$key1 = $form_state['values']['field_setup_time3'];

This line outputted as a string. Since I was only using integers in my select list, the label and key value were the same. I removed both lines of code and replaced it with this (after some playing around with devel):

$reservationStartPadding = $form_state['values']['field_setup_time3']['und'][0]['value'];

This outputted the value as a number and not as a string. I was able to use it from there in my future code correctly.


Not quite a block, but you can do this with custom panel panes and pass it the $node being viewed.  This is the cleanest way.  I don't have a link handy for an overview on how to do this, though.

You can also do something similar using a view, and wiring up the relationships / arguments appropriately.  You can then stick this view into a panel pane.

The hack is do do something like this in your block code

if (arg(0) == "node" && arg(2) != "edit") {
  $nid = (int) arg(1);
  if ($nid) {
    // do stuff
  }
}


I stumbled upon the same issue with Drupal 8.2.6: A 404 error was recorded even though my custom event subscriber was called.
Following what suggested in comments I read about the Redirect module, I set the event subscriber priority using the following code.
public static function getSubscribedEvents() {
  // This needs to run before RouterListener::onKernelRequest(), which has
  // a priority of 32. Otherwise, that aborts the request if no matching
  // route is found.
  $events[KernelEvents::REQUEST][] = array('onKernelRequest', 34);

  return $events;
}

This fixed the issue I was having.


There are a couple of modules that do this

Redirect 403 to Login: https://www.drupal.org/project/r4032login
Anonymous Login: https://www.drupal.org/project/anonymous_login
You could probably also do it with the Rules module
Simplest: You can also go to admin/config/system/site-information and set the "Default 403 (access denied) page" to "/user/login"

This page was old, but looked like it had been updated along the way for Drupal 8.


Edit button on content which users have permissions to edit, including their profile

Contextual Links are a Permission that can be enabled for different roles via admin/people/permissions. If enabled, it will only show the options that user has access to.

If I wanted to add my own custom buttons in different situations, I'd start with Display Suite which allows me to create custom fields (which might be my buttons) and show/hide those buttons based on View Mode, content type, etc.


The syntax error comes from key being a MySQL reserved keyword.
The best solution is to not use these keywords as identifiers.
 Otherwise the workaround is to enclose them in backticks.

It may work like this:

  [...]
  ->insertFields(array(
           'uid' => $this->user->uid,
            'tid' => $data['tid'],
            '`key`'    => $key,
            'value'    => $value
    ) )
   [...]

However this fails at cross-database compatibility since the backtick is a MySQL-only syntax. Better rename the column if possible.


How to store user specific data after registration?

users are a "fieldable entity" in Drupal 7. Just go to "configuration / people / account settings / manage fields" and add your fields. Make sure to check the "Display on user registration form" box.

For the "place of residence" I recommend the addressfield or location modules.


How to display all users except current user?

I was able to make a view that displayed all the users while excluding the current user.  Here is a screenshot of the settings I used:

Note that the important filter here is the "User: Current (No)".  That is the one you'll need to have.


If the content was created it's also there in the database. Most obvious reason for you not finding it, would be silly mistakes, like a typo in the search, or you looked in the wrong database (either created the node the wrong place or looking in the wrong database).

It's not possible to have a node in a drupal site that doesn't exist in the database unless you believe in fairies ;)


Is it possible to change the path of modules/themes installed using an installation profile?

If you have already installed the profile — no, you can't move modules by modifying make file. Profile's .make file is used only during installation process.

If you want to replace modules from profiles/%PROFILE_NAME%/modules/ to sites/all/modules on already installed copy of Drupal, you can just replace files (with mv or something) and then run system_rebuild_module_data() function to ask Drupal to update modules destination. With Drush:

drush eval "system_rebuild_module_data();"

For profile installation process — I really don't know why and don't know how to modify .make file. Maybe you can specify 'contrib_destination' property for every project?


pm-update fails "sh: --backend=2: command not found"

This is happening because Drush is trying to find the local Drush executable via $drush = realpath($_SERVER['argv']['0']);.  In this context, realpath is returning FALSE, because $_SERVER['argv']['0'] does not exist.

As a workaround for this particular problem (which is that pm-update cannot call updatedb), you could run drush pm-updatecode followed by drush updatedb.

Note

If you work around the problem instead of solving it, you will also run into this same issue with other commands, such as sql-sync.


Website styles in general are coded through CSS.

Drupal implements that through themes. If you're using the default Bartik theme you can override the navigation item spacing with the margin property on the list items.

It's not recommended to modify an existing theme file if you need to adjust its style. The best practice is to create a subtheme based on the original and include the modifications in the subtheme so they override the original one.

If you're not knowledgable in themeing or CSS you can make small CSS adjustments with the help of a module like CSS Editor. This way you don't have to worry about themes or subthemes, the code will always apply.

You can try something like:

#main-menu-links li {
  margin-right: 20px;
}

You may have to clear your CSS cache in Drupal to see the changes, if you have the CSS aggregated under Performance.


Top 10 priorities in performance optimization of a complex Drupal site

I won't talk about APC and other Apache optimization tricks.

In in experience:

Enable caching for Views and reduce use of Views
Enable Javascript and CSS compression
Minimize the modules. Disable unused ones. In production I disable as UI's .. the
following script will give you some help.
Most of bottleneck comes from Mysql. I suggest you optimize it and I found this post useful.

Disable User Interface Modules

When not developing you can safely disable Field UI, Rules UI, Views UI, dblog etc. Also I'm sure but we should also be able to disable CKEditor/FCKEditors.

This is what I use in a script:

drush dis --yes admin_menu advanced_help backup_migrate content_type_overview  dashboard diff environment_indicator field_ui help module_filter rules_ui search term_merge update views_bulk_operations views_ui vppr  field_ui  rules_admin devel site_audit  drupalgeddon l10n_client taxonomy_manager dblog


How do I add COUNT(foo.bar) to a dynamic query?

@MEsch is right about the method to call, but I would rather write the code as the following.

$query = db_select('taxonomy_term_data', 't')
  ->fields('t', array('tid', 'name', 'description'));

$alias = $query->leftjoin('taxonomy_index', 'i', '%alias.nid = t.nid');

$query->addExpression("COUNT($alias.nid)", 'count');
$query->range(0, 60)->groupBy("$alias.nid");

SelectQuery::leftJoin() returns the alias effectively used in the query, and the code I wrote is more generic.

As for calling SelectQuery::addExpression() before SelectQuery::leftJoin(), the result doesn't change, if you are not using the alias returned from SelectQuery::leftJoin(). The following queries return both the same result.

$query = db_select('taxonomy_term_data', 't')
  ->fields('t', array('tid', 'name', 'description'));
$query->leftjoin('taxonomy_index', 'i', 'i.nid = t.nid');
$query->addExpression("COUNT(i.nid)", 'count');
$query->range(0, 60)->groupBy("i.nid");

$query = db_select('taxonomy_term_data', 't')
  ->fields('t', array('tid', 'name', 'description'));
$query->addExpression("COUNT(i.nid)", 'count');
$query->leftjoin('taxonomy_index', 'i', 'i.nid = t.nid');
$query->range(0, 60)->groupBy("i.nid");

When you print $query, you get the following, in both the cases.

SELECT t.tid AS tid, t.name AS name, t.description AS description, COUNT(i.nid) AS count
FROM
{taxonomy_term_data} t
LEFT OUTER JOIN {taxonomy_index} i ON i.nid = t.nid
GROUP BY i.nid
LIMIT 60 OFFSET 0


How do I trigger group membership was granted for a user - Group module

as @Jaypan suggested to me,
I used hook_ENTITY_TYPE_insert()
so my code is:
function hook_group_content_insert(GroupContentInterface $group_content) {
  if ($group_content->hasField('entity_id')
    && !$group_content->get('entity_id')->isEmpty()) {
    $users = $group_content->get('entity_id')->referencedEntities();
    $user = reset($users);
    if ($user instanceof UserInterface) {
      // Do your code here.
    }
  }
}


Hiding group_group field programmatically

You should be able to hide the group_group field with the $form['group_group']['#access'] = FALSE; this is used by the Hide checkbox on the field settings page and this is how it works.

However, if you testing as an anonymous user maybe you have this issue: https://www.drupal.org/project/og/issues/2278003 there's a patch which fixes the access itself.


Is there a way to order views grouped fields?

How I resolved this
I don't know what I did wrong in the first place here, as after having removed sorts from my view and added them again the ordering is fine, and not complicated at all
Summary
If you are contructing a view of nodes, grouped by taxonomy term, and using the grouped field (term:title) as views accordion headers, then you can easily sort the accordion headers by taxonomy title/weight, and their child items by node title. To do this add a first sort criteria for term:title/weight(asc), and a second sort criteria for Content:title(asc).
I opted for a sort based on weight in the end, as I can always reset vocabulary weights to alphabetical order, and this allows the editors a bit of free choice if they need to prioritise the list.


Several field templates or on node template?

I would never recommend Contemplate to someone who needs true control over the output.

Here is what I usually do:

I make php stuff and logic stuff on the node_preprocess, only sending to node.tpl variables ready to be echoed, or arrays to be foreach'ed and then printed, in the case of cck fields with multiple values.

And I never run functions of any type on node.tpl.php. If you need to run a function, run it on preprocess!

Using this approach my templates become faster, as they can take take a little more advantage of the internal template caching system, and also, my node.tpl.php gets REALLY easy for me and others to understand it.


You're not returning any markup from the theme function. The purpose of a theme function is to optionally accept some arguments and return markup. Here's an example of a theme function returning markup.

For more information see Overriding themable output.


How to remove "Drupal" from title of page?

Drupal by default will put the site name at the end of the page title but specific themes might change this.

if you want to override this your best bet is to use https://www.drupal.org/project/metatag module and override appropriate settings

There is a setting for first page or for all content types or specific content types; it very configurable.

Or you might do it programmatically in your THEMENAME.theme file:

function THEMENAME_preprocess_html(&$variables) {
    $variables['head_title']['name'] = "Another Name";
}

To take away the | you have to create a new html.html.twig template in your custom theme and modify (copy paste it from the theme you are overriding)

    <title>{{ head_title|safe_join(' | ') }}</title>

to something like this

    <title>{{ head_title|safe_join('  ') }}</title>


How can I programmatically add webform elements to an existing webform?

So I spent a full day investigating on something similar. Kudos to @jrockowitz for providing the right direction. Below is something I wrote to work.

$webforms = \Drupal::entityTypeManager()
  ->getStorage('webform')
  ->loadByProperties([]);

$new_field = [
   'new_field'=>[ '#type' => 'textfield',
     '#title' => 'Question one',]];

foreach ($webforms as $webform) {
     // Applying to all forms.
      if (!in_array('new_field', $webform->getElementsDecoded())) {
        // $webform->getElementsDecoded() will get all the previous elements of the webform.
        $new_element_arrangment = array_merge($webform->getElementsDecoded(), $new_field);
        $webform->setElements($new_element_arrangment)->save();
    }
}


How to associate User data with custom module?

As usual there are plenty of ways to do something with Drupal.
Of course it would be possible to create a content type and import it via Feeds but sometimes (in case it might become plenty of data) it could be better to use a different approach.

So far it seems I'd go with MongoDB, the appropriate module and get the data into the DB using JSON and try to relate that to the current user if or where needed. Due to the amount of data and the visualisation it seems to be better to go the Document DB way.


You can use the following code. (Add error checking where necessary.)

  $image_url = parse_url(theme_get_setting('logo'));
  $image_path = str_replace(base_path(), realpath(DRUPAL_ROOT) . '/', $image_url['path']);
  $info = image_get_info($image_path);
  $height = $info['height'];
  $width = $info['width'];

As side note, theme_get_settings('logo_path') returns the path of the uploaded file used as logo. While theme_get_settings('logo') always return a value, whatever the logo is the default one, or one that has been uploaded, theme_get_settings('logo_path') returns a value when the logo has been uploaded.
The value returned for "logo_path" is similar to public://logo.png. To obtain the real path, you would use code similar to the following one.

  if ($image_uri = theme_get_settings('logo_path')) {
    if ($wrapper = file_stream_wrapper_get_instance_by_uri($image_uri)) {
      $image_path = $wrapper->realpath();
    }
    elseif (!empty($image_uri)) {
      $image_path = realpath($image_uri);
    }
  }


Populate multiselect options onchange of dropdown using AJAX

Have you tried one of the following modules?

Multiselect (this one suits the most)

Hierarchical Select (relatively easy to configure)

Conditional Fields (requires separate dropdown lists)

A combination of Multiselect and Hierarchical Select will mostly help you achieve what you have shown.

Regards,

Supriya Rajgopal


How to an Add to cart Button to a Content Type?

Below are 2 possible alternatives for setting up a simple shopping cart without using the Drupal Commerce or Ubercart modules (as in your "I don't want a huge functionality like Drupal commerce does. No products, products sku.").
Option 1: A lightweight e-shop
If you're only looking for a simple and lightweight e-commerce solution, have a looking at the Light Shop module (for D7, not for D6, not (yet?) for D8). Here is a quote from its project page:

Session-stored basket.
Adding to basket and its subsequent editing/checkout process is done using AJAX. Also it works fine when JavaScript is turned off.
Node based shopping. As the product can be assigned to any node type. One or more. With full support Field API features (regarding nodes).
Orders history. For each order will be created a separate node.
There is no dependence on other modules.
Full support for working with anonymous users
Integration with Views.

Option 2: A simple shopping cart
If you're only looking for a shopping cart, have a looking at the Basic Cart module (for D7, not for D6, not (yet?) for D8). Here is a quote from its project page:

Basic cart is a very simple shopping cart / checkout process for Drupal, that just sends 2 emails after each order. Along with the shopping cart, this module also provides a block where you can view your cart's content. It's ideal for small websites with only a few products or other content types being sold, for example touristic offers.
Main difference from Ubercart and Commerce:
The main difference from Ubercart and Commerce is the possibility of choosing the content types that can be added to the cart. It also doesn't bother you with the Product SKU, that can be a pain when you have just a few products.
Features:

The possibility of choosing the content types that can be added to the cart.
The possibility of sending, or not, an email to the customer once an order is placed.
Custom email messages for both the site administrator and the customer, along with the order details.
Order registration and listing in the administration area using Views module.
Integration with Rules module.
A block with the contents of your shopping cart.

Here is a screenshot of it (note the "Checkout" button also ...):

Note: According to "Payment/Basic Cart integration" it should be possible to integrate this module with the Payment module. Though that integration is still outstanding. So while waiting for that to ever get delivered, it looks like you'll have to investigate yourself to what extend this Payment module is usable in your case without that integration. As an alternative: contact the module owner to see what kind of sponsorship may get it delivered soom.


There are two different page caches.

The Internal Dynamic Page Cache works with all kind of elements like blocks and nodes and is uses the cache tags, cache contexts and cache max-age provided by these elements.

The Internal Page Cache is for complete pages for anonymous users and only uses cache tags.

You can control the page cache for anonymous users with one parameter.

Go to the perfomance configuration:

admin/config/development/performance

And configure the page cache maximum age with the time how long your information is valid. This is also important for proxies and the browser cache, because it would not help to invalidate the drupal cache, if the page is cached in other places. After that time the page expires and should be built again. According to the documentation:

  Configuring the internal page cache On the Performance page, you can
  configure how long browsers and proxies may cache pages; that setting
  is also respected by the Internal Page Cache module. There is no other
  configuration.

But this is not true. You should configure this time for proxies and browser cache, but the internal page cache does not respect the time you set there. The only reliable solution I found is to uninstall the module Internal Page Cache or set an expire time in an EventSubscriber (for example 3600 sec in the future):

/src/EventSubscriber/SetExpiresSubscriber.php

<?php

namespace Drupal\mymodule\EventSubscriber;

use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class SetExpiresSubscriber implements EventSubscriberInterface {

  public function onResponse(FilterResponseEvent $event) {
    $request = $event->getRequest();
    $response = $event->getResponse();
    if ($event->isMasterRequest()) {
      $request_time = $request->server->get('REQUEST_TIME');
      $expires_time = (new \Datetime)->setTimestamp($request_time + 3600);
      $response->setExpires($expires_time);
    }
  }

  public static function getSubscribedEvents() {
    $events[KernelEvents::RESPONSE][] = ['onResponse'];
    return $events;
  }

}

mymodule.services.yml

services:
  mymodule.setexpires:
    class: Drupal\mymodule\EventSubscriber\SetExpiresSubscriber
    tags:
      - { name: event_subscriber }


Is there a hook for custom line item before rules price calculation?

As Clive mentioned, there's hook_commerce_product_calculate_sell_price_line_item_alter() that lets you manipulate the line item prior to the sell price calculation process executing on it. However, whatever unit price you set via that hook may be overridden by Rules that you weren't intending to apply to those line items. In my opinion, the best thing to do would be to write a custom Rules action to encapsulate your pricing and call it in a sell price calculation rule.


How to add block-like visibility settings to nodes?

Block visibility rules are kind of fundamentally different from nodes in that nodes are intended to always show up using the "full" or "default" display mode in the main content block/region of the specific node's unique URL. On the other hand, blocks go hand-in-hand with the ability to be placed in any region on any page.  Block visibility can group permissions (ie role based rules)  along with path-or-url-based rules, but nodes cannot natively do this.

I can think of three possible alternatives (there might be more):

1) Embed Nodes in a block using one of these modules, and then use block visibility rules to place it.  This has the drawback that you have to tie things together quite manually in two places.

2) If you're showing campaign nodes on other nodes, then you can use an entity_reference field to reference the campaign node from another node (or vice versa)  and then just set the entity reference field's display settings to render the entity as if it were a field on the node.

3) Write a completely custom solution to mimic block visibility rules for nodes.  I'd start with a Text (long) field (call it field_campaign_urls),  then in a node_form_alter() hook alter the display to show up in a vertical tab (or you could use Field Group module to do this in the UI).  Then you'd need to implement a hook that gets called on all pages, e.g. hook_page_alter test the internal Drupal URL (and optionally also the pathauto alias) for a match against all values in the field_campaign_urls database table. The challenge here will be writing the wildcard functionality, you'll need to figure out how to convert  some/url/* into a database condition LIKE 'some/url/%'  This is also where you might want to start digging into the block.module code to find out more about the internal structure of how block visibility query logic works.   Finally, you'll need to combine this logic with your custom node access logic as well.  And indeed figure out which block region you want to add your node to.  You may leverage drupal_add_region_content to add your rendered node to a specific region.


Customise Publishing Options based on Role

The Revisioning module automatically generates separate create, edit, and publish permissions by role for all content types for which revison control is enabled.  It also integrates with the Rules module.  You may find this to be a simpler approach.


How can I update/revert a feature which includes page manager and mini panel components that is stuck as overriden?

Attempting to answer the question:

You should be able to simply re-export the feature to update the pane identifiers in code.

Background info:

There are two parts to this problem.
First of all, features uses a different way of determining whether or not something is overridden, than ctools does. So Ctools consider the state to be "in code", but features, "overridden".

Secondly, the way panes are identified have recently changed. The change initially came about to solve a particular bug, but now causes other problems instead, namely the 'new-X' "overrides".

There are several different patches in the Panels queue that all have different ideas on how this problem should be solved. Currently, I'm afraid to say that I believe you can't do a great deal about this. The current behavior simply isn't optimal.

You can read more in this issue, and the ones that are linked to.


User login link is always visible in menu

This seems to be a bug, /user/login should not be accessible as an authenticated user, but it redirects to user/1.

Edit: Discussed this with @dawehner and we figured it out together. This is egression: Do not bypass route access with 'link to any page' permissions for menu links

Open a bug report. This might actually a be a pretty serious security issue, looking at AccessManager, I don't understand why that starts with an allowed() state,LoginStatusCheck returns neutral, that is merged together to an allowed().


Taxonomy hierarchy in filter block of views isotope?

First, I'm confused about what you mean by views isotope?

But if you're asking to build a hierarchical taxonomy in view select, there's Simple hierarchical select module.

  Simple hierarchical select defines a new form widget for taxonomy fields to select a term by "browsing" through the vocabularies hierarchy.


Programmatically rearrange order of entity reference list on node

After getting and rearranging the field data you can set it again:

$node->field_focus_area->setValue($newOrder);


The http://drupal.org/project/countdown module does this on a block level, but since all the 'heavy lifting' is done on the client side with javascript, I wouldn't imagine it would be all that difficult to rejigger it to look at an appropriately css'ed field...


While previewing a node, the node parameter is not "upcasted" from an integer to a node object. But you can easily do this yourself in the preprocess function, just add those lines before:

  $router = \Drupal::routeMatch();
  $node = $router->getParameter('node');
  if (is_numeric($node)) {
    $node = \Drupal\node\Entity\Node::load($node);
  }
  //now you always have "real" node object (instanceOf Drupal\node\NodeInterface -> true),
  //no matter if preview or normal viewing


Entity Reference and nested arguments in Views

Actually Entity Reference does implement reverse pointers, so to speak.

On your program view, which I suppose has entity reference fields to course nodes, first set up a Relationship (under the 'Advanced' view section) that will link to the view the specific Course nodes that exist for the current program as entity references.

If you go to add a relationship, you'll get a dialog that looks like this:

Set it to filter the potential relationships to ones using 'Entity Reference' fields.
Select the 'Referenced entity' field that exists in the Program content type to point to its Courses (whatever you called it).  You can choose to change its name to 'Referenced course' or something short like that for later.  You can also limit the view to include only Programs that have course fields by checking that 'Require relationship' box!
Now all those course nodes are available in your view (you can add their fields to your view if you need to)
Next, add one more relationship.  This time look for the relationship that is a 'Referencing entity' (as opposed to 'Referenced entity') for your Course Date node.  That will provide a link to all Course Date nodes, which themselves reference the current Course node.  When setting up this second relationship, make sure you select the previous relationship to be used in the 'Relationship' dropdown.  After all, this reverse reference points to the course node of the current program, not to the current program itself, right?
Finally, you should now be able to add fields for course nodes and course date nodes that relate to your program, because of these two relationships.  Just make sure the fields you add, have the correct Relationship set from the relationship drop-down.  That way they will pull from the correct node.


How do I attach a file to a file field when saving (update/insert) a node?

I think that you don't have the fid.

/**
 * Implements hook_node_presave().
 */
function hook_node_presave($node) {

  if($node->type=='profil'){

    $uri = 'public://profiles/fichier';
    $filename = $node->title.' - PDF - '.$node->language.'.pdf';
    $file_path = $uri . '/' . $filename;

    // Output PDF with TCPDF
    $pdf->Output($file_path, 'F');

    $file_temp = file_get_contents($file_path);

    // Saves a file to the specified destination and creates a database entry.
    $file_temp = file_save_data($file_temp, $file_path, FILE_EXISTS_RENAME);

   $node->field_fichier = array(
     'und' => array(
       0 => array(
        'fid' => $file_temp->fid,
        'filename' => $file_temp->filename,
        'filemime' => $file_temp->filemime,
        'uid' => $node->uid;,
        'uri' => $file_temp->uri,
        'status' => 1,
        'display' => 1
    )
  )
);


Is it possible to create sub-node that can assign on a node?

Do you mean you want a Book that has chapters and you want them linked like a book? There is a module for that in Core called book. https://drupal.org/documentation/modules/book


As directed by aerozeppelin I got the following error:

  Fatal error: Allowed memory size of 50331648 bytes exhausted (tried to allocate 4096 bytes) in /home/htdocs/includes/database/query.inc on line 1857

So increasing the PHP memory limit is the cure; this link is useful for that.


Set a Document File in a webform submission programmatically

To attach the file to a webform submission, you should get the file id first, and then set the file_attachment to file id.
Try this out.

  $webform_submission = \Drupal\webform\Entity\WebformSubmission::load(1);
  $data = $webform_submission->getData();
  // Get the document file object from uri.
  $document = \Drupal::entityTypeManager()
    ->getStorage('file')
    ->loadByProperties(['uri' => 'private://documentA.pdf']);
  // Get the file Id.
  $doc_id = reset($document)->id();
  // Set the file_attachment to fid.
  $data['file_attachment'] = $doc_id;
  $webform_submission->setData($data);
  $webform_submission->save();


Show all users except profile being viewed (views, panel node)

the last checkbox on the settings of the contextual filter - exclude :) (under more)


certainly possible.

http://api.drupal.org/api/drupal/modules!search!search.api.php/function/hook_search_preprocess/7

Check out that function.


Get page number of multistep webform in tpl.php

I hacked it and used jquery to hide the div when there is an existence of a previous page class.


In view's settings (Page settings/Block settings) find Access. Change Permission to Role and select appropriate role (anonymouse)


Is it possible to create a panalized node in code?

Make sure that your content type is panelized (you've panelizer link at /admin/structure/types).
Double check the Panelizer settings of that content type, for instance whether to 'Provide an initial display named "Default"' (at /admin/structure/types/manage/%).

Above 2 steps can be achieved programatically by either exporting panelizer_defaults component into Features code:

features[panelizer_defaults][] = node:my_content_type:default

or define them using hook_panelizer_defaults manually.

At this point all your created nodes should be panelized automatically and the settings should be available in node object at $node->panelizer['page_manager'].

Still not sure if your node is panelized or not? Run this via drush (where 123 is your node id):

$ drush eval "print_r(node_load(123)->panelizer['page_manager']);"

and if you'll see an object printed out, your node is panelized.

Then if you would like to create/re-create panel display associated with the node, try the following code:

$node = node_load($nid);
$old_display = $node->panelizer['page_manager']->display;
$new_display = panels_save_display($display);
$node->panelizer['page_manager']->display = &$new_display;
$node->panelizer['page_manager']->display_is_modified = TRUE;
node_save($node);
// Clear caches just in case.
ctools_include('object-cache');
ctools_object_cache_clear('panels_node_display_cache', $node->nid);
$did = is_numeric($new_display->did) ? $new_display->did : FALSE; // Your display id.

The same thing can be achieved on newly created code by creating a panels_new_display(); instead and assign it to $node->panelizer['page_manager']->display.  Also note that the display should be only saved once (not on every node save), then it can be modified based on your needs.

See also:

How to attach node into panelized node?
Updating Panelizer content programmatically


Remove certain content types from search

Configuring search is easy with Search API. Excluding node types from indexing is one of its basic config options.

https://www.drupal.org/project/search_api

When you set up your index and go to the configuration page, you can exclude bundles (types).


Views contextual filters for user term references

I can try this on a view, but I think the way to do it is to add the relationship, then add a Contextual filter of the Taxonomy Name. That works

with one Relationship to Contextual Filter, so why wouldn't it work with two.


How do I automatically update database tables when changing custom entity fields

There are published examples using hook_update_n().


You've got it backwards-- you don't want to use views to display the panel.  Instead, you want to use panels to display the view.

I will try to explain how this works as simply as I can.  Panels overrides the node page display.  Therefore, the display must be changed in Panels.

You can add your views block to the panels display.  To do this, you can use a Contextual Filter.  The Contextual Filter is the "argument" that views needs to display the content.  Panels will provide this argument (the value for the contextual filter) because it is the one overriding the display.

Explaining how views and panels work in detail is beyond the scope of what I can do here but I will refer you to Node One's excellent free videos on learning views and learning page manager/panels.


How to programmatically stop a migration?

According to my comment on Luke solution, here is the complete code to interrupt you Migration in Migrate these days.

public function preImport() {
  parent::preImport();
  if($this->externalDependency == 0){
  throw new MigrateException('Dependencies were unfulfilled.');
  }
}

public function postImport() {
  parent::postImport();
  if($this->externalDependency == 0){
  return false;
  }
  // My code here
}

public function processImport(array $options = array()) {
  try {
    $result = parent::processImport($options);
    return $result;
  }
  catch (MigrateException $e) {
    $this->endProcess();
    drupal_set_message($e->getMessage(), 'error');
    return MigrationBase::RESULT_STOPPED;
  }
}


How to return drupal error message in php cli

Since you are using the command line, have a look at PHP's input/output streams. These let you write data out to where your environment would be expecting to receive output.

Alternatively, you might want a look at Drupal's built-in logging with watchdog(). You can see the messages it generates in Administration >> Reports >> Recent log messages.


I got the answer to this problem.

I used debug code if ($hook == 'cron') watchdog('cron', "hit $module cron"); in function module_invoke_all()

where to put debug code ?

In module.inc file of core drupal, add

 $function = $module .'_'. $hook;
 $result = call_user_func_array($function, $args);

between this two line of module_invoke_all() function, add above debug line.

It will look like :

$function = $module .'_'. $hook;

if ($hook == 'cron') watchdog('cron', "hit $module cron");

$result = call_user_func_array($function, $args);

After putting above line in module.inc,run cron manually and check log in recent log entries.

Because of this debug statement, I found the module which was not allowing to run cron.

I corrected the custom module code in that and cron started working fine.


The code I would use is similar to the following one.

$entity_query = new EntityFieldQuery();
$entity_query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->entityCondition('created', strtotime('1 January 2019'), '<')
  ->addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT');
$result = $entity_query->execute();
if (isset($result['node'])) {
  node_delete_multiple(array_keys($result['node']));
}

The differences between the code I am using and the code shown in the answers for Delete a node after X weeks it was created are the following:

The object used to query the entity is instantiated differently and its class is different
The code doesn't select just the published nodes (I take you are interested in deleting all the nodes created before 2019)
The code is using addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT') to get all the nodes, even the ones to which the currently logged-in user doesn't have access (Remember that cron tasks are executed as anonymous user, which possibly doesn't have access to many of the nodes)
In Drupal 7, the functions to delete nodes are node_delete() and node_delete_multiple() which require, respectively, a node ID and an array of node IDs

If I were to do the task in a hook_cron() implementation, I would use the following code.

  function mymodule_cron() {
    $entity_query = new EntityFieldQuery();
    $entity_query->entityCondition('entity_type', 'node')
      ->entityCondition('bundle', 'article')
      ->entityCondition('created', strtotime('1 January 2019'), '<')
      ->addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT')
      ->range(0, 25);
    $result = $entity_query->execute();
    if (isset($result['node'])) {
      node_delete_multiple(array_keys($result['node']));
    }
  }

Older Drupal 7 versions would need to replace addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT') with addMetaData('account', user_load(1)). For those versions the code would be then similar to the following one.

  function mymodule_cron() {
    $entity_query = new EntityFieldQuery();
    $entity_query->entityCondition('entity_type', 'node')
      ->entityCondition('bundle', 'article')
      ->entityCondition('created', strtotime('1 January 2019'), '<')
      ->addMetaData('account', user_load(1))
      ->range(0, 25);
    $result = $entity_query->execute();
    if (isset($result['node'])) {
      node_delete_multiple(array_keys($result['node']));
    }
  }

Using hook_cron() avoids issues in the case there are many nodes to delete. Trying to load, for example, 3000 nodes (even if the EntityFieldQuery class returns partially loaded nodes) could cause memory or timeout errors.


Views: how to ASC sort the grouping field #1 and sort DESC its content?

I have created a small test setup in Drupal, containing six nodes with each having a year (integer) and a content (text) field.

The view's configuration is displayed below:

The sort criteria is first on the year field (descending) and then on the content's text (ascending). The view generates the following result:

Note that I have excluded the year field from the display. Instead I'm using the grouping option on year in settings of the unformatted list (however, this is not necessary, but the result resembles your question more closely).


how to put permission to only paid users can print something in my drupal site

If you mean controlling who can view/download (i.e. be 'served') the PDF then you need to read up on the private file system (Working with files contains a pretty good introduction).

If you mean showing the PDF to anyone who requests it, but only allowing paid users to print from it, you can't. That would be controlling a user's browser, which you can't do for obvious security reasons. It's the nature of the web; if you want to distribute content, you have to face the fact that it can be copied unless you go down the DRM route.

The only DRM solution I know of for PDFs is Adobe Content Server; it's written in Java and is a real pain in the proverbial but it does work. You can control the number of times a person can print or even copy/paste data from the PDF.

It does introduce a really annoying workflow, though, that you'll need to explain in detail to your users; and it ain't cheap.


Have the server interpret www.example.com/directory as a directory rather than a Drupal path

So, your drupal site lives at webroot, and your wiki lives at webroot/wiki? First thing i would suggest is to put your wiki outside your drupal root and creating a separate virtual host. You're asking for trouble with your current setup.

The .htaccess file that ships with Drupal should properly be treating webroot/wiki as a directory, if it exists. See https://stackoverflow.com/questions/15879029/dont-understand-rewritecond-request-filename-f-and-d

If it just won't work for you, update Drupal's .htaccess to explicitly add your wiki path:

RewriteCond %{REQUEST_URI} ^/wiki

Put this right before:

RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

Your rewrite section will look like this (comments elided):

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteCond %{REQUEST_URI} ^/wiki
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]


Migrate from WordPress (with buddypress plugin)

I did a Wordpress import this summer into a Drupal 6 system.  While I ended up doing a manual import for a variety of reasons, a decent amount of my code was based on Wordpress Import.

This module has been suplamented by Wordpress Migrate which uses the Migrate framework.  Since you mentioned Drupal 7, this approach would be worth exploring.

Both of these use the WXR format, so you are likely to lose less data than with other methods, and you can generate the backup file right from the WP admin interface.

Personally, I would take a backup of your site (like with Backup and Migrate), and try out Wordpress Migrate before trying to use Feeds.

Keep in mind that Wordpress RSS and WXR files may not always be valid XML, so you may run into parsing issues.  I have had problems because of WP plugins that add embed code or <script> blocks directly into the post/page, and then WP doesn't wrap everything properly in a CDATA section.

It is also worth noting that you may end up losing any markup that would be the result of short-tags in the post/page body, and just import the sort-tag.


Redirect after login from custom login block

You have to add form_alter and add custom #submit handler to user_login form if current_path() is correct for you and set $form_state['redirect'] there.

Check this post Redirect to a custom page after a node has been added or edited.

Also it can be achieved via custom rule, if you don't want to write any custom code.


Images refering wrong path

I would say, Image is not referring any wrong path and there is nothing wrong in what you are seeing. Whatever you are seeing is by design in Drupal.

If you defined the Image style, the corresponding files automatically gets prepared in the folder. Hence if you upload an image the image gets uploaded at one default place which is for original images, But if you have defines the image style for that content type, then images gets saved at other place also. Hence In your case both "sites/default/files" and "sites/default/files/styles/large" are true. You can see the same image at two places.

For Example,

I just uploaded the image in Article and article content type has the image style Large. So that image gets uploaded at two places, as below in my folder.

FOR ORIGINAL IMAGE - sites/default/files/field/image/exampleImage.jpg
FOR LARGE IMAGE STYLE - sites/default/files/styles/large/public/field/image/exampleImage.jpg

So, same way, if I declare new Imgae style, like Medium Or Thumbnail, the new file with that name gets created and image gets saved there.

Hence, I am not getting why you want to change the path. There is nothing wrong in path. It is by Drupal's default desing. Hence, you not have any problem in your folders.

Hence for image, There is not a concept of changing path here. There is a concept of changing the Image style and image style choose their own folder automatically which is path.

So, you can go to Structure/content type/exampleType/Manage Display/ and from there you can change the Image style which you want and that image style will create/choose its own folder automatically.


Best practice to deploy an update which depend of a new configuration

I would recommend that you create the field programatically. In your update function. You could also create multiple update functions, just create the field in one, then migrate the data then remove the old field.

If you have a lot of data, then your update function should be done as a batch, so it doesn't run in any PHP timeouts or memory limits. In that case, having the update functions separate makes it easier to implement them.

To avoid duplicating code, you could read the config from the config sync storage and create it through the config entity storage, something like this:

$config_record = \Drupal::service('config.storage.sync')->read('field.storage....');
$storage = \Drupal::entityTypeManager()->getStorage($entity_type);
$entity = $storage->createFromStorageRecord($config_record);
$entity->save();

This is usually fine for custom update functions in projects because it will only be executed once. This approach is risky for core/contrib/reused modules (which usually import it from their default config) because you don't know when the update will be executed. Maybe you have to make another change to that config next week and add another update function to deal with that change, but if someone didn't execute the first yet, this initial update will already create the field based on the latest schema and then your update logic might get very confused about that.


Audio File Field is empty (null) on drupalgap app

The problem was that the url of the source audio file was wrong. It happened after i deleted originalsong.mp3 and reuploaded it. So, system gave it new name originalsong_0.mp3 (Note the _0 at the end of the filename). Probably drupal keeps track of files uploaded even when they are deleted so when i upload same mp3 with same filename it gets _0, _1 etc.
Null object appears at www.example.com/mobile-application but when project is compiled and run in real Android device it works out of the box. Play button works but not Download button(minor problem for me).


As far as I understand you could restrict block from being shown in front page, from block visibility settings. Alternatively, you could also make a custom template for the front page.


dpm breaks only if used in form custom submit on edit node

Thumbson was spot on. MySQL was hitting it's the packet limit and increasing maximum_allowed_packet in /etc/mysql/my.cnf solved the problem. (ubuntu path)

The error won't show in Drupal, the only place I could find it was in my php-fpm log. See below:

[13-Jan-2015 00:54:27] WARNING: [pool www1] child 21620 said into stderr: "NOTICE: PHP message: PHP Fatal error:  Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]: General error: 2006 MySQL server has gone away' in /srv/w$
[13-Jan-2015 00:54:27] WARNING: [pool www1] child 21620 said into stderr: "Stack trace:"
[13-Jan-2015 00:54:27] WARNING: [pool www1] child 21620 said into stderr: "#0 /srv/www/eslsearch.net/public/includes/database/database.inc(2171): PDOStatement->execute(Array)"
[13-Jan-2015 00:54:27] WARNING: [pool www1] child 21620 said into stderr: "#1 /srv/www/eslsearch.net/public/includes/database/database.inc(683): DatabaseStatementBase->execute(Array, Array)"
[13-Jan-2015 00:54:27] WARNING: [pool www1] child 21620 said into stderr: "#2 /srv/www/eslsearch.net/public/includes/database/database.inc(2350): DatabaseConnection->query('SELECT expire, ...', Array, Array)"
[13-Jan-2015 00:54:27] WARNING: [pool www1] child 21620 said into stderr: "#3 /srv/www/eslsearch.net/public/includes/lock.inc(167): db_query('SELECT expire, ...', Array)"
[13-Jan-2015 00:54:27] WARNING: [pool www1] child 21620 said into stderr: "#4 /srv/www/eslsearch.net/public/includes/lock.inc(146): lock_may_be_available('schema:runtime:...')"
[13-Jan-2015 00:54:27] WARNING: [pool www1] child 21620 said into stderr: "#5 /srv/www/eslsearch.net/public/includes/bootstrap.inc(433): lock_acquire('schema:runtime:...')"
[13-Jan-2015 00:54:27] WARNING: [pool www1] child 21620 said into stderr: "#6 /srv/www/eslsearch.net/public/includes/bootstrap.inc(455): DrupalCacheArray->set(Array)"
[13-Jan-2015 00:54:27] WARNING: [pool www1] child 21620 said into stderr: "#7 [internal function]: DrupalCacheArray->__destruct()..."


Export and Import Taxonomies and Extra Fields

According to this drupal link

drush ev '\Drupal::entityManager()->getStorage("shortcut_set")->load("default")->delete();'


print out multiple values of a taxonomy field

0 in $node->field_hotel_tx_atmosphere['und'][0]['tid'] means that you are taking only first term so you should loop through array to get all terms.

I recommend entity_metadata_wrapper (available with Entity API module):

$wrapper = entity_metadata_wrapper('node', $node);
foreach ($wrapper->field_hotel_tx_atmosphere->getIterator() as $delta => $term_wrapper) {
  // prepare and render field value:
  $result = field_view_field('taxonomy_term', $term_wrapper->value(), 'field_tx_headline', 'text');
  print render($result);
}

or build a View to display selected data in the right way.


Change a variable dynamically without it persisting in the DB

So this is what I came up with, an implementation of hook_init(). Perhaps there is a better solution?

function MYMODULE_init() {
  global $conf;

  // If we have the environmental variable ENV && we are not on a config page
  if ($env = getenv('ENV') && current_path() != 'admin/config/system/googleanalytics') {

    // Alter the googleanalytics_account ID
    if ($env == 'dev') {
      $conf['googleanalytics_account'] = 'UA-xxxxxxxx-x';
    }
  }
}


You need to provide website URL on your app settings.

Step 1. Navigate to your app settings

https://developers.facebook.com/apps/[your-app-id]/settings/

Step 2. Under website section provide your website URL.

check this answer for Reference


How to call User::load with dependency injection

You should use entity_type_manage to get the user storage. Something like this:

<?php

namespace Drupal\country_selector\Plugin\Block;

use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\user\UserStorageInterface;
/**
 * Provides a 'DefaultBlock' block.
 *
 * @Block(
 *  id = "default_block",
 *  admin_label = @Translation("Country switcher"),
 * )
 */
class DefaultBlock extends BlockBase implements ContainerFactoryPluginInterface {

  protected $account;
  protected $userStorage;

  /**
   * Class constructor.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, AccountProxyInterface $account, UserStorageInterface $user_storage) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->account = $account;
    $this->userStorage = $user_storage;
  }

  /**
   * {@inheritdoc}
  */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('current_user'),
      $container->get('entity_type.manager')->getStorage('user')
    );
  }

  /**
   * {@inheritdoc}
  */
  public function build() {
    $build = [];

    $userIdx = $this->$acount->id();
    $userx = $this->userStorage->load($userIdx);
    $countryx = $userx->country_iso_code_2;
    .....

Hope this helps.


Add custom styles for printing taxonomy terms

If you go to the display settings for your node (eg. admin/structure/types/manage/article/display) and in the "Custom display settings" fieldset check the box for "Print" and the save.
Then click the tab for the "Print" display settings.

Then configure your field with an inline label.

If this is not sufficient for your requirements you could also then override node or field templates specifically for that print display mode.

I can provide more information on that if you require it.

For node and field templates you can either use an if statement in the template to specify a specific view mode or you can add specific template suggestions so that you can have specific templates, like node--print.tpl.php

For the if statement method there are variables already available in those tempaltes:

node.tpl.php

<?php if ($view_mode == 'print'): ?>
  Your code goes here.
<?php endif; ?>

field.tpl.php

<?php if ($element['#view_mode'] == 'print'): ?>
  Your code goes here.
<?php endif; ?>

Or you can add template suggestions like this in your template.php file:

node.tpl.php

/**
 * Variable preprocessor for the node templates.
 */
function THEMENAME_preprocess_node(&$vars) {
  // Template suggestions for node--VIEW-MODE.tpl.php.
  $vars['theme_hook_suggestions'][] = 'node__' . $vars['view_mode'];
  // Template suggestions for node--NODE-TYPE--VIEW-MODE.tpl.php.
  $vars['theme_hook_suggestions'][] = 'node__' . $vars['node']->type . '__' . $vars['view_mode'];
}

field.tpl.php

/**
 * Variable preprocessor for the node templates.
 */
function THEMENAME_preprocess_field(&$vars) {
  $element = $vars['element'];

  // Template suggestions for field--VIEW-MODE.tpl.php.
  $vars['theme_hook_suggestions'][] = 'field__' . $element['#view_mode'];
  // Template suggestions for field--FIELD-TYPE--VIEW-MODE.tpl.php.
  $vars['theme_hook_suggestions'][] = 'field__' . $element['#field_type'] . '__' . $element['#view_mode'];
  // Template suggestions for field--FIELD-NAME--VIEW-MODE.tpl.php.
  $vars['theme_hook_suggestions'][] = 'field__' . $element['#field_name'] . '__' . $element['#view_mode'];
}

Those are examples. You can make other suggestions based on pretty much anything you want.
You can also just do a specific template suggestion for the print view mode instead of doing dynamic ones for all view modes like the above examples.
If using the above examples be careful that you don't have conflicts, for example if you have a node type that is the same as a view mode.


Specifying display of a new Paragraph type with images using HTML/twig?

In Drupal, the specifying the generation of HTML from Paragraph types (as well as other types in Drupal) is done via the misnomer "theming."

First create a
sub-theme.
Next, copy the
/modules/contrib/paragraphs/templates/paragraph.html.twig file into
your sub-theme's templates folder and name it
paragraph--figure--default.html.twig.
Add the following code below the set classes closing brace %} which specifies the parameters for the image you'd like to display.

{%
  set imagestyle = {
    '#theme':      'image_style',
    '#style_name': 'large',
    '#uri':        content.field_image['#items'].entity.uri.value,
    '#alt':        content.field_image['#items'].entity.alt,
    '#attributes': { class: 'myimage' },
  }
%}

Last, replace {{content}} with the code below:

<figure>
    {{ imagestyle }}
    <figcaption>{{ content.field_caption }}</figcaption>
</figure>

Note: Using {{ content.field_image }} directly inside <figure> instead of specifying a structure with theme image_style will not work.


You can place your blocks in the "content" region and then you can arrange them in the correct order on the blocks page, admin/structure/block.

See screenshot below for Drupal 7 example.


How to associate an entity view mode with a path? (Commerce product entity)

You can add your own entity view path with

hook_menu

e.g, something like

/**
 * Implements hook_menu
 */
function mymodule_menu(){
  $items = array()
  $items['myproduct/%myproduct'] = array(
    'title callback' => 'myproduct_page_title',
    'title arguments' => array(1),
    'page callback' => 'myproduct_page_view',
    'page arguments' => array(1),
    'access callback' => 'myproduct_access',
    'access arguments' => array('view', 1),
  );
}

/**
 * My Product page view callback
 */
function myproduct_page_view($myproduct){
  drupal_set_title($myproduct->title);
  $uri = entity_uri('myproduct', $myproduct);
  // Set the node path as the canonical URL to prevent duplicate content.
  drupal_add_html_head_link(array('rel' => 'canonical', 'href' => url($uri['path'], $uri['options'])), TRUE);
  // Some example to get entity display
  $view_mode = 'full';
  return myproduct_entity_view($myproduct, $view_mode);
}

See node_menu node/%node for example node view implementation.

Nevertheless, I'd recommend using standard product display nodes for product display.


I'm guessing you're using commerce kickstart and/or you've got Commerce Extra Price Formatters installed, it has an extension that provides the feature you're displaying, RRPP and your price.

Check out your display options, the second price won't appear automatically until you make it so. Go to admin/structure/types/manage/[your-product-machine-name]/display and verify that your price is being displayed there:

Then click in the link for the settings of the variation type display if you're in kickstart or go to admin/commerce/config/product-variation-types and edit the display for your variation type.

If you're not in kickstart, the url for this same screen would be admin/commerce/products/types

Change the price formatter to Formatted price or whatever other fits for your needs.


Migrating from Postgresql 9.1 (non drupal) to Percona Server 5.5

I end up using the feeds importers modules. You may have to change (rewrite/delete) your tables.

dump my table in a csv file (*.csv) make sure to add the headers.
create a content type with the name of my table and have all the columns of my tables
create a feed importer make sure to map the sources (postgreql) and target (drupal mysql) columns
got the import link (homepage/import) to upload the file. this may take a few minutes depending on how big you DB is.
when you go to content you should see all the newly added rows

Hope it helps.


To get the form with a suggestions list like that you need to create an exposed filter in your content Views and use Exposed form in block option. Place the block in a region of your theme.

To get the autocomplete suggestions list for taxonomy terms use the Has taxonomy terms filter and set it to Autocomplete.

The Global filter doesn't seem to work with taxonomy fields, I'm not sure if there are combinations you can try to make it work and have all the vocabularies terms searchable in one field.

The default Taxonomy term Views contextual filter needs to be removed since it won't work with only exposed filter output unless you use Views Filter Harmonizer.

Query Parameters To URL can help with the SEO side of things.

To get the Term name into your content Views instead of the TID you have to add a Relationship to the related Taxonomy term field. Then you'll be able to add Fields, Filters and Contextual filters based on the "Name", but the widgets might not offer autocomplete or other options you have under "Has taxonomy term".

Alternatively you can create a "Taxonomy term" TYPE of views where you can get the Name filter for all vocabularies, but no autocomplete.

(Add Relationship to content so you can show nodes in the results.)

Search Autocomplete might help partially, maybe you can get it to direct to a specific views page with the result as argument.

Using a more powerful Search API or other search features related to Views might allow you to achieve everything you're asking about.


How do I create a "More like this" block?

Here is the recipe for search_api_solr as per the OP. Note: both apachesolr and search_api_solr leverage Solr's builtin more like this feature. It is, therefore, not available to normal search.

Enable some modules: search_api, search_api_solr, search_api_views
Create a Search server of the Solr class.
Create a Search index (or use the Default node index) and point your Solr search engine at it.
Create a new view on your search index NOT on Search index.
eg:

Show *Default node index* sorted by *unsorted*
Continue and edit.
Reveal Advanced and Add a Contextual filter.
Filter on Search or scroll down to find Search: More like this.
Under When the filter is not available select Provide default argument: Content ID from URL.
Configure by selecting the Fields for Similarity that you want to determine likeness on.

http://drupal.org/node/1250304#comment-4870278


Programmatically created nodes don't appear unless opened and saved

Use hook_node_presave($node) to check whether you are getting proper values.

Also, try drupal_form_submit() instead of node_save() for edit


You can do the following:

In hook_preprocess_page() add the following code.

$block_entity = Drupal\block_content\Entity\BlockContent::load(BLOCK_ID);// BLOCK_ID
$block_view = \Drupal::entityTypeManager()->getViewBuilder('block_content')->view($block_entity, 'DISPLAY_VIEW_NAME');
if ($block_view) {
    $variables['page']['my_block'] = $block_view;
}

In your Twig template, print the block with the following code.

{% if page.my_block %}
  {{ page.my_block }}
{% endif %}


I'm not a Git expert, but as I understand it all of the releases of the dev branch listed on the project page are made directly to the 7.x-3.x branch.  Of course you're free to create your own branches locally for your own needs, but the master-like branch, which includes all of the releases pushed to drupal.org, is always going to be that 7.x-3.x branch.

If you want to switch to one of the tagged releases, use git tag to get a list of all the releases.  Then, to check out the 7.x-3.1 release (for example), use git co 7.x-3.1.

If you intend to edit the code for this release, you can then create a new branch (as Git explains) by using git checkout -b mycustombranch.


How to remove span from rewrite result in a field view?

You will need to click on the fields you excluded (one by one), click on Style settings and select Customize field HTML. Then select -None- under HTML Element. You may need to do this for Customize label and Customize wrapper. Click Apply. Don't forget to click Save.

EDIT: Since you have now clarified that you are using Views Fieldsets (and for next time, be sure to provide ALL details about your problem!), I believe you will need to override the default tpl.php file for the Views Fieldset fields.

Views Fieldset provides default tpl.php files inside the template folder inside the module folder (usually found in /sites/all/modules/views_fieldset. You need to copy the content of that file, save it in your theme's template folder and modify it. Follow the steps in this general tutorial (you will need to adapt it to your problem) to override the default template for Views Fieldset fields.  Good luck.


Conditional Stylesheets Set-up: Using the Module

Assuming you are using the conditional style module the format would be

; Set the conditional stylesheets that are processed by IE.
stylesheets-conditional[lt IE 7][all][] = ie6-and-below.css
stylesheets-conditional[IE 9][all][] = ie9.css
stylesheets-conditional[IE][print][] = ie-print.css
stylesheets-conditional[(gte IE 9)|(gt IEMobile 7)|(!IE)][all][] = modern-browsers.css

And there should be no space between the conditional-stylesheet and [IE].

If that doesn't work then you should make sure that the stylesheet it is referencing can be loaded. The stylesheet lines don't show up if the stylesheet doesn't exist or cannot be opened.