If you first created a node whose path is all-events and then created a page view whose path is all-events then the page and the view are competing of the same alias. Just delete your node and your view should display fine.


Here is my solution based on my favorite Rules module ;)

These 2 rules below automatically assign a predefined role to a user who registers to your website using a promotional link and code.

Important: Before importing these 2 rules:

backup your site :P
replace example.com with your domain name
replace 11 with your role id number
replace code=promo1 with your secret promotional code

You can import rules via this page on your website:
/admin/config/workflow/rules/reaction/import

Rule 1:

{ "rules_auto_assign_role_1" : {
    "LABEL" : "Auto assign role to user based on the registration path Part 1",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "user_presave" ],
    "IF" : [
      { "NOT user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "11" : "11" } } } },
      { "data_is" : {
          "data" : [ "site:current-page:url" ],
          "value" : "http:\/\/example.com\/user\/register?code=promo1"
        }
      }
    ],
    "DO" : [ { "redirect" : { "url" : "user?code=promo1" } } ]
  }
}

Rule 2:

{ "rules_auto_assign_role_2" : {
    "LABEL" : "Auto assign role to user based on the registration path Part 2",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "user_view" ],
    "IF" : [
      { "AND" : [
          { "NOT user_has_role" : {
              "account" : [ "site:current-user" ],
              "roles" : { "value" : { "11" : "11" } }
            }
          },
          { "data_is" : {
              "data" : [ "site:current-page:url" ],
              "value" : "http:\/\/example.com\/user?code=promo1"
            }
          }
        ]
      }
    ],
    "DO" : [
      { "user_add_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "11" : "11" } }
        }
      }
    ]
  }
}


How do I map attachments submitted via mailhandler?

I created a file field and mapped the attachment.

Create the file field under structure/types. Set number of values to 'unlimited'.
Under the feeds mapping map attachments to File:URI


You need to implement hook_theme() in your .module file to define a new theme implementation, set the #theme key in your form to the name of your implementation and create a twig template with this same name, but replacing hyphens with underscores:

example.module

function example_theme() {
  return [
    'my_awesome_form' => [
      'render element' => 'form',
    ],
  ];

Form/MyAwesomeForm.php

class MyAwesomeForm extends FormBase {
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildForm($form, $form_state);

    $form['#theme'] = 'my_awesome_form';
    [...]

templates/my-awesome-form.html.twig

<form{{ attributes }}>
  {{ form.form_build_id }}
  {{ form.form_token }}
  {{ form.form_id }}

      {{ form.name }}

      {{ form.type }}

  [...]

In this example form.name and form.type are your form fields, the array keys that you used to create the form, and I used bootstrap markup to show them in two columns.

Hope this helps.

Regards.

PS: This is a copy of my post at https://www.drupal.org/node/2788835#comment-11785706. I cloned it here because I'm not allowed to post comments.


Setting a default value in views jump menu d7

I figured it out, just went to views admin, deleted the -select-, reordered my taxonomy terms and bum!! it worked! am so dumb.


The Views module provides a Search view out-of-the-box (it's disabled). I would:

Turn off the default Search module.
Install Views.
Clone the default Search view in the Views administration page and call it My SITENAME Custom Search.
Add whatever filters you want to this View like the date criteria you list and adjust the deafult sorting if needed.

tip: you can easily search all the text in say the title and body field(s) of your Nodes with 1 text search box by adding a Filter of type Global: Combine Filter which uses the title and body fields in your Views: Fields section.

note for really really really massive sites you'll want to actually use a robust search engine. But as a proof of concept or small site (less than says tens of thousands of nodes) this should work Ok.

EDIT

To use the existing site search mechanism you would use hook_query_alter to change the query array to add SQL conditions to the Where clause of the query statement with whatever conditions you want. Note, that perhaps you may not have the sql fields needed for the query logic (you might thought). And if thats the case you would then need to use sql Joins to be able to reference the fields in SQL you want to do business logic on. Then add/modify a sort by sql clause, the same caveats about fields applies here again.

My Views solution above is 5 minutes worth of simple configuration and then adjusting some CSS. This solution could be 5 minutes if all the fields are in the SQL query already -- or much longer to figure out the necessary joins and syntax. The Devel module can help you inspect the raw search query. Good luck.


** UPDATE **

As suggested by oknate, using hook_user_login:

function hook_user_login(&$edit, $account)
{
  if(!$account->access)
  {
    drupal_set_message(t('This is your first login. Welcome!'));
  }
}

** Original less optimal method **

You can use hook_init() in D7, and check if they have a value for last access:

function hook_init()
{
  global $user;

  $first_login = db_query('SELECT 1 FROM {users} WHERE uid = :uid AND access = 0', array(':uid' => $user->uid))->fetchField();

  if($first_login)
  {
    drupal_set_message(t('This is your first login. Welcome!'));
  }
}


Hard to debug without further details.
If you get white page then check your Webserver logs, especially error log.
You can also try to run drush cron to catch some more details (error messages).


How to remove a URL from my XML sitemap?

This could either happen because it's node/add/article is included within a menu that's indexed by XML Sitemap or a custom path that was added.

In either case, a drush command can update the path flag for exclusion & rebuild the sitemap so that it's no longer there.

drush sqlq "UPDATE xmlsitemap SET status = 0 WHERE loc = 'node/add/article'"
drush xmlsitemap-rebuild

If you need to do this through the UI, you'll need to check either /admin/config/search/xmlsitemap/custom for a custom link or edit the menu item that contains it (/admin/structure/menu).


Synchronize drupal database with a traditional database

Easy answer: use the data module for drupal 6.x

http://drupal.org/project/data

"Data module helps you model, manage and query related sets of tables. It offers an administration interface and a low level API for manipulating tables and accessing their contents. Data module provides Views integration for displaying table data and Drupal search integration for searching table content."

The included data_ui module will let you setup the connections to your external database and map the fields.


There are different templates that you could use to theme the quiz.

1) page--node--take.tpl.php this would take care of the basic page level template for all the nodes with the url of the form node/nid/take

2) node--quiz.tpl.php this would be used for the quiz page.

3) quiz-single-question-node.tpl as you guessed this is the one for the single page quiz node. there is one variable in that $question_node

<?php print drupal_render($question_node->content['body']);?>

that would render the quiz form on each of the quiz node. so this could be used to add additional things to the quiz node like a footer with instruction or things like that.

4) theme_quiz_question_navigation_form function is the place were the navigation buttons are rendered so you could either over ride it in your theme or create a template file. the variable would be $form.

5) multichoice-answering-form.tpl.php this tpl contains the part of the form other than the buttons in the multichoice question type. this has got a variable called $form. you can make the required changes and then render the same in the tpl with something like print drupal_render($form);

Or the above can also be done using the form_alter function with in a module or theme. the form ID to use would be quiz_question_answering_form

There are many other template and theme functions with in the quiz module to change the look and feel of quiz for example to change the design of the result page you have quiz-report-form.tpl.php

If you go through the files and functions of the quiz module you would see many other templates and theme functions.


Merge content (e.g. a forum, with nodes, terms and users) from one Drupal site into another

If it was just for nodes i would say use this:

http://drupal.org/project/node_export

As you need to migrate users and taxonomy terms as well I would use this:

http://drupal.org/project/migrate

Although there will be some php OOP coding to do.


There are a few ways but I prefer entity_load():
$vocabulary = taxonomy_vocabulary_machine_name_load('Services');
$terms = entity_load('taxonomy_term', FALSE, array('vid' => $vocabulary->vid));

You could also use:

taxonomy_term_load_multiple()
EntityFieldQuery


How do I manage breadcrumbs when the node uses multiple vocabularies?

Here's my solution. Keep in mind that I'm very new to Drupal, so this might be a bit over-complicated, but hopefully it gives someone with a similar problem some direction. I will likely refactor this class in upcoming days, but right now I just need a break from all this mess.
function [YOUR-MODULE-NAME]_system_breadcrumb_alter(\Drupal\Core\Breadcrumb\Breadcrumb &$breadcrumb, \Drupal\Core\Routing\RouteMatchInterface $route_match, array $context) {

  // Control Blog Post Breadcrumb Taxonomy Trail
  $blogPostBreadcrumb = new BlogPostBreadcrumb();
  $blogPostBreadcrumb->alter($breadcrumb);
}

use Drupal\Core\Breadcrumb\Breadcrumb;
use Drupal\Core\Entity\EntityBase;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Url;
use Drupal\node\Entity\Node;
use Drupal\taxonomy\Entity\Term;
use Exception;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class BlogPostBreadcrumb
 *
 * The purpose of this class is to control Blog post breadcrumbs, as described here:
 *
 * RULE 1:
 * When the user is on the Tag page (Home > Blog > Tag) and clicks on a blog post, the blog post breadcrumbs will
 * display: Home > Blog > [Tag Name] > Blog Post Title
 *
 * RULE 2:
 * When the user is on the Category page (Home > Blog > Category) and clicks on a blog post, the blog post breadcrumbs
 * will display: Home > Blog > [Category Name] > Blog Post Title
 *
 * RULE 3:
 * When the user loads the blog post directly (i.e. Home > Blog, or comes from other sources unrelated to
 * Category or Tag), the blog post breadcrumbs should default to Category:
 * Home > Blog > [Category Name] > Blog Post Title
 *
 */
class BlogPostBreadcrumb
{
  /**
   * @param Breadcrumb $breadcrumb
   */
  public function alter(Breadcrumb &$breadcrumb): void
  {
    try {
      // current node
      $current_node = $this->currentNode();

      // nothing found, nothing to do
      if (empty($current_node)) {
        return;
      }

      // what is the current content type
      $content_type = $this->getField($current_node, 'type');

      // apply rule only to blog_post content type, otherwise let's stop the madness right here
      if ($content_type !== 'blog_post') {
        return;
      }

      // determine if the tag can be extracted from referrer. If not, default it to college_tag
      $altered_breadcrumb = $this->getTaxonomyLabelAndUrlByReferrer()
        ?? $this->getTaxonomyLabelAndUrlByCollege($current_node);

      // nothing matched - just let it be. Display blog_tags rather than nothing.
      if (empty($altered_breadcrumb)) {
        return;
      }

      // modify existing breadcrumb list by replacing the third link with proper tag
      // (Home > Blog > [college_tag/blog_tag] > Blog Title)
      $breadcrumb->getLinks()[2]->setText($altered_breadcrumb['label']);
      $breadcrumb->getLinks()[2]->setUrl($altered_breadcrumb['url']);

      // we have to disable caching, otherwise whichever taxonomy opens first, it will get cached!
      // load menu_link_content entity
      $entity =  \Drupal::entityTypeManager()
        ->getStorage('menu_link_content')
        ->load($current_node->getEntityTypeId());
      // disable caching
      $breadcrumb->addCacheableDependency($entity);
    } catch (Exception $e) {
      // if any exception is thrown, we don't want to stop the page from loading.
      // Worse case scenario, it will load blog_tags into breadcrumbs.
    }

  }

  /**
   * Get Field from node
   * Helper method for retrieving field value from given node.
   *
   * @param EntityInterface $node
   * @param string $fieldName
   * @return mixed|null
   */
  protected function getField(EntityInterface $node, string $fieldName)
  {
    return $node->get($fieldName)->getValue()[0]['target_id'] ?? null;
  }

  /**
   * Load node from current url
   *
   * @return EntityBase|null
   */
  protected function currentNode():? EntityBase
  {
    if ($nid = \Drupal::routeMatch()->getParameter('node')) {
      return Node::load($nid->id()) ?? null;
    }
    return null;
  }

  /**
   * Determine Taxonomy Breadcrumb Label and Url by referrer
   * We want to display Breadcrumb category depending from where the user is coming from:
   * Blog College (category) or Blog tag page
   *
   * @return array|null
   */
  protected function getTaxonomyLabelAndUrlByReferrer():? array
  {
    // capture referrer the "Drupal way"
    $route_parameters = $this->referrer();

    // if type is not a taxonomy term, it's not used to us
    if (empty($route_parameters['taxonomy_term'])) {
      return null;
    }

    // load node (taxonomy term)
    $term = Term::load($route_parameters['taxonomy_term']);

    // get taxonomy type
    $taxonomy = $this->getField($term, 'vid');

    // check if taxonomy belongs to college_tags or blog_tags
    if (empty($taxonomy) && !in_array($taxonomy, ['college_tags', 'blog_tags'])) {
      return null;
    }

    // if we can't find the url or the label
    if (empty($term->url() || empty($term->label()))) {
      return null;
    }

    return [
      'label' => $term->label(),
      'url' => Url::fromUserInput($term->url())
    ];
  }

  /**
   * Determine Taxonomy Breadcrumb Label and Url by college
   * This method will be used when referrer page doesn't exist, or the referrer is not Blog Category or Blog Tag page
   *
   * @param EntityInterface $node
   * @return array|null
   */
  protected function getTaxonomyLabelAndUrlByCollege(EntityInterface $node):? array
  {
    // blog can have one college tag (category)
    $taxonomy_id = $this->getField($node, 'field_college');
    $term = Term::load($taxonomy_id);

    // if we can't find the url or the label
    if (empty($term->url() || empty($term->label()))) {
      return null;
    }

    return [
      'label' => $term->label(),
      'url' => Url::fromUserInput($term->url())
    ];
  }

  /**
   * Referrer node
   * Load referrer node the "drupal way"
   *
   * @return mixed
   */
  protected function referrer()
  {
    // this would be college_tag or blog_tag page
    $previousUrl = \Drupal::request()->server->get('HTTP_REFERER');
    // fake the request to previous page, so we can get more info
    $fake_request = Request::create($previousUrl);
    // build url object.
    $url_object = \Drupal::service('path.validator')->getUrlIfValid($fake_request->getRequestUri());
    if ($url_object) {
      return $url_object->getRouteParameters();
    } else {
      return null;
    }
  }
}


How can I make db_query SELECT LIKE case insensitive?

The typical way to accomplish this is to compare a lower-case version of you search string against a the lower-cased variant in the table. See below for an example using strtolower() and LOWER():

$mail = strtolower($mail);

$results = db_query(
 'SELECT email_address
  FROM email_address_table
  WHERE (LOWER(email_address) LIKE :mail)',
  array(':mail' => '%' . db_like($mail) . '%')
)->fetchAll();


How to setup Drupal Performance Monitoring to Bypass Varnish?

I could bypass it by adding a "NO_CACHE=1" cookie to the request. Using a POST instead of a GET request will bypass Varnish as well.


New multisite server: should I use CPanel? And Symlinks?

From the information you've provided, it sounds like CPanel would not be a good setup for you. CPanel is great if you want an easy way to manage separate accounts that don't have access to each other. That's why many resellers use CPanel. You will likely spend just as much time getting around CPanel to do what you want.

However, keep in mind that CPanel offers a lot out of the box, like email, easy SSL Cert management, DNS management, and monitoring, not to mention security and software updates. If you spin up your own environment, you will need to make sure you set up a firewall of some sort, and an email server, at the very least. Server setup can be a large topic, and is very dependent on your particular hosting needs.

You didn't mention it, but have you looked at Aegir? It may provide you with the multi-site management and update management that you're looking for: http://www.aegirproject.org/

Regarding your proposed directory structure, I have not tested a setup like that so I can't provide a direct answer to your question, but I would look into using Drush and aliases if you haven't already.


Drush 8 throws unknown error on Drupal 8 install

Looks like the version of PHP you are using does not meet the minimum requirements for Drush and/or Drupal.  Check your PHP version, and compare against the Drush supported versions matrix.


Bootstrap subtheme does not apply to main menu

You must use the template files from bootstrap theme since all those are overridden there. the templates file you should use are under themes > bootstrap > templates > system.

copy the page.tpl.php and html.tpl.php from there to your sub-theme.

simply use the same .info file for your sub theme as well. it will give you all the regions. set "base theme=bootstrap" in template_name.info file.

remember to clear the cache


How can I use exposed filter likes "views tree" in views of content?

The Taxonomy Menu module looks like just what you're after.

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


How can I add a class to a view list item that has a moderation state of draft

This can be done through the Views interface.

You can add classes based on existing Field values to entire rows in Format > Settings, or you can add classes to individual Fields (you mentioned title) under Style settings wrapper or field HTML options.

Tokens to use in all of these cases can be found in the settings of the Field according to which you want to style the rows/other fields. The settings are under Rewrite results > Override the output of this field with custom text > Replacement patterns options.

You don't have to actually keep the rewrite enabled, you just need to temporarily reveal and uncollapse to copy the tokens you need.

Then add CSS for those classes to your subtheme as usual, or through CSS editor module.
You can hide the field ("Exclude from display") but it needs to be there on the list, arranged before any other fields that may use its value for classes.


There are 2 things you can do here:

Use Docker as external container like you are doing. You need to pass the --net parameter too to make that work, see example below. You will always use this drush container as a running command, not a container that is up and running with your stack all the time.

docker run --net={your_container_network_name} --rm -it -v $(pwd):/app drush/drush sqlc

Simply add drush to your Drupal container and connect to that container to run drush commands:

Dockerfile:

ENV DRUSH_VERSION 8.1.2
RUN curl -L --silent https://github.com/drush-ops/drush/releases/download/${DRUSH_VERSION}/drush.phar \
  > /usr/local/bin/drush && chmod +x /usr/local/bin/drush

Connect to your container and then run any drush command inside it:

docker exec -it {container_id} bash

root@{container_id}:/var/www/html# drush status


You can do it just for your site using hook_commerce_currency_info_alter(), but more appropriately check out the information in the Drupal Commerce FAQ on Currency Formatting to get the proper format in core. The reason it's showing up as 12.34 ZAR is because that's just the bland default format we use for currencies we didn't know how to format. : )


You can try \Drupal::database()->select->addExpression().

For you, below code might be useful.

\Drupal::database()
  ->select('node_field_data', 'spmw')
  ->fields('spmw', ['id'])
  ->addExpression("DATE_FORMAT(created,'%H:%i')", "created")
  ->execute()
  ->fetchObject();


Help understanding how to modify lay out of pages within drupal

I assume you are embedding the images in a block which you then show on all your pages.

If you reference a background-image from your style sheet as in url(../images/hello.jpg) all works fine because the style sheet, no matter what page you are looking at, references images from the style sheet directory as a base . If you embed an image tag on a page your img url will not be correct for pages of different depths as the page's url changes, and it is the page url that is the base. You have two quick solutions:

Pathalogic module - it is a text input filter that will rewrite
your embedded anchor and image paths automatically
PHP Filter - It is also a text input filter. Rewrite the path using the l() function, or concatenate it onto $base_url in a PHP snippet. This method is not preferred and support for the PHP Filter has been dropped in Drupal 8.

And as to the css and theming problems:

Marinelli is using a 960 grid system. There are lots of information on the web available on that and I suggest you read up on that.

In short, you must add appropriate classes to your images which will then take care of the css on your behalf. To float 3 images horizontally you need to add the following classes to your images.

image 1. class="alpha grid_4"
image 2. class="grid_4"
image 3. class="grid_4 omega"

And depending on your use case you might need to do a clearfix on the parent container.


How to add an SQL expression to the entity query? (D8)

Using query tags and metadata the underlying Select query can be altered easily.

$query = \Drupal::service('entity_type.manager')->getStorage('taxonomy_term')->getQuery();

// Add tag and any metadata to the entity query.
$query->addTag('my_category')
  ->addMetaData('my_category', $dynamic_category_name);

$tids = $query->condition('vid', 'tags')->execute();

And then in my_module.module file:

/**
 * Implements hook_query_TAG_alter() for my_category tag.
 */
function my_module_query_my_category_alter(\Drupal\Core\Database\Query\AlterableInterface $query) {
  $expression = "Replace(taxonomy_term_field_data.name, ' ', '-')";
  $args = [
    ':dynamic_category_name' => $query->getMetaData('my_category'),
  ];

  $query->addExpression($expression);
  $query->where($expression . ' = :dynamic_category_name', $args);
}


How to have #description in form to be below title and above field?

User #after_build at the end of your hook_form_alter.

$form['#after_build'][] = 'MODULE_NAME_move_description_up_after_build';

See below function to move the description in between the title and field.

/**
 * build function
 * @param type $form
 * @param type $form_state
 * @return type
 */
function MODULE_NAME_move_description_up_after_build($form, $form_state) {
  drupal_add_js('jQuery(document).ready(function ($) {
    $("label ~ div.description").each(function(index, element) {
      $(this).insertBefore($(this).prev("input"));
    });
  });', array('type' => 'inline', 'scope' => 'footer', 'weight' => 5));

  return $form;
}


http to https htaccess always redirecting to home page

By default, Drupal includes an .htaccess file that has instructions in the comments for doing https redirection.  I suggest you follow the instructions in that file.

From Drupal 7.22:

# Various rewrite rules.
<IfModule mod_rewrite.c>
  RewriteEngine on

  # Set "protossl" to "s" if we were accessed via https://.  This is used later
  # if you enable "www." stripping or enforcement, in order to ensure that
  # you don't bounce between http and https.
  RewriteRule ^ - [E=protossl]
  RewriteCond %{HTTPS} on
  RewriteRule ^ - [E=protossl:s]


How to count the number of posts by a author? D8

There is no difference between Drupal 7 and Drupal 8 on how to accomplish this.

From a default Content view:

Add the "Content: Authored By" field to the view.
Click "Use Aggregation" and change to yes.
Click "Aggregation Settings" to the right of "Content: Title".
Change to COUNT and Entity ID respectively.

View export:

langcode: en
status: true
dependencies:
  module:
    - node
    - user
id: content_with_author_count
label: 'Content with author count'
module: views
description: ''
tag: ''
base_table: node_field_data
base_field: nid
core: 8.x
display:
  default:
    display_plugin: default
    id: default
    display_title: Master
    position: 0
    display_options:
      access:
        type: perm
        options:
          perm: 'access content'
      cache:
        type: tag
        options: {  }
      query:
        type: views_query
        options:
          disable_sql_rewrite: false
          distinct: false
          replica: false
          query_comment: ''
          query_tags: {  }
      exposed_form:
        type: basic
        options:
          submit_button: Apply
          reset_button: false
          reset_button_label: Reset
          exposed_sorts_label: 'Sort by'
          expose_sort_order: true
          sort_asc_label: Asc
          sort_desc_label: Desc
      pager:
        type: none
        options:
          offset: 0
      style:
        type: default
        options:
          grouping: {  }
          row_class: ''
          default_row_class: true
          uses_fields: false
      row:
        type: fields
        options:
          inline: {  }
          separator: ''
          hide_empty: false
          default_field_elements: true
      fields:
        title:
          id: title
          table: node_field_data
          field: title
          relationship: none
          group_type: count
          admin_label: ''
          label: ''
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: false
            ellipsis: false
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: false
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          click_sort_column: value
          type: string
          settings:
            link_to_entity: false
          group_column: entity_id
          group_columns: {  }
          group_rows: true
          delta_limit: 0
          delta_offset: 0
          delta_reversed: false
          delta_first_last: false
          multi_type: separator
          separator: ', '
          field_api_classes: false
          entity_type: node
          entity_field: title
          plugin_id: field
        uid:
          id: uid
          table: node_field_data
          field: uid
          relationship: none
          group_type: group
          admin_label: ''
          label: ''
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: false
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          click_sort_column: target_id
          type: author
          settings:
            link: 0
          group_column: target_id
          group_columns: {  }
          group_rows: true
          delta_limit: 0
          delta_offset: 0
          delta_reversed: false
          delta_first_last: false
          multi_type: separator
          separator: ', '
          field_api_classes: false
          set_precision: false
          precision: 0
          decimal: .
          format_plural: 0
          format_plural_string: "1\x03@count"
          prefix: ''
          suffix: ''
          entity_type: node
          entity_field: uid
          plugin_id: field
      filters:
        status:
          value: true
          table: node_field_data
          field: status
          plugin_id: boolean
          entity_type: node
          entity_field: status
          id: status
          expose:
            operator: ''
          group: 1
      sorts: {  }
      header: {  }
      footer: {  }
      empty: {  }
      relationships:
        uid:
          id: uid
          table: node_field_data
          field: uid
          relationship: none
          group_type: group
          admin_label: author
          required: true
          entity_type: node
          entity_field: uid
          plugin_id: standard
      arguments: {  }
      display_extenders: {  }
      group_by: true
    cache_metadata:
      max-age: -1
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - 'user.node_grants:view'
        - user.permissions
      tags: {  }


Views: Showing related nodes from the tagged taxonomy term using views

Create view (block)
Add fields (title)
Add Contextual filters: "Content: Has taxonomy term ID"
Configuration on this filter:

When the filter value is NOT in the URL
Provide default value
Type: Taxonomy Term ID from URL. Under that, check the box "Load default filter from node page, that's good for related taxonomy blocks." Check the boxes of the taxonomies you want involved here

Filter criteria: Content: Type (= FAQ)


Theme settings to include different PHP files into template

Did you cleared cache ? I usually include header.inc, but I try your code and it worked on my site.


How to create multiple node at a same time programatically?

I guess it is because you overriding node variable.

In my opinion the more Drupal way is to use Rules module. There you can create   application node after article is created.


This is a job for Views.  To expound upon the comments, this is a screen shot of a quick view that will do this:

I created two quick content types, answer and question.  I used the body field just for expediency in both, and the only other field I added was a node reference called question in the answer type.

In the View, I filted on published nodes of type answer, the argument is that node reference field above, with the default coming from the URL.  I output the Title and Body field.  I set the paging options to 4 so that it would output a maximum of 4 answers to match the LIMIT in your query.  I didn't sort the output but you can do that if you want in Sort Criteria.

I created only one quick question and answer.  On my system, the question is nid 379, so:

putting that in as the argument, the view will output any answers (well, up to 4) with that nid as the node reference in question.  Create a block display for this, and you can have this displayed on your node page with the question.

Now, as you mention in the comments, if you are sure you want to do all of this yourself in your page.tpl.php file with db_query()s, feel free to scrape out the query Views has built for you from the preview.  In this case, that would be:

SELECT node.title AS node_title, node.nid AS nid, node_revisions.body AS node_revisions_body, node_revisions.format AS node_revisions_format FROM node node  LEFT JOIN content_type_answer node_data_field_question ON node.vid = node_data_field_question.vid LEFT JOIN node_revisions node_revisions ON node.vid = node_revisions.vid WHERE (node.status = 1) AND (node.type in ('answer')) AND (node_data_field_question.field_question_nid = 379 )

and modify it to your specific needs.


Defining and manipulating help text for a path

A quote from the documentation (subheading Parameters):

  $path: The router menu path, as defined in hook_menu(), for the help that is being requested; e.g., 'admin/people' or 'user/register'. If the router path includes a wildcard, then this will appear in $path as %, even if it is a named %autoloader wildcard in the hook_menu() implementation; for example, node pages would have $path equal to 'node/%' or 'node/%/view'. For the help page for the module as a whole, $path will have the value 'admin/help#module_name', where 'module_name" is the machine name of your module.

This means that the following should work for you:

    function mymodule_help($path, $arg) {
      switch ($path) {
        case 'node/YOUR_NODE_ID':
          // Help text for the simple page registered for this path.
          return t('This is help text for the simple page.');

        case 'admin/help#testmodule':
          // Help text for the admin section, using the module name in the path.
          return t("This is help text created in the page example's second case.");
      }
    }


Create/Update a commerce order using parameters passed via the url

As far as I know, the only way to do this is with a custom module. It should implement hook_menu() to accept as many parameters as you need, and invoke a callback that uses the Drupal Commerce API like in this example.

[EDIT] There are three modules that may help you do this if you don't want to create a custom module yourself:

Rules link. It attaches a link to entity displays that triggers a rule. It passes the entity to the attached Rule
Rules link event. In some ways similar to Rules link, but from what I can tell, you can actually use the SKU (or other parameters) as an argument in the URL link, accessible to the Rule through a token [path:last] and so forth. Main difference between Rules Link and Rules Link Event here.
Commerce cart link. Similar to Rules link event, but works with ctools to create a token for the link, which increases security.


Add custom user image field on private messages list instead of default user picture

You have made mistake in your field name, Drupal creates an machine name of any field prefixed as "field_" if you create it using Field UI. Using thumbnail as the style and also ensure that the style you have added -- people_profile_image is created in the Image Styles

so your code should be

if (!empty($user->field_profile_image[LANGUAGE_NONE][0]['fid'])) {
  // Load the file
  $file = file_load($user->field_profile_image[LANGUAGE_NONE][0]['fid']);
  $account = user_load($user->uid);

  // Note the style name is "thumbnail" and that your field name is
  // field_profile_image not profile_image which you have put in second line
  // which loads the file
  echo theme('image_style', array('style_name' => 'thumbnail', 'path' => $file->uri));
}


Altering fields before rendering: hook or template?

You can configure views in many ways and the hooks, that are called, will change accordingly.

You can easily debug this, if you put a "catch all" hook into your module and print out the hooks that are called:

function mymodule_preprocess(&$variables, $hook) {
   echo "$hook
\n";
}

Then your page will be full of hooks, that are called at different places and you can try to narrow it down to the hook you need.

The next step would be to install devel and enable kint and debug the variables of the hooks, that you are interested in:

function mymodule_preprocess(&$variables, $hook) {
   if ( $hook == 'views_view_grid' ) {
      kint($variables);
   }
}


After enabling MySQL replication getting deadlocks when clearing cache

Follow this and you should be good to go: Fixes for MySQL Deadlocks in D7


drush and connecting with a non-localhost database

Occurred to me right after I posted my question to check whether someone had created another my.conf or .my.conf file on the system at sometime in the past. And yes there was a .my.conf file that had been created some years ago. Renamed the file and viola, drush pml works as expected.

Hopes this helps someone puzzled by incorrect database connection.


Field without Used in data in Fields Report

OK, I'm on the right track after a bit of sleuthing. Drupal\Core\Entity\EntityFieldManager::getFieldMap() reveals that the final knowledge comes from entity.definitions.bundle_field_map. I won't write where it dwells because we're performing heart surgery here... But he who dares will find it. :-)


Hiding submenu items of a page in Drupal 6

You can use Menu Block module to only show the top level items: http://drupal.org/project/menu_block

Make a normal menu, create a menu block using that menu and set the depth to '1' .


Automake forum on node creation with rules

There is no need for any custom php here. Just the below steps.

In Rules actions,

Action 1: "Create a new entity > Taxonomy term"
Enter your title based on the created node and put it in the forum taxonomy
Action 2: "Set a data value > [entity-created:parent], Value: 194"


How to add views exposed filter blocks into views

Add the following function in your template.php

function THEMENAME_render_block($module, $delta, array $options = array()){
  $default_options = array(
    'title' => '<none>',
    'region' => -1,
  );

  $options = array_merge($default_options, $options);

  $block = db_query('SELECT * FROM {block} WHERE module = :module AND delta = :delta', array(':module' => $module, ':delta' => $delta))->fetchObject();
  if($block) {
    $block = block_load($module, $delta);
    $block->title = $options['title'];
    $block->region = $options['region'];
    $blocks = array($block);
    $rblocks = _block_render_blocks($blocks);
    $render_array = _block_get_renderable_array($rblocks);
    return drupal_render($render_array);
  }
  return "";
}

then in your views header render the block like so

<?php print THEMENAME_render_block('<moduleName>', 'delta', array('title' => t('Filter Title'))); ?>

For this you must have views php module enabled if you want to render the block from views header or else you can use tpl file to render the block in the header as @rooby suggested.


The Drupal user with uid = 1 is created by Drupal during the installation process of Drupal. User 1 bypasses all access callbacks in the system by default -- he can see/do anything.

Beyond that it is a typical Drupal user. If you want to secure the "admin" or uid=1 user please refer to this documentation page: Securing user #1 on steps you can take to secure the usage of the uid=1 user.


Drupal 8 entities inheritance and bundles

Drupal Core uses that itself for test entity types:

So yes, this works. However, it only works as far as it is covered by PHP. You can inherit base field definitions for example if you call the parent method and use the return value, see those classes.

Annotations for example are however not inherited, each subclass needs to re-define everything.

There is the plan to provide a default content entity that will a default set of base field definitions and other things that you probably want to have on custom entity types, likely that will live in the 8.x version of the entity.module.

On what you want to use, that depends on your use case. The common use case for bundles is so that users/site builders can create them and add configurable fields. If you need that, use them.

Keep in mind that not everything is generic, various things are still node specific, like the whole revision handling (the storage is generic, but all the user interfaces require a ton of custom code at the moment), the node preview functionality is also custom and other things. We plan to improve that situation in the mentioned entity.module until we can improve it in core.


Render a CCK field with only the node object in Drupal 6

In D6, you can render CCK fields with:

content_format

e.g:

print content_format('field_my_cck_field', $node->field_my_cck_field[0], 'default', $node);

See also content_view_field for an alternative option.

If you're in a node template and the field is set to display, you can also just go:

print $FIELD_NAME_rendered // where $FIELD_NAME is the field name


What to attach event listener to in Drupal behavior

The cause was pretty basic - this is in the admin theme, which in Drupal 7 is set to use jQuery 1.4.4, and .on() wasn't added until 1.7. I switched to using .bind(), and it works fine now.


How can I programmatically create a block type?

I had the same issue and I hope I have resolved it.
Your algorithm is next:

Create your own module
Create file <your_module>.install
There must be at least one hook hook_install (I have used two: hook_install and hook_uninstall)
Inside install hook:

create a new block type
create fieldStorageConfig
create fieldConfig
set component for form and view display

My code:
<?php

use Drupal\block_content\Entity\BlockContentType;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;

function <your_module_name>_install() {
  $newBlockType = BlockContentType::create([
    'id' => <your_id>,
    'label' => 'Custom block type',
    'description' => "A custom block type",
  ]);
  $newBlockType->save();

  $blockId = $newBlockType->id();

  block_content_add_field($blockId, 'Icon', 'custom_block_icon', 'image', 'image', 'image_image');
  block_content_add_field($blockId, 'Count', 'custom_block_count', 'integer', 'number_integer', 'number');
  block_content_add_field($blockId, 'Description', 'custom_block_description', 'text', 'text_default', 'text_textfield');

}
function block_content_add_field(
  $blockTypeId,
  $label,
  $componentName,
  $fieldStorageType,
  $viewDisplayType = 'text_default',
  $formDisplayType = 'text_textarea_with_summary') {
    // Add or remove the body field, as needed.
    $field = FieldConfig::loadByName('block_content', $blockTypeId, $componentName);
    if (empty($field)) {
      $fieldStorage = FieldStorageConfig::loadByName('block_content', $componentName);
      if (empty($fieldStorage)) {
        $fieldStorage = FieldStorageConfig::create([
          'field_name' => $componentName,
          'entity_type' => 'block_content',
          'type' => $fieldStorageType,
        ]);
        $fieldStorage->save();
      }

      $field = FieldConfig::create([
        'field_storage' => $fieldStorage,
        'bundle' => $blockTypeId,
        'label' => $label,
        'settings' => ['display_summary' => FALSE],
      ]);

      $field->save();

      /** @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface $display_repository */
      $display_repository = \Drupal::service('entity_display.repository');

      // Assign widget settings for the default form mode.
      $display_repository->getFormDisplay('block_content', $blockTypeId)
        ->setComponent($componentName, [
          'type' => $formDisplayType,
        ])
        ->save();

      // Assign display settings for default view mode.
      $display_repository->getViewDisplay('block_content', $blockTypeId)
        ->setComponent($componentName, [
          'label' => 'hidden',
          'type' => $viewDisplayType,
        ])
        ->save();
    }

    return $field;
}

Result: the new custom block type with 3 fields.


How to update Drupal securely using GUI/web interface

I think you are right that it's asking you to enter your important credentials over a potentially non-encrypted channel. This feature is a trade-off between doing things an optimally secure way and making it easy to get updates done. If updates are hard to do people won't do them and that is also an insecure situation.

Entering your credentials over a non-encrypted channel is only insecure if you think someone is sniffing your traffic. You can mitigate that by using a vpn or ssh tunnel (especially one that goes to the server).

Your idea to upload your private ssh key to the webpage to avoid using credentials seems at least partially flawed to me: the private key has the same value to an attacker as your ssh username/password. If you send the key on a non-encrypted channel that can also be intercepted and abused.

If you are concerned about security you can:

Add a full or self-signed ssl certificate to your webserver
Use a vpn or ssh tunnel to encrypt your non-encrypted (http) browser traffic
Just keep using ssh+drush to get the updates done


Drush not recognized and internal or external command

Did you install Drush Launcher? This seems like a PATH issue -- your command lines doesn't know where to find Drush 9.

  To be able to call drush from anywhere, install the Drush Launcher.
  That is a small program which listens on your $PATH and hands control
  to a site-local Drush that is in the /vendor directory of your
  Composer project. If you skip this step, run Drush from Drupal root
  via ../vendor/bin/drush. In that case Drush's bash integration and
  custom prompt won't work.

from: http://docs.drush.org/en/master/install/


I have the impression that what you're asking for requires more then just (only) the Flag module. I.e. you should get it to work if you also use the Rules Link module.

If you're not familiar with Rules Link, then have a look at "How to show authorized users a link for relevant Views results using the Rules Link module?". The scenario explained in that question is about users that are "blocked" or "active", and which you could consider as a variation of what this question here is about, i.e.:

think of "active" users as "users who have flagged their nodes" (as in your question).
think of "blocked" users as "unflag a user from his view of applicants" (as in your question).

Of course, you don't want to block or activate users for your case. But instead you could use 2 separate flags:

a 1st flag to be used by all the users, to indicate something like "I want to apply for this node" (adapt the label to whatever fits).
a 2nd flag to be used by the recruiter to indicate something like "reject a user as an applicant".

Obviously, you could show to "recruiters" (role) a view of all the users who have flagged their nodes (with the "1st flag"). And using Rules Link you could improve that view to trigger some additional Rules magic to simply flag an applicant (with the "2nd flag").

Note: no custom coding needed, only 2 flags to be configured, and some rules magic (combined with Rules Link).


How to programmatically code a block to show taxonomy vocabulary as an unordered list?

That's something I have put together for myself in the past. I posted the code on the Drupal taxonomy_get_tree() API page where you can get a copy for yourself. The core part of the code is usable with Drupal 6 as well (some smaller modifications are needed to make it work though).


Include Drupal modules inside composer.json file

There are general two kind of dependencies you can make in a composer file.

Other Drupal modules
PHP/JS/FOO libraries

If your module depends on a specific library, you should do like the address module and make sure that the library is present when it's being installed, so you can prevent installation if the library is not available. It's a clever way of making sure you don't install the module in a broken setup, which could cause fatal errors etc.

IF you simply depend on other drupal modules, you should also add the dependency in the info file which should be enough.


Gallery that can be added to a node via node edit page?

I usually use Galleria module to do so:
https://drupal.org/project/galleria

Turns image fields of nodes into Galleria galleries with this JavaScript (JQuery) image gallery.


What effect does BigPipe have if my traffic is mostly anonymous and I'm serving unpersonalized content behind varnish?

How does BigPipe have an effect if my traffic is mostly anonymous and behind varnish?
This really depends on the content of the page. Taking away any content depending on the logged-in user there might be no dynamic part left which could have any effect.
Additionally, why does the second request bypass Varnish?
As mentioned in the module description it is not possible the send the cache tag headers after the dynamically generated content has been streamed to Varnish. The Internal Page Cache can be controlled without sending headers because it is cached in the local database.


Is there a way to change content in 1 master node and have it changed in hundreds of others?

If you have so many blocks, then you should try to find ways/techniques to reduce the amount of them. Below are some possible modules to help you on that.
BEAN
You should have a look at the Bean module, which potentially can help you to answer this question. Here is a quote about its project page:

Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

This module also works great in combination with the UUID and UUID Features Integration modules. And after you become familiar with the Bean module, you might find other cases in your site where you also want to use this module (which somehow compensates the fact that you need to add another module).
The video tutorial Drupal Bean module tutorial - using Bean Admin UI provides a great introduction to really understand the power of this module, and the kind of things you can do with it (by only using site building techniques, no custom coding involved). It also shows how the Bean module transforms Drupal blocks into fieldable entities.
Remark: this module (a raising star!) has been moved to core in D8 ...
Rules and Rules block visibility
Another module to have a look at (to help reduce the number of your blocks), is the Rules block visibility module. Here is a quote from its project page:

The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless:

Need to show a block only for users registered more than a month ago?

Perhaps you have a block that must be shown only between 8am-5pm on weekdays?

What about displaying or hiding a block based on current weather conditions?

All of this can be done by using Rules block visibility.


Content publishing and confirming comment via email in drupal 7?

Currently there is no module for this functionality afaik.

To implement this one,

You need to pull the mails from server
Processing the mails and performing other operations like checking whether the user is an admin
After the processing create the content
Finally add a cron job to perform this operation regularly

This article provides info about how to achieve this feature in drupal 7 with combination of several modules.

However authenticating using the sender's mail will be a security risk. For example if the admin mail ID is exposed then anyone can send mails as admin by altering the header information.


How to use trusted contacts as a selection rule for user panel page, drupal commons

I couldn't find a direct solution for this.

So as a workaround, I'm using Flags and Rules. Trusted contacts are flagged (explained in "How to create a rule to flag users when they're approved as a Trusted Contact?").

Once the flag is there you can then use it as a selection rule in panels.


Get Media entity field values in custom validation handler

Digging the form_state I found the user submitted values for embedded media entites lies at form state storage. My validation code now looks like

/**
 * Implememts hook_form_alter().
 */
function mymodulename_form_alter(&$form, \Drupal \Core\Form\FormStateInterface $form_state, $form_id) {
  $operative_form = array(
    'my_node_add_form',
    'my_node_edit_form'
  );
  if (!in_array($form_id, $operative_form)) {
    return;
  }
  $form['#validate'][] = '_mymodulename_validate_element_node_form';
}

/**
 * Custom validation handler for EDP.
 */
function _mymodulename_validate_element_node_form($form, $form_state) {
  $form_storage = $form_state->getStorage();
  $form_storage_embed_entities = $form_storage['inline_entity_form'];
  foreach ($form_storage_embed_entities as $key => $value) {
    $media_entities = $value['entities'];
    foreach ($media_entities as $media_entity) {
      if ($media_entity['entity'] instanceof \Drupal\Core\Entity\EntityInterface) {
        if ($media_entity['entity']->getEntityTypeId() == 'media') {
          $asset_type[$media_entity['entity']->field_asset_type->value] = $media_entity['entity']->field_asset_type->value;
        }
      }
      if (count($asset_type) > 1) {
        // early bail.
        break;
      }
    }
    // Validation condition goes here.
    if ($validation_condition) {
      $form_state->setErrorByName('field_asset', t('Did you try turning it on and off.'));
    }
  }
}


Field configuration changes after clearing the cache

This is a strange problem which should not happen. I'm afraid you have some debugging to do.

First of all, try to reproduce the problem on a clean installation with just Drupal core, no additional themes or modules. If you can reproduce the problem, you probably found a bug in Drupal core. Search in the issue queue if it has already been reported. If not, report the problem in a new issue.

If you cannot reproduce the error with just Drupal core, it must be a problem in your site. Duplicate the site (so you're not destroying work you have already done) and turn off modules one by one. Once the problem goes away, you know you have roughly located the problem. Then you can either try to debug the module yourself, or go to the issue queue of that module and try to work with the module maintainer to figure it out.


How do I get the server time using REST GET HTTP?

/entity/date_format/long is just giving information on the date format

The easiest and cleanest way to do this is probably to create a simple custom REST resource in a custom module and within the resource you can return the server time using php functions

$message = [
    'time' => date("Y-m-d H:i:s"),
    'timezone' => date_default_timezone_get(),
];

You also have to implement CacheableResponseInterface in order to get the current time on every call to the service otherwise you are going to get a cached response.

Here is a working REST API time service module for this which I did just for the sake of this exercise


how Drupal refresh/rebuild its route automatically after route programmaticaly created?

I can't see anything in the module doing it, but this is done through the router.builder service.

Either rebuild immediately, with \Drupal::service('router.builder')->rebuild(); or tell it to rebuild at the end of the request, which is \Drupal::service('router.builder')->setRebuildNeeded()

Based on what you posted, it looks to me that you went through all the boring, generic stuff and stopped right before if would have gotten interesting, in that services rebuildIfNeeded() method. which checks the rebuildNeeded flag and rebuilds if TRUE.

So, you don't have to do anything to have that method called, that happens automatically if the service got invoked, you just have to make sure that flag is set.


Check if user has access to a certain page

If you want to verify if the currently logged-in user has access to a page, you can use the following code:

if ($router_item = menu_get_item($path)) {
  if ($router_item['access']) {
    // The user has access to the page in $path.
  }
}

$path is the path of the page you want to check (e.g. node/1, admin/user/user).

The code works in Drupal 6 and higher versions, and it is the one used from menu_execute_active_handler().

The reason I am not suggesting to directly call the access callback is because the arguments that need to be passed to that function.

The code used by _menu_check_access() is the following one (Drupal 7):

$arguments = menu_unserialize($item['access_arguments'], $map);
// As call_user_func_array is quite slow and user_access is a very common
// callback, it is worth making a special case for it.
if ($callback == 'user_access') {
  $item['access'] = (count($arguments) == 1) ? user_access($arguments[0]) : user_access($arguments[0], $arguments[1]);
}
elseif (function_exists($callback)) {
  $item['access'] = call_user_func_array($callback, $arguments);
}

The code, which needs to be as much generic as possible, doesn't directly handle a user object. This means that is not possible to replace the user object for the currently logged-in user with another user object.
The code must be generic enough to handle menu definitions such as the following ones:

$items['node/add/' . $type_url_str] = array(
  'title' => $type->name,
  'title callback' => 'check_plain',
  'page callback' => 'node_add',
  'page arguments' => array($type->type),
  'access callback' => 'node_access',
  'access arguments' => array('create', $type->type),
  'description' => $type->description,
  'file' => 'node.pages.inc',
);

$items['node/%node'] = array(
  'title callback' => 'node_page_title',
  'title arguments' => array(1),
  // The page callback also invokes drupal_set_title() in case
  // the menu router's title is overridden by a menu link.
  'page callback' => 'node_page_view',
  'page arguments' => array(1),
  'access callback' => 'node_access',
  'access arguments' => array('view', 1),
);

In both the definitions, the access arguments don't include a user object, and node_access() in this case uses the user object for the currently logged in user. In the second case one of the argument is the node object that is obtained from the URL; for example, if the URL is example.com/node/1, then the second argument passed to the access callback is the node object for the node with node ID equal to 1.
Writing code that handles these cases too would mean to duplicate code already existing in Drupal. Even if you duplicated that code, there would be still the problem of the access callbacks that are checking the access against the currently logged-in user.

If you want to check if a user that is not the currently logged-in user can access a menu is to first change the value of the global variable $user, use the code I reported at the beginning of my answer, and then restore the value of $user. For how to change the value of the global $user, you can see Programmatically impersonating another user without causing the currently logged-in user to log out. The difference is that, instead of using the value returned from drupal_anonymous_user(), you use the value returned from user_load().


Unfortunately there is no upgrade path for views from D6/D7 to D8 and plans for this in core are postponed.

See the latest comment for this issue https://www.drupal.org/node/2500547#comment-11402389. There is a contrib project mentioned, but this is at very early stage.


db_update() doesn't implement any interfaces that have join()/innerJoin()/etc. methods so I think you're stuck with using db_query() and writing the query string out manually.

$sql = "
  UPDATE field_data_field_TEST as ft
  left join node as n on ft.entity_id = n.nid
  set n.type = :type1
  where n.type = :type2";

$args = array(':type1' => 'test', ':type2' => 'foo');
db_query($sql, $args);


Adding the year to the date on the blogs

Change the date format in Regional and Language Settings to match your preference:

https://www.drupal.org/node/71106

Then (assuming you are displaying fields rather than full/teaser nodes) select the date format you require from by editing the field settings in views

And specifying which of the predefined (or custom) date formats you would like to use:


I've used the Dynamic Background module, which has a whole set of advantages for setting up background which vary according to content. At that particular time I used the Context module, which gave me a varied set of options (including content type, path, taxonomy, etc.) and which is very extensible. For your recipes, you could combine with the taxonomy functionality for different types of recipes, or select a particular image for each.

While I don't like using modules for everything, if this is going to be part of your day to day use of the site, I recommend that you choose the simpler solution, so you can try and choose what works better for you.

When you install the Module, you can set up which images you want to use, style the image and the type of behaviour you want for the whole site:

Since you can assign it using CSS, you can set it up for the content area only (#region-content), or whatever indicator you define in Panels. So, you can combine the logic in panels to show a particular background for a content type, or whatever logic you want to assign.


Count of entities with a certain field value, filtered by created date

Found a work-around -- http://drupal.org/node/847698#comment-3174900

Disable aggregation, then add filter, then re-enable aggregation.


hook_form_FORM_ID_alter in theme file to toggle field visibility

After a lot of banging on this, I found the right combo.  We don't have a custom admin theme, so I ended up moving this code in to a custom module.

The important part I was missing was [value] in ':input[name="field_news_topstory[value]"]' => ['checked' => TRUE]

use Drupal\Core\Form\FormStateInterface;

function mymodule_form_node_news_form_alter(&$form, FormStateInterface $form_state, $form_id) {
    $form['field_news_top_story_image']['#states'] = [
       'visible' => [
         ':input[name="field_news_topstory[value]"]' => ['checked' => TRUE]
       ]
   ];
}


This is probably connected to the module File Entity.
You find a patch in this issue:
https://www.drupal.org/project/file_entity/issues/3060204


This drives me nuts in Drupal Commerce. Now that you have the relationship, add a field to your view Content:Path using the relationship and tick boxes for Exclude from display then go to Rewrite results and tick the box next to Use absolute link (begins with "http://"). Move this field so that it appears above your image field. Then, in your image field, Link image to [Nothing] and under Rewrite results tick Output this field as a link and under Link path enter the token for your path.

Good luck.


How do I hide the page title based on node type using template_preprocess_page()?

OUTDATED - please use this solution instead ...

In D8 i used

function MYTHEME_preprocess_page(&$variables) {
    if (!empty($variables['node']) && $variables['node']->getType() == 'page') {
        $variables['title'] = '';
    }
}

You still find the "node" object but you can't simply call the "type". The variable is protected, so you have to get the value via the function getType(). To get an overview install Devel and print with Kint the methods. This should only be a simple help, but maybe someone can deeper explain the concepts. Is it better to unset $variables['title'] in some way then to use $variables['title'] = ''?


Some of the user profile fields on registration page not showing in user edit page

I think the custom fields comes under a new tab. The tab name would be the value you given in the category field . please check


Alright, after a lot of searching and testing things out i've found the following things to work:

For the checkbox it won't work with the data.element_name syntax (or at least in any variation that tried, and that's a couple dozen).  What will work is this: {{ webform_token('[webform_submission:values:ticketselectie]', webform_submission) }}.  In this example "ticketselectie" is the name of the checkbox element with 4 checkboxes in it (options).  What you get from this is a string containing the option text for each checked checkbox, seperated by comma.

You can use the twig split filter to extract an array out of checked checkboxes.
Turns out you need to use data.custom_composite_element.0.element_key as the syntax.  given that a custom composite element only ever has one row, it's always the 0 delta you need, and then the name of the key behind that.  So given a custom composite with the name "abonnementen", and in there two number fields with the names "minderjarigen" and "anderen", that leaves with the following syntax: data.abonnementen.0.anderen or data.abonnementen.0.minderjarigen

That's it really.  Took way too long to find that, and it's kind of weird to me that the "data." syntax didn't work for the checkbox element.  So if anyone knows a better way, please do reply.


How to intetrupt a form submission in drupal

Try adding the validate function as you have added the submit function:

function add_new_article_form_alter(&$form, &$form_state, $form_id){
  if($form_id=='announcement_node_form')
  {
    $form['#after_build'][] = 'add_new_article_after_build';
    $form['account_password'] = array(
        '#title' => 'Parola',
        '#type' => 'password',
        '#required' => TRUE,
    );

    $form["#validate"][] = 'add_new_article_form_validate';
    $form['#submit'][] = 'add_new_article_form_submit';

    return $form;
  }
}


I render it with following snippets and work correctly

$block = \Drupal\block\Entity\Block::load('simplenewssubscription');
$block_content = \Drupal::entityTypeManager()
    ->getViewBuilder('block')
    ->view($block);
$vars['newsletterblock'] = $block_content;


this may seem a silly suggestion, but have you tried going to /user rather then /admin the former being the login page, the latter being the admin pages once logged in?


Views taxonomy for multiple content types

You can achieve this by using views :

Create a new view with show content of type ALL -> continue and edit
Under format select show fields
Under filter criteria select Content: Has taxonomy term and select selection type Drop down later check Expose this filter to visitors, to allow them to change it and click apply

Result : You can have an exposed filter with taxonomy term that filters the contents irrespective of content type


Views Slideshow with numbered navigation disappears

Hi I don't normally post replies but I had a similar issue to you where my Carousel module with slide show stopped working in December 2013

Only when logged in as admin would I see the correct view

I was sure this has stopped about the time i updated some modules

After a bit of trial an error I noticed that the upgrade from 1.3 on 1.4 on Responsive Menus Module caused the issue

By using a 1.3 module the problem went away

Check which version you are using under 'Modules' and 'USER INTERFACE' section of administrator menu


I believe I found a fairly hacky answer for now. In feeds/mappers/content.inc I modified the function content_feeds_set_target after I added the money type to the array of included field types in line 18

function content_feeds_set_target($node, $target, $value) {

  $field = isset($node->$target) ? $node->$target : array();

  // Handle multiple value fields.
  if (is_array($value)) {
    $i = 0;
    foreach ($value as $v) {
      if (!is_array($v) && !is_object($v)) {
        $field[$i]['value'] = $v;
      }
      $i++;
    }
  }
  else {
    $field[0]['value'] = $value;
    //added these two lines to take care of the Money field
    $field[0]['amount'] = $value;
    $field[0]['currency'] = 'USD';
  }

  $node->$target = $field;
}

I know that this isn't the way to develop in Drupal and most likely I need to set up another content type or something along that line but this helped me (who am a complete noob to Drupal) to get started importing the price field.


How to see all keys for a PrivateTempStore?

No, with the current PrivateTempStore you don't have access to the list of keys. You're welcome to create your own TempStore class if you want different functionality, but I don't see why that is needed here.
The whole point of PrivateTempStore is to stash temporary data for a user, under a given key. If you don't know the key, then you have no knowledge of the type or structure of the data stored there, so in general you won't know how to use it. If your intention is to store a collection of data of a known type (stored in an associative array, for example) so that you can iterate over it later, then store the array itself under a known key, don't store each array element separately. Then you can retrieve the array later from the known key and do a foreach over each element of the array.


Referencing "type" in nodes returned by loadMultiple();

Thanks @berramou the solution is to use:

if ( $node->bundle() == "my_content_type" ) { ... }

Solved!


How do I find out the user name and password for an existing account?

If you have access to the database you can change the password with a simple query.  If you want to save one step from having to go to the MD5 website you could also use the MySQL built-in function with something like this:

UPDATE `users` SET `pass` = MD5('mynewpassword') WHERE `uid` =1;

Note:  That only seems to work for Drupal sites <= version 6.x.  If you are using version 7.x the MD5 hash will not work (I'm guessing it uses some sort of salt string on it).  To reset the password on version 7.x you can just change the email address of the admin user to your email address with a query like this:

UPDATE users SET mail = 'myemail@mywebsite.com' WHERE uid = 1;

Once that is done you can go to the normal login page and just request a password reset, and it will be sent to your email address.

Reference:  https://superuser.com/questions/104482/how-do-i-take-control-of-a-drupal-installation-on-my-web-space-without-the-admin


How to validate file using hook_file_validate?

In Drupal 7 just use drupal_set_message

/**
 * Implementing hook_file_validate
 * @param type $file : Object
 * @return type : array of error messages
 */
function hook_file_validate($file) {
    drupal_set_message("<pre>" . print_r($file, 1) . "</pre>");
    $errors = array();
    if ($file->source == 'field_article_file_und_0') {
        if ($file->filesize > 290081) {
            $errors[] = t("The file's exceeds upload limit. Please try again.");
        }
    }
    return $errors;
}


In Drush 8 you may access Symfony Console output object directly.

<?php

/**
 * @file
 * Contains example drush command.
 */

use Symfony\Component\Console\Output\ConsoleOutput;

/**
 * Implements hook_drush_command().
 */
function MODULENAME_drush_command() {
  $items['example'] = [
    'description' => 'Command description.',
  ];
  return $items;
}

/**
 * Callback function for example command.
 *
 * @see http://symfony.com/doc/current/console/coloring.html#using-color-styles
 */
function drush_MODULENAME_example() {
  $output = new ConsoleOutput();
  $output->writeln('<info>Green text</info>');
  $output->writeln('<comment>Yellow text</comment>');
  $output->writeln('<question>Black text on a cyan background</question>');
  $output->writeln('<error>White text on a red background</error>');
}


How to get custom entity data in custom page

This is the solution

$storage = Drupal::entityTypeManager()->getStorage('event');

$nids = Drupal::entityQuery('event')->execute();
//Load all nids
$events = $storage->loadMultiple($nids);
//You can also use
$events = $storage->loadMultiple();


How to add a button "Add More" with ajax for adding multiple fields?

In your form function, group the textfields under a key, you can define your own key. I use group here.

// Create wrapper for ajax
$form['group']['#prefix'] = '
';
$form['group']['#suffix'] = '
';

for ($i = 0; $i < $form_state['num_names']; $i++) {

  $form['group']['name_' . $i] = array(
    '#type' => 'textfield',
    '#title' => t('Name')
  );
}

In your ajax callback, return part of the form.

function ajax_add_col($form, &$form_state){

  $form_state['num_names']++;

  // rebuild whole form with new values
  $form_state['rebuild'] = true;

  return $form['group'];
}


Drupal 7 Rules: Compare Group Reference Field and fire Rule if data changed

I solved the problem by creating an own condition for rules using the API of the rules module.

function hook_rules_condition_info() {
  return array(
    'rules_condition_text_compare' => array(
      'label' => t('Textual comparison'),
      'parameter' => array(
        'text1' => array(
          'label' => t('Text 1'),
          'type' => 'text',
        ),
        'text2' => array(
          'label' => t('Text 2'),
          'type' => 'text',
        ),
      ),
      'group' => t('Rules'),
    ),
  );
}

See hook_rules_condition_info for more details.


Module for using Twitter's timeline widget on user's profile pages?

If you want to do this yourself, in broad strokes, you could create a custom module that does the following:

Creates two user profile fields that your users can edit if they want:

a.  Their Twitter User Name

b.  Their Twitter Widget ID
Creates a block that:

a.  Is displayed when a User Profile is displayed and these two fields are filled out that

b.  Takes these two fields from the user profile being displayed and integrates them into the HTML required by Twitter (see https://twitter.com/settings/widgets/new when logged into Twitter), eg, it outputs the twitter code from your previous question (https://drupal.stackexchange.com/questions/94079/allow-users-to-embed-twitter-feeds-without-allowing-script-tags) but fills in the USERNAME and WIDGET_ID with the values of these two fields.

Once again, Twitter is requiring this Widget ID, so whether or not this is confusing to your users is, unfortunately, irrelevant.


How do I turn off the add to cart message from Commerce site using Rules

You can't remove a message from the queue once it's been added via Rules, so you just need to reproduce the conditions in inverse from one rule to the next. In other words, you already configured the conditions in your custom rule to prevent the duplicate, so now put the opposite conditions on the rule that shows the normal Add to Cart message.


I don't think your approach will work, adding the new "alt" field to the edit/add form is only a small part of the task. Where and how you save the data? Instead, create a new field via the manage field section. Then you can use theme_preprocess or a tlp/twig file to change the output.


How to remove the home link in menu breadcrumb in drupal

You can check if your theme bring this option in appearance > Theme settings

Or you'll have to use THEME_breadcrumb hook. Here's the zen function, have a look at the bolded part.

function zen_breadcrumb($variables) {
  $breadcrumb = $variables['breadcrumb'];
  $output = '';

  // Determine if we are to display the breadcrumb.
  $show_breadcrumb = theme_get_setting('zen_breadcrumb');
  if ($show_breadcrumb == 'yes' || $show_breadcrumb == 'admin' && arg(0) == 'admin') {

    // Optionally get rid of the homepage link.
    $show_breadcrumb_home = theme_get_setting('zen_breadcrumb_home');
    if (!$show_breadcrumb_home) {
      array_shift($breadcrumb);
    }

    // Return the breadcrumb with separators.
    if (!empty($breadcrumb)) {
      $breadcrumb_separator = theme_get_setting('zen_breadcrumb_separator');
      $trailing_separator = $title = '';
      if (theme_get_setting('zen_breadcrumb_title')) {
        $item = menu_get_item();
        if (!empty($item['tab_parent'])) {
          // If we are on a non-default tab, use the tab's title.
          $breadcrumb[] = check_plain($item['title']);
        }
        else {
          $breadcrumb[] = drupal_get_title();
        }
      }
      elseif (theme_get_setting('zen_breadcrumb_trailing')) {
        $trailing_separator = $breadcrumb_separator;
      }

      // Provide a navigational heading to give context for breadcrumb links to
      // screen-reader users.
      if (empty($variables['title'])) {
        $variables['title'] = t('You are here');
      }
      // Unless overridden by a preprocess function, make the heading invisible.
      if (!isset($variables['title_attributes_array']['class'])) {
        $variables['title_attributes_array']['class'][] = 'element-invisible';
      }

      // Build the breadcrumb trail.
      $output = '';
      $output .= '
' . $variables['title'] . '
';
      $output .= '

' . implode($breadcrumb_separator . '

', $breadcrumb) . $trailing_separator . '

';
      $output .= '';
    }
  }

  return $output;
}

Zen provide an option to disable this feature :

$show_breadcrumb_home = theme_get_setting('zen_breadcrumb_home');
if (!$show_breadcrumb_home) {
  array_shift($breadcrumb);
}


Text format filter for embedding links and videos into body copy

A quick hack in Drupal 6 for the links would be:

<?php

function MYMODULE_filter($op, $delta=0, $format=-1, $text='') {
  switch ($op) {
    case 'list':
      return array (0 => t('MYMODULE Open Graph Link Maker'));

    case 'description':
      return t('Changes links into Open Graph Link Blocks with a thumbnail, title, and description');

    case 'no cache':
      return FALSE;

    case 'process':
      return _MYMODULE_og_block($text);

    case 'prepare':
      return $text;
  }
}

function _MYMODULE_og_block($text) {

  $text = preg_replace_callback("`(<p>|<li>|[ \n\r\t\(])(www\.[a-zA-Z0-9@:%_+*~#?&=.,/;-]*[a-zA-Z0-9@:%_+~#\&=/;-])([.,?!]*?)(?=(</p>|</li>|<br\s*/?>|[ \n\r\t\)]))`i", '_MYMODULE_link_to_og', $text);

  return $text;

}

function _MYMODULE_link_to_og($match) {

  $all = file_get_contents('http://' . $match[2]);      // alas get_meta_tags() only finds tags with name=, not property= like og: uses so we need to do this ourselves...
  $title=_MYMODULE_get_og_meta('title', $all);
  $image=_MYMODULE_get_og_meta('image', $all);
  $description=_MYMODULE_get_og_meta('description', $all);

  if ($title && $image) {
    $content=$match[1];
    $content.='
';
    $content.='';
    $content.='' . $title . '
';
    $content.=$description;
    $content.='
';
    $content.=$match[3];
    return $content;
  } else {
    _filter_url_trim(NULL,72);                       // these might be different in D7
    return _filter_url_parse_partial_links($match);  // but all it does is the default behavior of changing it into a link
  }

}

function _MYMODULE_get_og_meta($meta, $text) {

  $foo=explode('<meta property="og:' . $meta . '" content="', $text);  // I am sure someone out there can do this better with preg_replace_callback :)
  $bar=explode('"', $foo[1]);
  return $bar[0];

}

which looks for www.__ and creates a simple facebook like div from the facebook og: meta tags.  If you wanted to get fancier, of course you could look for the first image etc in the html in a similar fashion if they weren't present.

Now, I know you said you are using drupal 7, and I think that would be just changing MYMODULE_filter() to MYMODULE_filter_info() and changing up the arrays in the return as the filtering code itself should be the same.  Obviously, css style it how you want, I just threw in some quick stuff.

Also, this obviously doesn't do any of the fancy facebook ahah stuff but for something coded while watching Hawaii Five-O, I hope it helps you out a bit :)

Oh, somewhat obviously, to turn it on, you would go into your input filters and add/enable it for filtered_html, for example, and turn off the original one that changes www.__ into links so you don't refilter it again.


Form won't submit properly on the front page

I have discovered that I needed to make sure the form did not submit to the front page. I needed to set up a custom path for #action on the form, and make sure there was a callback defined in a module.

When landing on that callback, the validation and submit handlers successfully fire. I can then redirect users back to <front> if they are successful. The downside is that on error, there needs to be a separate page where the form is displayed. I couldn't find a way to show the error on the front page itself.

This is good enough for what I need. Thanks for the suggestions in the comments.


You need call form to Popup by function ctools_modal_form_wrapper

Any error, message will show in popup, to check submit success you need use statement

if (!empty($form_state['executed'])) {
    $output[] = ajax_command_replace('#modal-content', 'Thank you');
}

Or you can use ajax form to call ajax.

$form['markup'] = array(
    '#markup' => '

'
  );
//You need markup for wrapper
$form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Sumbit'),
    '#ajax' => array(
      'wrapper' => 'pop-up',
      'callback' => 'modal_form',
    ),
  );

And function submit form

function modal_form($form, &$form_state) {
  //Process data when form submit
  ctools_include('modal');
  ctools_modal_add_js();
  $commands = array();
  $commands[] = ctools_modal_command_display('Form Submit', 'Say Thank You');
  print ajax_render($commands);
  exit;
}


Using selected value of Entity Reference as filter for another Entity Reference

Found a categorically stunning module that does precisely what i needed over here https://www.drupal.org/project/ddf

Its simple to use as well. Install the module, enable Dynamic dependent fields and DDF Entity Reference modules after that.

Once that is done, go to your content type that contains the two or more enetity reference fields, using the example above that would mean editing content type user information. Now, go to manage fields, select edit on the entity refence field you want to be filtered, going back to the example again that would mean the state/province entity reference field, scroll down to the field settings section and on target type select node, on mode select the option Views: Filtered by an entity reference view with dynamic arguments, on views used to select the entities option choose the view that you have created for that entity reference - make sure that entity reference view has a contextual filter in it.

When all that is done, the last option is view arguments field and just below that the DDF module will give you a list of option that can be used as arguments to be passed to the entity reference views contextual filter... select one of them, in the example again, it would be something like {field_er_countries}.

Remember to save all your hard work and you should be good to go...


I can confirm this happens out of the box all the way back to at least 6.25.

You can 'fix' it pretty simply with the following code:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_form') {
    unset($form['basic']['#id']);
  }
}

That gives this markup in place of the old:

  Enter your keywords:

      <input type="text" maxlength="255" name="keys" id="edit-keys" size="40" value="book" class="form-text error">

    <input type="submit" name="op" id="edit-submit" value="Search" class="form-submit">


Drupal Commerce - creating a product catalog

You need to have the Product Reference module enabled and create your Product Display content type manually and add a product reference field to it. Then you can use this content type in Views.

Source: Creating Product Display Content Type


Drupal 7 sites hogging my shared hosting account

Shared hosting is the bane of the internet -- I recommend not using shared hosting if at all possible stick with the VPS. Did you turn on Aggregation, and caching in your drupal install? Did you install APC and configure drupal to use it. If you use APC and are a read-heavy anonymous traffic site, then APC can be configured to store all your pages in an in-memory cache and you never even hit the DB.

Tweaking a website to maximize server usage is really really website specific. The low hanging fruit is stuff like Performance settings in Drupal, APC, maybe Nginx for a webserver, etc. Beyond that profile your site.

Alternatively as you mentioned you could cache to disk by using like Boost.


If someone is facing exactly same issue, Here is what i did.

In my .theme file I've preprocessed search results like this

function YOURTHEME_preprocess_search_result(&$variables){
  $result = $variables['result'];
  $info = array();
  if($result['node']){
    $info['date'] = format_date($result['node']->getChangedTime(),'short');
  }

$variables['info_split'] = $info;
  $variables['info']['#context'] = array(
    'info' => $info,
  );
}

After this the date will be available in info_split.date variable and it will be automatically rendered as in the twig file all the info is rendered you can optionally render o hide some parts of the search listing.


Adding local task tabs to node display for specific content type

Solution from Matt B only hides the tab on the node view page, but not on the node edit etc. The direct url will also be accessible in that case.

A better solution is to write a custom access handler

See Custom validation of route parameters


Parse error: syntax error, unexpected '[', expecting ')' in C:\xampp\htdocs\drupal-8\core\vendor\react\promise\src\functions.php on line 62

Drupal 8 requires PHP 5.5.9 or higher (for short array syntax among other things).

You'll need to upgrade your version of PHP.

Source: System Requirements


In the view you need an exposed filter on the term field. In the settings for this field, expand on the "More" section near the bottom and you'll see a field called "filter identifier" - enter tid in this field (in this screenshot, you can see I used "category" it can be whatever label you want to give it). Click Apply this display. Save the view.


Why does the page callback have two arguments?

Menu callbacks are passed first the arguments defined in page arguments then excess arguments from the url.

So in the above example:

menufun/1/bar/baz

Will provide these vars:

$a = 1;
$b = NULL;

If you however provide an extra argument in the url:

menufun/1/bar/baz/2

You will transfer it to the menu callback:

$a = 1;
$b = 2;

The other advantedge is like tim writes, that it allows reuse of the same code for various cases, making the module more maintainable.


Image upload in content type, no previous image is present

A little more configuration is necessary to add the feature of browsing existing media, you can do it with Entity browser and Core Media module in Drupal 8.5 and upwards.

Here's a great tutorial on how to do that, you need the Part 4: How to Browse Media Assets: Managing Media Assets using Core Media in Drupal 8


Why is Views Nivo Slideshow block only displaying to logged in users?

I have some problems with blocks before and I always check the following, it has solved my problems so far.

Check your block permission.
Verify the block is assigned to a valid region setting in your template.
Rebuild the node permissions in admin/reports/status. Before doing this, backup your database and clear the cache.
Verify the access permission used from the view is view published content.

When I am working with views, I make sure the theme developer module is not enabled. I disable it, and then I clear the cache.


How to get multiple value with token_get_values()?

You cannot, using token_get_values(). The code that is returning the value of the token for a CCK field uses just the first value of the field. The function that gets the value of a token for a CCK field (content_token_values()) contains the following code. (See in particular the code between // [1].)

  $content_type = content_types($node->type);
  $node->build_mode = 'token';
  $node->content = array();
  content_view($node);
  // The formatted values will only be known after the content has been rendered.
  drupal_render($node->content);
  content_alter($node);

  $field_types = _content_field_types();
  foreach ($content_type['fields'] as $field_name => $field) {
    $items = isset($node->{$field_name}) ? $node->{$field_name} : array();
    $function = $field_types[$field['type']]['module'] . '_token_values';
    if (!empty($items) && function_exists($function)) {
      // [1]
      $token_values = (array) $function('field', $items, $options);
      // [1]
      foreach ($token_values as $token => $value) {
        $tokens[$field_name .'-'. $token] = $value;
      }
    }
  }

The function called in $function('field', $items, $options) is, for a text field, text_token_values(), which contains the following code.

  if ($type == 'field') {
    $item = $object[0];

    $tokens['raw']  = $item['value'];
    $tokens['formatted'] = isset($item['view']) ? $item['view'] : '';
    return $tokens;
  }

Despite content_token_values() passing all the CCK field values, the function just uses the first value.


Commerce add to cart form combined products: how to change default product

That checkbox you've mentioned is irrelevant, if I understand your request properly. The Add to Cart form assumes whichever product you reference first is the default product when it first builds the form (i.e. it has a product reference field value delta of 0).


Basically, you need to create a custom module and let ubercart know about your gateway using hook_uc_payment_gateway(), then use hook_uc_payment_method() to define a payment method.
Then, you continue with defining a form that is used on checkout and finish it with creating redirect to your external payment system.

You can start with this - http://nmc-codes.blogspot.sk/2012/07/how-to-create-custom-ubercart-payment.html, it should give you a good start.


Strict warning: Only variables should be passed by reference

That's not a Drupal error. It's a PHP error. You're getting it because the reset function expects an array to be passed by reference. You are passing it the return value of the array_keys function, which does not return its result by reference.

If you want to break down your code to avoid this error, try something like this:

$array_keys = array_keys($result['fieldable_panels_pane']);
$promobox_id = reset($array_keys);

Also, consider seeing this page for more information: http://www.php.net/manual/en/language.references.pass.php


How to make a multi-site instance aware of shared module directory?

Quick way...Run

variable_set('install_profile', 'name_of_custom_install_profile');
drupal_flush_all_caches();

from somewhere in the new site.

That'll trick your new site into thinking it was installed with the custom profile, and it should start checking that folder for contrib modules.


How can I use Javascript (Google Analytics) in my "Rewrite Results" in Views?

Views will indeed strip out onclick attributes.
You can work with data attributes and use an external JS file to add the onclicks.
Example for Views rewrite:

[myfield]

External Javascript (jQuery example):

jQuery(document).ready(function(){
 if(jQuery("a[data-event-type]"){
   jQuery("a[data-event-type]").click(function(){
    _gaq.push(['_trackEvent',jQuery(this).attr('data-event-type'),...........);
   });
 }
});


I save form data using hook_form_alter() but the data don't appear when editing the node from the UI

You need implement hook_node_prepare. This hook is used to load additional data before a node object is shown on the add/edit form.


Try flood_unblock module and flood_control I think both will help you with your requirements, choose the best based on your use case.


How do I alter the title of a menu link?

I suggest implementing a custom menu link plugin. The code below assumes your module name is example.

<?php

namespace Drupal\example\Plugin\Menu;

use Drupal\Core\Database\Connection;
use Drupal\Core\Menu\MenuLinkDefault;
use Drupal\Core\Menu\StaticMenuLinkOverridesInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * A menu link that displays number of points.
 */
class ExampleMenuLink extends MenuLinkDefault {

  /**
   * The database connection.
   *
   * @var \Drupal\Core\Database\Connection
   */
  protected $dbConnection;

  /**
   * Constructs a new points menu link.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Menu\StaticMenuLinkOverridesInterface $static_override
   *   The static override storage.
   * @param \Drupal\Core\Database\Connection $db_connection
   *   The database connection.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, StaticMenuLinkOverridesInterface $static_override, Connection $db_connection) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $static_override);
    $this->dbConnection = $db_connection;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('menu_link.static.overrides'),
      $container->get('database')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getTitle() {
    $count = $this->dbConnection->query('SELECT COUNT(*) FROM {example_points}')->fetchField();
    return $this->t('You have (@count) points', ['@count' => $count]);
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheTags() {
    // Invalidate these tags when number of points is changed.
    return ['example.points_count'];
  }

}

If you don't want to inject the database service the class would become much simpler.

<?php

namespace Drupal\example\Plugin\Menu;

use Drupal\Core\Menu\MenuLinkDefault;
use Drupal\Core\Menu\StaticMenuLinkOverridesInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * A menu link that displays number of points.
 */
class ExampleMenuLink extends MenuLinkDefault {

  /**
   * {@inheritdoc}
   */
  public function getTitle() {
    $count = \Drupal::database()->query('SELECT COUNT(*) FROM {example_points}')->fetchField();
    return $this->t('You have (@count) points', ['@count' => $count]);
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheTags() {
    // Invalidate these tags when number of points is changed.
    return ['example.points_count'];
  }

}

Next you need to put the link definition into example.links.menu.yml file.

example.user_points:
  route_name: <front>
  menu_name: main
  class: Drupal\example\Plugin\Menu\ExampleMenuLink
  weight: 30

The caching problem

Whenever the number of points is changed the menu link cache should be invalidated as follows.

 \Drupal::service('cache_tags.invalidator')->invalidateTags(['example.points_count']);

You need to find out the right place for this. If the points managed by contributed module check the module API and pick up an appropriate hook (hook_points_insert(), hook_points_delete() and so on).

Since the number of points is calculated for each user account individually you may consider using per account cache tags (something like ['example.points_count.' . $uid]). Therefore the cache will be preserved  for users with unchanged points.

To generate code for the Menu link plugin I used Drupal Code Generator.


How can I have editors select which blocks to be displayed in what order per page?

You can have a checkbox field for sidebar block in your content type. Once user selects a set of block to be visible, check those checkbox values in your page.html.twig. Print only those blocks which are checked by user.


How can I show the field setting options like "Style Settings", "Rewrite Results" in Views

It's a jQuery issue. Downgrade to 1.5 for administrative pages only (admin/config/development/jquery_update). Greater versions break views and other admin areas - not sure why though


If taxonomy vocabulary changes from Translate to Localize how to combine terms?

Looks like you should consider using the Taxonomy Manager module. From its project page:

... provides a powerful interface for managing taxonomies. A vocabulary gets displayed in a dynamic tree view, where parent terms can be expanded to list their nested child terms or can be collapsed.
The Taxonomy Manager has following operations and key features:

...
merging of terms (using the Term merge module in 7.x)
...


How to create a views export in XLS format?

The Views Data Export PHPExcel should suffice:

  This module extends Views Data Export module to allow XLSX files export.

That format is supported by Office 2007 and up.

Or go with what Brady said in comments and use CSV, it should be just as good.


Where are those images placed ?

If this is in content type, you can style the content type content by using custom tpl.php files and wrap your images in div there. (in sites/all/thems/yourtheme , that is.)

Also, you can create template files even for fields.

That gives you enormous power of controlling output :) .

It is bit "dirty", but you can also wrap images in div using jQuery. But first method is cleaner.


How to use Commerce Feeds to Import Stock for the Commerce Stock module?

Your problem sounds similar to the issue: Not recognizing product variants fields.

The solution is most probably to upgrade the Commerce Feeds module to 7.x-1.x-dev, or if you don't want to use a dev version you could downgrade the Feeds module to 7.x-2.0-alpha9.