Looks like you've largely answered your own question. But to confirm, Lightning generally does not pin to a specific version of core in it's composer.json file. The current constraint is ~8.3.1 (note the tilde) which means the current release of Lightning should work with core 8.3.1 to 8.3.9(repeating) but not 8.4.0.

Core is the exception to the rule. Lightning normally pins to specific versions of dependencies if they are patched (see Lightning's dependency constraint logic). But since core follows SemVer, has predictable releases, and Lightning releases every time core does, Lightning doesn't pin core - even when it is patched (which is pretty much always).

Lightning increments the second digit of its release numbers (the minor release) when Drupal makes a minor release. In the current release of Lightning (2.1.4) the one relates to the three in the current release of core (8.3.3). So Lightning 2.1.x should run on any core 8.3.x. That's why Lightning uses the tilde (~) modifier and three digits when specifying Drupal core constraints.


Panel with a view that is filtered dynamically by taxonomy term

To allow panels to provide the context, Under the pane settings, set the 'Required context' to 'Term ID' and besure that the 'Context is optional' setting is unchecked.


Contextual Filters > Default option: PHP Code input option is missing

Either the core 'PHP' module is disabled or you don't have the 'Use PHP for settings' permission.


Apachesolr Comments

  By default the apachesolr module index comments attached to the node.
  So you can not search comments directly. This module separates
  comments from the nodes and allows you to search them directly.

UPDATE:

For search api apply this patch

diff --git a/modules/callbacks.inc b/modules/callbacks.inc
index dca9e1d..e12be6a 100644
--- a/modules/callbacks.inc
+++ b/modules/callbacks.inc
@@ -80,6 +80,12 @@ function entity_metadata_comment_get_node_properties($node, array $options, $nam

     case 'comment_count_new':
       return comment_num_new($node->nid);
+
+    case 'comments':
+      $select = db_select('comment', 'c')
+        ->fields('c', array('cid'))
+        ->condition('c.nid', $node->nid);
+      return array_keys($select->execute()->fetchAllKeyed(0, 0));
   }
 }

diff --git a/modules/comment.info.inc b/modules/comment.info.inc
index 4321b4c..a9d7fe9 100644
--- a/modules/comment.info.inc
+++ b/modules/comment.info.inc
@@ -136,6 +136,13 @@ function entity_metadata_comment_entity_property_info_alter(&$info) {
     'setter permission' => 'administer comments',
     'type' => 'integer',
   );
+  $properties['comments'] = array(
+    'label' => t("Comments"),
+    'type' => 'list<comment>',
+    'description' => t("The node comments."),
+    'getter callback' => 'entity_metadata_comment_get_node_properties',
+    'computed' => TRUE,
+  );
   $properties['comment_count'] = array(
     'label' => t("Comment count"),
     'description' => t("The number of comments posted on a node."),

Taken from the source https://drupal.org/node/1414688#comment-7037540 and also worth looking at this http://blog.merge.nl/shorts/search-api-indexing-nodes-including-comments


There is a module that will do exactly that, called FAQ.

And it also integrates with Views should you need to extend it. But out of the box, it should do the two things you need (I have used it and did both things).


DrupalGap index.html No connection found on ios simulator

I met the same problem, but solved it by including the plugin of network-information. Then both ios and android work fine.

cordova plugin add cordova-plugin-network-information


How can I show an Ad popup after search form is submitted?

you could try a custom search-results.tpl.php to create a JS overlay while the results are being rendered


How to exclude a cache table from memcache?

You do it in the same way the  code you are showing does for cache_form.

$conf['cache_class_cache_abc'] = 'DrupalDatabaseCache';

Adding that line in the settings.php file, you are telling Drupal to save the cache for cache_abc in the database.

Keep in mind that, in Drupal cache terminology, cache_abc (which would be the name of the database table containing the cache data, when the cache is saved in the database) is called bin.


Follow the following steps:
Part one:
1. Install Views field view module and REST Export Nested (https://www.drupal.org/project/rest_export_nested)
2. First Create a View filtered by the content type mentioned, selecting Rest Export View.
3. Then Add nid, title and the special field Called "View" https://screencast.com/t/3la2zG6llfi
4. Duplicate this view as Rest Export Nested.

Part two:

Go and create another view filtered by taxonomy terms of your type(Product Availability), selecting Rest Export View.
Add as fields what you want to display for each term. For example, you can add the title of the term, and other fields.

I added 2 fields for example.
3. Add as the relationship the field name which is referenced to the taxonomy (Product Availability) from your content type(Products).
My content type is article and it has field_taxonomy which is a reference to the taxonomy term.
4. The last step on configuring this view is to add a contextual filter: Add "ID" and select to use the relationship created before,
selecting the "Provide default value" and choosing "Content id from URL".

5. Save this view.

Return to the first view created and configure the "View" field as the print screen is showed:
Choose the second view created in the "View " drop-down and o display "rest export". For contextual fields write the {{ raw_fields.nid }} . It will work only if you were added the node id as a field in this view above the "View" field.

The result will be the following:

Node id 1 has 2 field taxonomy terms assigned: "term 1" and "term 2", and in the view object, you can see that there 2 arrays, each array represents a taxonomy term with the fields values.


How to specify default options in a checkbox field using Field API

Try this for your instance creation:

field_create_instance(
  array(
    'field_name' => $default_notification_field_name,
    'entity_type' => 'user',
    'bundle' => 'user',
    'label' => t('Default settings for notifications'),
    'description' => t('Select the default notification options for the groups to which you subscribe, the contents you send and the replies to (your) comments. These default options can then be modified on a per-group, content or comment bases.'),
    'required' => FALSE,
    'widget' => array(
      'type' => 'options_buttons',
    ),
    'default_value' => array(
      0 => array(
        'value' => 'comment',
      ),
      1 => array(
        'value' => 'content',
      ),
    ),
  ));

To assist you in knowing the array structure, try this:

Install the devel module
Go to the page /devel/php on your site
Run this code to see all field information on your site:

// Show all fields.
dpm(field_info_fields());
// Show all field instances.
dpm(field_info_instances());


The pages that list content related to specific Taxonomy terms are created through views called Taxonomy term (usually at /admin/structure/views/view/taxonomy_term).

You can control what those pages output by editing that Views. I usually disable that original View and Duplicate it to work on overrides, so I can always refer back to the original if something goes wrong.

Which exact steps to take to exclude depends on your particular needs.

If there aren't that many nodes that need to be excluded you can just add the filter for node ID, use the Is not equal to Operator and enter the ID of the node that is not supposed to be found on Taxonomy term pages.

This solution will exclude that node from all the terms pages. If that node is referencing more than one term, it will not display on any of the terms pages.

To exclude more than one node you can add as many ID filters as you need, or more conveniently use the Regular expression, see this answer for more info: How to exclude multiple nodes based on their ID in taxonomy term view?

If you need to exclude your list of nodes from terms from one Vocabulary, but not from all the other Vocabularies, you'd have to modify the Contextual filter settings in those Views and configure separate ones for that special vocabulary and then the other Contextual for all the rest. You'd have to use the OR instead of AND (there's a module for that). This requires a bit more experience with Views configuration.

Another way may be to create a new field on your content, it probably makes the most sense to make it of type Boolean, that only have true/false states, and set those special nodes to True for that field (hide that field on Manage display, this is just your internal mark). Then in Taxonomy Views exclude the nodes that have that field set to True.

The advantage of this approach is that you control that when creating/editing nodes, while in the above solution you have to go edit Views each time.

Anything more than that you'd have to think about your site structure and change filters in Views to match that logic.


Drupal Commerce. Trigger shipping rules based on product field value

I eventually managed to get this working by dropping the idea of having custom fields and replacing them with taxonomy terms. For whatever reason (probably inexperience) I could not expose my custom fields to the rules module in order to trigger the shipping rules that I wanted.

By leveraging the Commerce Rules Extra module I was able first to trigger my shipping rules based on taxonomy terms instead of custom fields and secondly to define additional conditions for firing these rules with the help of the modules maintainer @MarcElbichon as discussed here https://drupal.org/node/2087815


Linking to front page with current selected language

Use the following code:

<?php print url('<front>', array('absolute' => TRUE)); ?>


There are four possibilities:

Using Git Bash for Drush. Off the top of my head, this won't work for SQL commands, though
If you're using Windows 10, you may want to install the anniversary edition update. It gives a Linux bash shell. It also has its limits (no kernel modules), but those limits shouldn't impede Drush use
CYGWIN. It may take some fiddling, but may do the trick too
Try and persuade your client to use Vagrant, then run Ubuntu in there


If I understand you correct, you want a menu to appear only at a certain content type? It is not done from there.

In Drupal 8 each menu is a block; After you have created the menu regularly with the native API unchanged, just add the block to the desired region and then set that block to appear only in a certain region you want it to appear in (You should see such an option in the block's conf page).


with the Permissions you can deny anything to anonymous (not registered) users you don't want them to do.
Also this may help.


I was able to do this by upgrading to the webform 4.0 beta version. and used [node:title].


Want to process node edit in two different ways

You can use revisioning module

Revisioning is a module for the configuration of workflows to create, moderate and publish content revisions.

Using this module when you edit a node, a new revision is created and it goes to modaration mode.

For more info check the module page


Your question is hard to answer because there are calendar modules.  How those modules are implemented could vary infinitely.

Drupal being so flexible you could pose this question to 10 people and get 10 different answers and they would all work!

If I were to have this problem I would look for a calendar module that would expose the data it may contain to Views so I could do anything I wanted with the data.  That would mean that the calendar module would use the Entity framework to save it's data which is the best way of doing things in Drupal.

The display of the calendar more than likely would not be a content type, it could be content you could insert into a content type using tokens or something like that or it may supply you a page and path to the calendar view or multiple paths.  Again I go back to you could pose this question to 10 people and get 10 answers.

This may not answer your question.  But your question is rather hard to answer without specifics in regards to modules.


Search Api Autocomplete doesnt filter by language

This issue has been fixed by fons vandamme via the drupal module issue tracker

function filter_by_language_search_api_query_alter(SearchApiQueryInterface $query) {
  //if query is of type search_api_autocomplete we will add our extra language filter
  if (strpos($query->getOption('search id'), 'search_api_autocomplete:') !== false) {
      dsm($query->getOption('search id'));

      global $language;

      $filter = $query->createFilter('AND');
      $filter->condition('language', $language->language, '==');
      $query->filter($filter);

  }
}

Make sure the language of your nodes are in the index.

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


This is your error:

General error: 2006 MySQL server has gone away

You can try to fix this in two ways:

my.ini

Open your my.ini file and locate max_allowed_packet. By default this is 1M. Setting it to 16M and restart your MySQL server. If the problem persists, try setting it to 512M and restart your MySQL server.

MySQL prompt

Enter your MySQL prompt, log in as user root or as a user with the SUPER privilege. Run the following command:

SET GLOBAL max_allowed_packet = 1024 * 1024 * 512;

This method doesn't require you to restart the server.


To be able to integrate with field API, you would need to declare your custom data thing as a fieldable entity. This is possibly, but it is quite a bit of work and then you'll have to add the field in a install hook.

What you can do as well is simply add a single 'fid' integer column to your table, add a form element of #type 'managed_file' to your form, which will automatically save the file for you and create an entry in the file_managed table. You can then simply reference the fid (file id) of that object. Also note that you need to call file_usage_add() so that the managed file knows that it is in use. When your object is deleted, use file_usage_delete() then the file will automatically be removed.

This is exactly what is done in Drupal 7 for profile pictures, have a look at user_save() for an example.


Format for webform submission node tokens?

If you use [webform_submission:node:field_sports:0:entity] you can get field values form the taxonomy term.

So to get the name, you can use:

[webform_submission:node:field_sports:0:entity:name]


How can I configure the backend to get a comfortable image insert functionality with captions?

Have you tried the Media module? From the project page:

Add media (images and video) into any textarea (requires Wysiwyg module).
Use the fields API (formerly CCK) to add fields to any type of media, eg. captions on images.
Plugins to use remote media from sites like YouTube, Flickr, ...
A unified interface for adding any type of media as a field to nodes.
Mass importing of files.
Drag and drop upload (with Plupload module).
Responsive image support (with Picture module).


hook_menu() and collapsable menu items with wildcard

I solved the problem with the Link Trail By Path module. This module add active class for 'parent' and 'child' link.


Code from standard Drupal profile is your friend: http://drupalcode.org/project/drupal.git/blob/c5d6e6334fb7a71ecf1dbc7e06a7de8ad9547b27:/profiles/standard/standard.install#l14

  // Add text formats.
  $filtered_html_format = array(
    'format' => 'filtered_html',
    'name' => 'Filtered HTML',
    'weight' => 0,
    'filters' => array(
      // URL filter.
      'filter_url' => array(
        'weight' => 0,
        'status' => 1,
      ),
      // HTML filter.
      'filter_html' => array(
        'weight' => 1,
        'status' => 1,
      ),
      // Line break filter.
      'filter_autop' => array(
        'weight' => 2,
        'status' => 1,
      ),
      // HTML corrector filter.
      'filter_htmlcorrector' => array(
        'weight' => 10,
        'status' => 1,
      ),
    ),
  );
  $filtered_html_format = (object) $filtered_html_format;
  filter_format_save($filtered_html_format);

Enable permission for system roles (code):

// Enable default permissions for system roles.
$filtered_html_permission = filter_permission_name($filtered_html_format);
user_role_grant_permissions(DRUPAL_ANONYMOUS_RID, array($filtered_html_permission));
user_role_grant_permissions(DRUPAL_AUTHENTICATED_RID, array($filtered_html_permission));
user_role_grant_permissions(variable_get('user_admin_role', 0), array($filtered_html_permission));


How do I allow an entity reference to be null in my custom entity?

The 'not null' instruction is automatically set to TRUE if that field is set in your entity's (entity_keys) annotations:

ex:

entity_keys = {
 *     "id" = "id",
 *     "uuid" = "uuid",
 *     "uid" = "uid",
 *     "price" = "price",
 *     "langcode" = "langcode",
 *     "complete" = "complete",
 *   },

In this case ->setRequired(FALSE) will be ignored.
However, if you really have to, you can force it to FALSE if you provide your custom storage schema handler.

Todo so add the handler in your entity annotations:

handlers = {
 *     "storage_schema" = "Drupal\YOUR_MODULE\YourEntityStorageSchema",
...
}

And the create YourEntityStorageSchema.php file:

<?php

namespace Drupal\YOUR_MODULE;

use Drupal\Core\Entity\ContentEntityTypeInterface;
use Drupal\Core\Entity\Sql\SqlContentEntityStorageSchema;
use Drupal\Core\Field\FieldStorageDefinitionInterface;

class YourEntityStorageSchema extends SqlContentEntityStorageSchema {

  protected function getEntitySchema(ContentEntityTypeInterface $entity_type, $reset = FALSE) {
    $schema = parent::getEntitySchema($entity_type, $reset);

    //then target your annoying field and set the 'not null' key to FALSE!
    if (!empty($schema['rp_payment']['fields']['operator_id']))
      $schema['rp_payment']['fields']['operator_id']['not null'] = FALSE;

    return $schema;
  }
}

Hope it helps! ^^


Instead of adding a <span> element, you could also use the ::before CSS selector. If a combination with :first-child or :nth-child() is not helpful, most likely you have to implement hook_menu_local_tasks_alter() and add a specific class to the desired link(s) (you can add them through attributes in localized_options of the #link property, see https://api.drupal.org/comment/25393#comment-25393) and then you could use the ::before selector. Or you could implement/overwrite theme_menu_local_task() (probably in combination with a theme preprocess or the earlier mentioned alter function) to add your <span> element.


It depends on what you want to generate. To get the \Drupal\Core\Url object for the node:

$node->toUrl();

To get a URL string:

$node->toUrl()->toString();

To get a \Drupal\Core\Link object:

$node->toLink();

To get an HTML string for the link:

$node->toLink()->toString();


You can implement a hook in your module. Ex:

/**
 * Update title of block based on the node type currently being viewed.
 *
 * Implements hook_block_view_alter().
 */
function my_module_block_view_alter(&$build, \Drupal\Core\Block\BlockPluginInterface $block) {
  // Only act on the block you want.
  if ($build['#id'] == 'your_block_id') {
    // Attempt to get the current node object from the route.
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node instanceof \Drupal\node\NodeInterface) {
      if ($node->getType() == 'type_a') {
        $build['#configuration']['label'] = t('Other Type As');
      }
      else {
        $build['#configuration']['label'] = t('All Type As');
      }
    }
  }
}

See api documentation for hook_block_view_alter for more info.


Hide the title or Change the Title style of one page based on page Title Multi site

If you're on a multi-site, you could just use the domain and add it to the body class. That way you can target the same content type differently on each site.

Using preprocess_html...

function THEMENAME_preprocess_html(&$vars) {
  global $base_url;

  // Split the URL
  $site_host = explode('/', $base_url);

  // Split the root domain from the TLD (.com).
  $site_host = explode('.', $site_host[2]);

  // Add it to your body class.
  $vars['classes_array'][] = drupal_clean_css_identifier($site_host[0]);
}

You might have to alter it a bit, but you get the idea. So if your domain was http://example.com, this would add example to the body class.

<body class="page-node page-node- page-node-194 node-type-product example">


In the settings of your view, change the format from "Unformatted list" to "HTML list".


You will want you view set up so that:

The view is displaying Users.
There is a relationship from User to Group
There is a relationship from Group to Manager
You add the contextual filter that defaults to the currently logged in user. Make this filter use the Group-Manager relationship.


create double view with same url alias for different theme

ok

create a menu with hook_menu
then with checking condition you want load your views in callback of your menu

Something like below

/**
 * Implements hook_menu().
 */
function mymodule_menu() {
  $items['myurl'] = array(
    'title' => 'title',
    'page callback' => 'myfunction_callbackfuction',
    'access callback' => TRUE,
  );

  return $items;
}

function myfunction_callbackfuction() {
  $view = views_get_view('view_name');
if($mycondtion)
  $view->set_display('page1');
else
  $view->set_display('page2');

  $view->pre_execute();
  $view->execute();
  print $view->render();
}


How to set which entities a workflow for Content Moderation applies to?

This is supported from Core 8.4, so you have to upgrade your site.  Then it shows up in the UI normally.


Controlling remote Drupal sites with Drush

You have a lot of questions there, but I'll try to give you the best overview of how to do this easily.

First, note that though Drush is listed as a module on Drupal.org, it is not technically a module as you don't "enable" or "disable" it like other modules.

Yes, Drush must be installed on the remote site.  When you do so, make sure to install the same version that you have installed locally.  It may still work if you're using different versions, but it can also cause strange bugs that are difficult to troubleshoot so always try to keep the same version.
It's certainly easier if you have SSH set up for some of the Drush commands.  Your web host should be able to help you with getting SSH keys set up for your local machine.
Yes, you will need to provide DB credentials.  This can be done by following the example in drush/examples/example.aliases.drushrc.php in the drush folder.
No, I don't think so.
You do not need to set up the alias on your desktop unless you are going to be logging in to your remote server and using aliases there.

Basically, if you have SSH working and have installed Drush on the remote server as well as your local machine, then, once you set up an alias, you can type something like drush @myremote status and it should work.


Git workflow from dev to live when central repo is in local network

Your question is a bit long, and too subjective. There are many ways to do things, and the answers to your questions are subjective. For better answers, post shorter questions that ask about a single factual item. It's hard to answer "what is the best workflow"-style questions on StackExchange; those are better handled on a discussion board.

Trying to pick out your specific questions: it is not necessary to use git to push to live, especially if you always keep a copy of the deployed code on your staging server.  It might be helpful to record the hash tag that you pushed to live somewhere when your script runs.  The main advantage to using git on the live site is that you don't need to do this, as you can use 'git log' to find out what is there.  If you do use git on the live site, be sure that the .git files are not accessible to the webserver.  I prefer to use this setup:

/path/www/mysite.com/.git
/path/www/mysite.com/htdocs/sites/all/default/settings.php

Regarding permissions, see also http://drupal.org/node/990812.  Hopefully I'll have this fixed up and committed soon. It has been languishing for a while; it works, but needs some cleanup in the flags, et.al.


Every Drupal.org project has a tab title 'Version control', click on it and it will take you to a page with Git instructions, including a section titled 'Creating a patch'.

See here for an example: http://drupal.org/project/wysiwyg_fields/git-instructions

Code below is copied from the D.o. instructions.

git checkout -b [description]-[issue-number]

Make your changes. Note the change in syntax for issue-related commit messages. See the Commit messages page for details.

git add -A
git commit -m "Issue #[issue number] by [comma-separated usernames]: [Short summary of the change]."

Roll the patch.

git status
git fetch origin
git rebase origin/6.x-1.x
git format-patch origin/6.x-1.x --stdout > [description]-[issue-number]-[comment-number].patch


drupal template files in different folders for different content types

See http://drupal.org/node/1089656 for more information on the possible file names that Drupal will recognize by default.

Drupal will not recognize contest.tpl.php as it is not one of the patterns that it recognizes.  If contest.tpl.php is an override of node.tpl.php then you should name it node--contest.tpl.php

If you want to override a page template in the same manner, see this previous post: https://stackoverflow.com/questions/5194109/drupal-7-candidate-page-tpl-name-for-particular-custom-content-type-entry/5194364#5194364


Do PHP static variables persist across Batch API batch items processing?

Static variables exist per request, so no, they won't persist across separate batch runs.

If you need to cache data across requests in memory just use redis/memcache/etc, there are contrib modules available for each that hook into the core caching stays so you can use a familiar API


Using a backup file to transfer a site to new directory

This will depend a little on which version of Backup and Migrate you are using.

Older versions only backed up the database, so you would also need to copy over the public and private files to the new site, along with the rest of the code.

Newer versions can backup files, but I don't have any direct experience with doing this.  It advertises that it can do either the public files, or the entire site.

Just keep in mind that Backup and Migrate will by default exclude the data from certain tables, mainly the cache files, logs, and the search index.  Rebuilding the search index can be a very expensive (and lengthly) process on a big site.  This is configurable, though.

There are other options, too, such as drush.


Why does Views PHP give me NULL for $row->path?

Found a workaround for using the alias path in Views PHP: [SOLVED] Views PHP $row->path showing Null

drupal_lookup_path('alias', 'node/' . $data->nid)

Question still unanswered. Will report issue.


KernelEvents::REQUEST is not fired on cached pages

The dynamic cache subscribes an event with priority 27. If you want that your code runs before that you have to use a priority >27:

  public static function getSubscribedEvents() {
    $events = [];

    // Run after AuthenticationSubscriber (necessary for the 'user' cache
    // context; priority 300) and MaintenanceModeSubscriber (Dynamic Page Cache
    // should not be polluted by maintenance mode-specific behavior; priority
    // 30), but before ContentControllerSubscriber (updates _controller, but
    // that is a no-op when Dynamic Page Cache runs; priority 25).
    $events[KernelEvents::REQUEST][] = ['onRequest', 27];

Which runs DynamicPageCacheSubscriber::onRequest..


Is there a Drupal Commerce integration with Facebook/Instagram Shopping?

I open-sourced my custom solution for using Facebook Product Catalog with Drupal Commerce 2.x.

While it isn't a plug-and-play module, with a few modifications it could be useful for you.

Check out my blog post to get more information: https://gorannikolovski.com/blog/drupal-commerce-and-facebook-product-catalog


How to make https links available to anonymous when new article is published?

Assuming both secure and non-secure websites are in fact the same Drupal instance, there are a few possibilities which may cause the issue you are experiencing:

Web server; configuration differences in secure non-secure sites.
Compare both website settings. Only difference should be SSL specific settings, rest should be same or inheriting settings from other's. if necessary, refer to web server's official documentation.
Web server; misconfiguration in redirect rules
From your comments it's clear that both websites are actually available. Still there could be redirect rules needs correcting.
HTTP or HTTPS version of the site has an external caching system
Check if there is caching system or proxy enabled for either of the sites. i.e. Varnish, Redis, CloudFlare.

Please provide some more details about the webserver (Apache, nginx, IIS, etc), and currently installed caching and performance related modules.

Also, you can consider serving the site only on HTTPS, to avoid penalties from search engines for duplicate content.


Customizing the comment form with custom user profile fields

The module Profiles2 will allow you to add fields through an associated profile structure and provides the familiar Drupal form format for managing fields.


The correct way is to create a custom module and implement hook_permission() to define an appropriate permission:

function hook_permission() {
  return array(
    'administer my module' => array(
      'title' => t('Administer my module'),
      'description' => t('Perform administration tasks for my module.'),
    ),
  );
}

Grant that permission to the roles that require access to it, and then use user_access() to make the access decision:

if (user_access('administer my module', $account)) {
  ...
}

As AyeshK points out in the comments, you don't actually need the second part - Views has n plugin for access based permissions already, which you can configure through the UI. So once you've added the permission and granted it to the relevant role(s), it'll be easy to get what you're looking for.


Inserting previously uploaded images into WYSIWYG editors

If you're using the Media module, any image uploaded should be available in the WYSIWYG insert media library tab.


CCK Nodereference individual imagefields

I don't think so, no. A node reference as its name suggests references an entire node. I've not heard of a CCK type that references another CCK field, though I could find a reference to a module that did that for D5. If that's your requirement, my recommendation would be to use an image-as-node method.


How do I apply a defined Image Style as a View Mode for a File field?

It appears that things have changed.

Applying image styles is now done exclusively through the structure->file types->images menu.

More extensive instruction can be found in this answer: How to set Media Styles in Media 7.1.2 / Media 7.2.X?


Generate only parent taxonomy terms in a block

In Drupal 7 to only show parent terms you add a “Contextual Filter” and add “Taxonomy term: Parent term,” then set “Provide default value” to a “fixed value” of 0.

That will filter out the child terms.


Can't connect to a remote MySQL during installation, drupal uses unix_socket instead of host?

I think I have located this issue. includes/database/mysql/database.inc, line 32:

// The DSN should use either a socket or a host/port.
if (isset($connection_options['unix_socket'])) {// will be TRUE if unix_socket is ''
  $dsn = 'mysql:unix_socket=' . $connection_options['unix_socket'];
}
else {
  // Default to TCP connection on port 3306.
  $dsn = 'mysql:host=' . $connection_options['host'] . ';port=' . (empty($connection_options['port']) ? 3306 : $connection_options['port']);
}

$connection_options['unix_socket'] will be an empty string if we leave it empty on the page. So this test will be TRUE. Replace isset with !empty solve this issue:)


Block changes do not save in admin/structure/block/ page

From my experience, this happens when you disable the Main page content block and save the changes. After doing this, clicking save will not do anything.

The simple fix is to enable the Main page content block, you should put it back under the Content region.


Yes, this is an issue with the module. Fortunately there is a patch.


enabling users to upload pictures from their harddrive in wysiwyg

I have used the WYSIWYG image upload module successfully on my previous D6 sites. It has good documentation and a simple interface to do what you need.


How to define a timestamp field using drupal6 schema

In short, you cannot do this because the schema API does not support the TIMESTAMP type.

  The MySQL implementation of the Schema API implements the datetime field using MySQL's DATETIME type. That type does not support automatic initializiation/update to the current time.

  MySQL's type TIMESTAMP supports automatic initializiation/update to the current time. Switching from DATETIME to TIMESTAMP is not an option, though:

  TIMESTAMP behaves differently in MySQL versions 4.1, 4.1.2, 4.1.3, 4.1.6
  The first TIMESTAMP column in a table behaves different than other TIMESTAMP columns in that table.


How to automate database table access as objects and provide common operations, like CRUD and views integraion?

Automatically, no (although if someone want to prove that wrong I'd be delighted to see the solution). However, everything you've asked for is easily attainable through Drupal's API:

For the database table, implement hook_schema() (no foreign keys are enforced in Drupal 7, though the relationships can be described for documentation)
For views integration implement hook_views_data()
For CRUD forms use the form API.

I think the closest you'll get to doing that automatically is the Entity Construction Kit. You can define your custom data as an entity, and I believe that module will create the appropriate entity forms for you. Integration with the Entity API module and Views means you can also expose that data, and you get field functionality built right in.

However, going that route will probably end up taking more code than doing it manually, and the reliance on the entity/field system will introduce extra overhead.

You might also want to look at the Doctrine ORM module; I haven't used it before, and it's only in dev, but if you can get that working it would give you objects mapped to DB tables as you're looking for. Exactly how that would fit into Drupal I'm not sure.

Things in Drupal 8 should be much better.


Anyone have any luck exposing Ubercart's "enter your VAT" part of the form?

This module is dependant on the billable address module being enabled. I did not need the billable module and thus is did not show (javascript dependancy).


Any way to use the Scheduler module with the Bean module?

Scheduler,

  ...allows nodes to be published and unpublished on specified dates.

As for Bean,

  Bean is an acronym that stands for Block Entities Aren't Nodes.

Emphasis mine in both.

So no, you can't use Scheduler with Bean as Bean doesn't use nodes. There's no such concept as "bean nodes".

I doubt you'll find a pre-built module with arbitrary scheduling for any type of entity. Being 'published' is a concept specific to the node entity type; not all entity types have that characteristic, so I doubt you'll find anything generic.

You'll probably need to write something from scratch. The code for scheduler will be the best starting point, but it'll need to be adapted to work with entities (or at least the Bean entity type).


I used panels for this. I added a new panel, which has the node with the nid of the webform as only content item in the main content area. I set the menu entry for the panel to "Menu Tab" and set the access rule of the panel to "Show only when node is of type person". This shows the desired tab element when a person node is selected.

For the webform itself I used the hook_form_alterwith the $form_id == "webform_client_form_<nid>" having <nid> as the node ID of the webform to set the #default_value of the webform field with the data coming from the person node. The ID of the person node I get by using the arg(1) function and the loading the node data with node_load($nid).

Hope that helps others.


How to configure REST server to create new node from URL parameters?

In order to create the node you must use the POST HTTP request so you can't do something like domain/endpoint?title=test&url=http%253A%252F%252Fwww.example.com(it's GET HTTP request). You can do the following to solve your problems:

First you need to make the Services 3.0 work with Firefox Poster tool. You can go Testing with REST Server for checking all the basic function in case you forgot to set the permissions or forgot to enable resources.
After you find out how to communicate with Services 3.0. You can use drupal_http_request to build your own POST/GET HTTP request. An example will be here Making authenticated requests to REST Server.


Calling function from other module does not work with module_load_include

You don't include the file extension in the third argument.

So this:

module_load_include('inc', 'node_clone', 'clone.pages.inc');

Should be this:

module_load_include('inc', 'node_clone', 'clone.pages');


How to add css class on click of CKeditor table button?

You can add copies of:
ckeditor.styles.js
ckeditor.config.js
to your theme directory

You can add a class using jQuery addClass

Be sure to set custom JS path under directory CKEDITOR profile settings.

*This was method under D7

D8
Option 1: You use this editor_js_settings hook to adjust ckeditor settings. A full list of settings can be found [here][3]

Option 2: Target item using jQuery addClass in the themes or custom module sites scripts.js file

Option 3: Create a custom module based on a copy of CKEDITOR module with a class added where you need it, or create a patch for the module to add your class. Classes to buttons are added here core/modules/ckeditor/ckeditor.admin.inc (be sure not to edit this core file)


How do other modules update elements using AJAX callbacks?

Thanks @Tasneem for directing me. I did it as follows:

function hook_form() {
  $form['select_element'] = array(
    '#type' => 'select',
    '#options' => $options,
    '#default_value' => $default,
    '#ajax' => array(
      'callback' => 'ajax_callback',
      'wrapper' => 'block_wrapper',
      'method' => 'replace',
    ),
  );

  $form['block_wrapper'] = array(
    '#type' => 'item',
    '#title' => t('Contents'),
    '#id' => 'block_wrapper',
    '#markup' => views_embed_view(...),
  );

  return $form;
}

function ajax_callback($form, $form_state) {
  $form['block_wrapper'] = array(
    '#type' => 'item',
    '#title' => t('Contents'),
    '#id' => 'block_wrapper',
    '#markup' => views_embed_view(...),
  );

  // Returning the entire $form here made the select element appear twice, so only return the wrapper element.
  return $form['block_wrapper'];
}


The edit function is usually provided in teasers with contextual links.

Activate the optional core module, and when the teaser is displayed, a contextual links icon will be displayed at the upper right corner of the rendered teaser.


Problem with calling drupal_get_form from an AJAX callback

Ensure that Drupal.attachBehaviors() is called from your AJAX callback. See Drupal 7 JavaScript API for more details.


You can add a "Content: Nid" contextual filter to your view, so your view will narrow down the content to the NIDs you provided. Make sure you check the "Allow multiple values" box when configuring the contextual filter. This will allow a url like example.com/myview/12+45+78 which would limit the results to node IDs 12, 45 and 78.


For someone who is not a programmer or is starting how can he/she contribute to Drupal.org?

Both @David and @Patrick have put it well, on the ways to contribute to the Drupal community. I think a good place to evaluate yourself and then start contributing would be at Drupal Ladder.
It was a result of the work from the guys from Boston, who came together and started something called Boston initiative where they come together and work on contributing.

You can look at the ladder screenshot below :

If one wishes to contribute, s/he is suggested to follow this steps starting from bottom and climbing the ladder one step at a time.

For more, you can also view the session about Drupal ladder at DrupalCon Denver.

P.S. : The Drupal Ladder was designed to encourage users to contribute to Drupal core and not did not focus on contribution towards the modules (contributed).


How to resolve my 404 error when using hook menu?

I tested the code by adding that path and it works.

I suggest the following steps debug:

Make sure that Drupal is able to flush the cache without any problem by checking if there is any errors at admin/reports/dblog
If you didn't find any errors when you flushed the cache, try to add a die('checking hook_menu') on your hook_menu implementation to see if the hook is being executed.
If you are not going to pass any arguments to that callback I suggest you to remove the line 'page arguments' => array(),
Check your Apache/NGINX settings, it could contain something that is affecting that path.


You can override views-exposed-form.tpl.php template.
In this overrided template you can putup own div wrapper etc.
How to override any template(tpl) visit here.

You can also use hook_form_alter. It perform alterations before a form is rendered. So using this add some alteration on form.


Save Ubercart order in database, processed through custom payment gateway

You do not need to implement that hook.

First you need to be sure whether the payment service method is gateway or redirect. Depending on this, the payment complete function is different.

Within that function, regardless how it is implemented, here is a list of functions that are helpful.

uc_cart_complete_sale()

  This function is utilized by the default checkout system and can be
  used by third party checkout integration modules to complete a sale.

uc_order_comment_save()

to leave comments in the order regarding the payment outcome, as well as watchdog()

uc_payment_enter()

  This function logs a payment for an order in the payment receipts table.


How to create a user1, user2 and 3 others like this post?

If this is already in a view -- you can do the flag/like counts by adding a relationship to the view (I'm assuming you're on Drupal 7).  Add the 'Flags: Node flag counter' relationship and select the flag you want the counts for.

Then you can add, for each piece of content in your block or page, the 'Flags: flag counter' field.  That'll appear only once you've added the relationship.  Make sure to select for it to use the relationship.

Let me know if this doesn't make sense and I can elaborate a little more.  :-)


You can do this by using any of these modules :

User Protect

  This module allows fine-grained access control of user administrators,
  by providing various editing protection for users. The protections can
  be specific to a user, or applied to all users in a role.

Role Deligation

  This module allows site administrators to grant some roles the
  authority to assign selected roles to users, without them needing the
  administer permissions permission.

Administer Users by Role

  This module allows site builders to set up fine-grained permissions
  for allowing "sub-admin" users to edit and delete other users — more
  specific than Drupal Core's all-or-nothing 'administer users'
  permission. It also provides and enforces a 'create users' permission.


A button to delete multi images on one click from imagefield

Refer to the question about "Delete multiple images at once from one node in Drupal 7", which appears to be similar to yours.

You may also want to look at the article about Drupal 7 Unlimited Fields Remove Button, from where you can also download the Unlimited Fields Remove module.


Programmatically populate file field using Entity API

Ok, I found the answer to this question here.

Instead of:

        $file = file_save_data($file, $folder.$filename, FILE_EXISTS_REPLACE);
        $entity->$key= (array)$file;

It should be:

        $file = file_save_data($file, $folder.$filename, FILE_EXISTS_REPLACE);
        if($file !== false)
        {
          $entity->$key->file->set($file);
        }

This 'if($file !== false)' is optional just to be sure that we're passing a file object.

  *Note that the difference is that we're not passing the file object as an array and also we're passing it to a 'file' atribute instead of
  passing it directly to the field.


Where are the "Replacement Patterns" (Tokens) in "Set Data Value" in Rules?

It depends on the type of the selected target data whether tokens can be used for the value or not.

For example if the target is a simple text field (e.g. node:title) then the value can be specified with tokens. On the other hand, if the selected target is for example an entity (e.g. node:field-tags:0), then token input is not possible.

When working with formatted text, it is necessary to drill down to the value column of the field. E.g. for the node body, specify node:body:value.


How does a PaymentGateway signal a completed order

A similar scenario has been discussed on #commerce Slack on Monday. In contrast to onReturn() no transition is triggered after onNotify().
@bojanz says:

it's a safeguard we'll need to add to Commerce, but won't have the resources to do so before october
once we have $order->balance and an order paid in full event, we can use it to auto-place the order
at least those two parts could land in september for 2.10

TL;DR
onReturn() must create a Payment, as suggested in a comment from @No Sssweat. In case PaymentGatewayException is thrown Commerce will redirect to the previous checkout step.
onNotify() can register info about payment but, at the current state, it won't place the order for you.


After a bit of dabbling, I got the answer. ->condition("grupkodu", NULL); is not sufficient, it needs to be ->condition("grupkodu", NULL, "IS NULL");


'Create Node' form as part of panelized page

You have to add a Context Node add form to your panel and afterwards, you can select the appropriate edit form in the 'Form' section when you add content to the panel.


How to insert images into custom block type

With twig you can use {{ directory }} to point your theme directory.


If you are comfortable with PHP, you could create a form that has all the students in a class and displays the student's name and then their grade.

Rather quickly, you could create a custom module and include several drupal hooks in it.  It would start out with something like this:

function YOURMODULE_menu() {
  $items=array();

  $items['class/grades'] = array(
    'title' => 'Class Grades',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('YOURMODULE_class_grades_form'),
    'access callback' => 'user_is_logged_in',
  );

  // any other menu items here

  return $items;
}

This creates a menu item so that when someone goes to

www.yoursite.com/class/grades

they will be shown a form.  NOTE:  With access callback set to user_is_logged_in, that means ANY logged in user on your site can do this but I am just trying to show you the broad strokes here.

We need to get the form, but before we go there, for another broad stroke, you will need to create a view that returns a list of student nodes. In the fields, just return the nid of the node.  If you hit preview, we want to see something like 13, 27, 55, 99, or whatever the nids are.  In that node, I am also going to assume you have a text field called grade that stores the grade for that student in the class.  For this, I will also assume this view is called just_the_nids.

Now, let's define that form:

function YOURMODULE_class_grades_form() {
  $form=array();

  $result=views_get_view_result('just_the_nids');

  foreach($result as $r) {
    $node=node_load($r->nid);
    $form[$r->nid] = array(
      '#title' => 'Grade for ' . check_plain($node->title),
      '#default_value' => !empty($node->field_grade[0]['value']) ? $node->field_grade[0]['value'] : '',
      '#type' => 'radios',
      '#options' => array(
        'A+' => 'A+',
        'A' => 'A',
        'A-' => 'A-',
        'B+' => 'B+',
        'B' => 'B',
        'B-' => 'B-',
        'C+' => 'C+',
        'C' => 'C',
        'C-' => 'C-',
        'D+' => 'D+',
        'D' => 'D',
        'D-' => 'D-',
        'F' => 'F',
      ),
    );
  }

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Grade'),
  );

  return $form;

}

What this does is grab the view you created and loops through it, loading each node and grabbing the title, which I hope is the student's name and then displays the grade of that student with radio buttons.  I know we could have returned the title and grade in the view and used it here, but just trying to "show the math" which might help later on :)

At this point, if you saved everything and flushed your menu cache, you could go to the page and see some like this:

Jill Doe
 ( ) A+
 ( ) A
 ( ) A-
  .
  .
  .

Doug Drupal
 ( ) A+
  .
  .

[GRADE]

However, pressing the [GRADE] button at the bottom of the page wouldn't do anything because we haven't declared what it should do other than just submit the form.  So we do that like this:

function YOURMODULE_class_grades_form_submit($form, &$form_state) {
  foreach ($form_state['values'] as $nid => $grade) {
    if (is_numeric($nid) && !empty($grade)) {
      $node=node_load($nid);
      $node->field_grade[0]['value']=$grade;
      node_save($node);
      drupal_set_message(check_plain($node->title) . '\'s grade set to ' . $grade);
    }
  }
}

What this does is go though the form and load each node again and set the grade field to what you clicked on in the form and then save the node back again with just that field changed (along with a perky drupal message telling you what it did :)

Now, what this doesn't do that it should for primetime:

Menu per class (unless you only have one)

Security (every logged in user can do this)

Internationalization (I didn't use t() where appropriate)

CSS Style (it isn't fancy, eg, the radios all go down vertically instead of horizontally, etc)

I assumed A-F grading, and also saved the text, You could get fancy here and store 4.0 for an A+, 3.7 for an A, etc, but right now it saves the actual text of the grade but anyway I hope it might give you some ideas on how to do it.

I also assumed D6, D7 has slightly different field structures.

A lot of information on the ins and outs of all this can be found in the Drupal Form API Quickstart Guide


Responsive bootstrap grid with 6 columns of equal heights

You should use 'Bootstrap Grid' format for Views in some cases, which you'll be able to select after install/enable of the Views Bootstrap module. Here is a quote about this module (from its project page):

  ... enables you to create components following the theme structure of the Bootstrap framework all within the configuration settings of the powerful Views module.


Disable Product Display upon purchase of the Product or it's variations

The Disable product when it was purchased issue on d.o. deals exactly with this problem.


How to reorganise files location without updating each node manually?

Yes there is a way to fo this, I have the same situation in my previous project and I have achieved this by using below code:

    $field_name = 'FIELD_MACHINE_NAME';
    $entity_type = 'ENTITY_TYPE'; // Node or user
    $bundle = 'BUNDLE'; // Content Type.
    $table_field = $field_name . '_target_id';
    $table = $entity_type . '__' . $field_name;
    $db_conn = \Drupal::database();
    $query = $db_conn->select($table, 'th');
    $query->leftJoin('file_managed', 'fm', 'fm.fid = th.' . $table_field);
    $query->fields('th', ['entity_id', $table_field]);
    $query->fields('fm', ['filename']);
    $query->condition('bundle', $bundle);
    $entity_results = $query->execute()->fetchAll(\PDO::FETCH_ASSOC);
    foreach ($entity_results as $result) {
      $fid = $result[$table_field];
      $file_load = File::load($fid);
      if ($file_load) {
        $new_directory = 'NEW DIRECTORY PATH';
        $new_uri = "public://" . $new_directory . "/" . $file_load->getFilename();
        $db_conn->update('file_managed')
          ->fields([
            'uri' => $new_uri,
          ])
          ->condition('filename', $file_load->getFilename())
          ->condition('fid', $fid)
          ->execute();
        drupal_set_message('File path changes successfully for for node id ' . $result['entity_id']);
      }
      else {
        drupal_set_message('Unable to load file for node id ' . $result['entity_id'], 'warning');
      }
    }

Here you have to be very careful while moving this to production. Backup DB and files before running this code.

And drush cr or clear cache after running this code for every field.


Where do I find the Facebook application id for the the fb_social module?

Login as FB app admin
Go here: https://developers.facebook.com/apps
Copy the destination for "Edit settings" link for your app
Take app ID from the URL. This is the pattern: https://developers.facebook.com/apps/[your app ID]/summary


As some people already mentioned and the error itself describes, this is a variable interpolation/auto-quoting problem.

The most appropriate option here - following the D.O.'s documentation - would be to use where(), instead of condition().

  $query->where($snippet, $args = array())

  The where() method allows for the addition of arbitrary SQL as a conditional fragment. $snippet may contain any legal SQL fragment, and
  if it has variable content it must be added using a named placeholder.
  The $args array is an array of placeholders and values that will be
  substituted into the snippet. It is up to the developer to ensure that
  the snippet is valid SQL. No database-specific modifications are made
  to the snippet.

  (Copied from https://www.drupal.org/node/310086)

And here is a rewrite of your code:

$query=db_select('pg_index', 'i',array('target' => 'import'));
$query->join('pg_attribute' , 'a' ,'a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey)');
$result = $query
    ->fields('a', array('attname','atttypid','atttypmod'))
    ->where("i.indrelid = 'semstudent'::regclass")
    ->condition('i.indisprimary', true)
    ->execute();

I just tried this and it worked without any problems, hope it works for you too!


Is there any replacement module for token actions and token starter modules in D7?

From Dave..Mainter of token module... (As Received)

The Token Actions module has been replaced by the actions provided by core that support tokens. Use the follow button on http://drupal.org/node/1902294 to track progress for migrating those deprecated actions to system-provided ones automatically.

The Token starter is not an actual module that is intended to be used. It's just an example of how you make new tokens. It was deprecated by the token example module in http://drupal.org/project/examples. You should instead make a custom module with a good name for your custom tokens, rather than re-using the token starter module.


Display subscribe to group on access denied page

You have a couple of options.

Not sure how you have your group node page setup but what I have done is use a node view panel.  In that panel I added the Field: Group (group_group) in a region then set the formatter to "OG subscribe link".  That will display the "Subscribe to group" link when a user clicks on the group they are not a member of.  Since you are getting access denied I'm guessing your group node page is not setup that way.

Another option is to modify the og-list view and add the field "Content: Group".  Then change its Formatter to "OG subscribe link".  That will create a new column in the view that will display a link called "Subscribe to group" for groups you are not a member of and "Unsubscribe to group" for groups you are a member of.


How to trigger a Rules action based on which content pane of a panel is used?

Have a look at the Rules panes module. Some details about it (from its project page):

Rules Panes allow embedding Rules components as content panes in Panels (or so).
By default any parameters for the component are entered manually by the end user, but they can also be pre-populated with CTools contexts on the page (which will also hide the form input).

So if you can find a way to transform your "... rules to perform some action ..." in a Rules component, you should be good to go.
Some pointers to some more docu/demos about it (also mentioned on its project page):

Videos introducing this module.
Presentation from DrupalCamp Stockholm 2013.
Video about Rules panes.


I extended some functionality in the slick module, but I am looking to do it in a way that doesn't get erased each time I update slick

In my opinion, the easiest way to preserve changes to contributed code is to manage your dependencies through Composer and use patches. When you update slick in the future, the output of the command will directly tell you which of your patches have been broken by the update.


if you don't want to upgrade the jQuery version. Please try this.

http://jsfiddle.net/ravindrasingh22/3HVpW/

$(document).ready(function() {

    var changeTooltipPosition = function(event) {
      var tooltipX = event.pageX - 8;
      var tooltipY = event.pageY + 8;
      $('div.tooltip').css({top: tooltipY, left: tooltipX});
    };

    var showTooltip = function(event) {
      $('div.tooltip').remove();
      $('
I\' am tooltips! tooltips! tooltips! :)
')
            .appendTo('body');
      changeTooltipPosition(event);
    };

    var hideTooltip = function() {
       $('div.tooltip').remove();
    };

    $("label#tooltip2'").bind({
       mousemove : changeTooltipPosition,
       mouseenter : showTooltip,
       mouseleave: hideTooltip
    });
});

HTML Code

Mouse Hover here

CSS Code

#hint{
     cursor:pointer;
    }
    .tooltip{
        margin:8px;
        padding:8px;
        border:1px solid blue;
        background-color:yellow;
        position: absolute;
        z-index: 2;
    }


Convert db_query to db_select or EntityFieldQuery

Yes, if you're querying entity/field data you should pretty much always use an EntityFieldQuery in place of raw SQL. If you're not querying entity/field data, and need to build up a dynamic query, then db_select() is probably the way to go.

I'd also recommend reading the DB API docs and making sure you understand how to use db_query() properly - currently your code is likely to be susceptible to an SQL injection attack, as you're not using parameterized queries.


Change the status to "complete" manually may not trigger the rule. Instead, applying a payment for the order manually may work.
See here


Form Display: How to move elements out of the advanced container?

These Fields are organized in different groups in NodeForm::form.

So the settings from Manage Form Display wont work until the #group property of the fields is unset or the surrounding container is unset.

This can be done with one of the form alter hooks in your theme or custom module.

For example the hook_form_BASE_FORM_ID_alter:

function your_theme_form_node_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
    unset($form['author']);
}

This will unset the author container. The containing fields Authored on and Authored by can than be moved around with the Manage Form Display Form.


Is there any way to reuse the same file or image?

The short answer is: Yes!

And you also don't have to wait till 8.4 comes out (however that will make things easier).

I suggest you the following modules:

Media Entity
Media Entity Browser
Media Entity Image

How is it working? (in nutshell):

Instead of using "image fields" you will have reference fields to media entities (Media Entity), which provides you the opportunity to use such an entity multiple times, also by other contents.
Media Entity Image gives you just a predefined bundle to media entity, which is a nice to have.
Media entity browser gives you a widget, which opens a modal, where you can select from existing media images, or upload a new one!

Drupal 8.4 will provide this as a core feature, which will make it more stable and easier to use. But until then: these three modules also do the job.


Modify token used in path URL alias generation

We found the solution using the sample found on How To Create A Custom Token In Drupal 8?

Code

/**
 * Implements hook_token_info().
 */
function my_module_token_token_info() {
  $info = [];
  $info['types']['my_token_group'] = ['name' => t('Custom Group'), 'description' => t('Custom Group')];
  $info['tokens']['my_token_group’][‘my_token’][] = 'A token to extract desired characters from Node body to be used in meta descriptions';
  return $info;
}

/**
 * Implements hook_tokens().
 */
function  my_module_token_tokens($type, $tokens, array $data, array $options, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) {
  $replacements = [];
  if ($type == 'my_token_group') {

    foreach ($tokens as $name => $original) {
      // Find the desired token by name.
      switch ($name) {
        case ‘my_token’:
          $node = $data['node'];
          if(is_object($node) && !$node->myFieldName->isEmpty()) {
            $token_value = $node->myFieldName->value; // or something similar.
          }
          else {
            $token_value = $node->label();
          }
          $replacements[$original] = $token_value;
          break;
      }
    }
  }
  return $replacements;
}


Add another node in create content Drupal 6

Try out Multi Node add module.

  This module provides a new interface for creating nodes where the
  users are able to select the fields what they want to use for creating
  the nodes.


i have an idea if you use string override module .this module provide the override  the local task menu.

http://drupal.org/project/stringoverrides/


How to configure URL paths using the pathauto module for multilingual sites?

Consider using the Pathauto i18n module for this. Excerpt from its project page:

  ... by default Pathauto creates alias only for one language or for all languages one alias. This module provides functionality to create aliases for each language. Also this module will be helpful, if you use field translation and you want show node on all language with paths, different from node/nid.

This module contains 3 submodules which can be used to enable separate functionality for each entity:

pathauto_i18n_node (for nodes).
pathauto_i18n_user (for users).
pathauto_i18n_taxonomy (for taxonomy).

Example (also from project page):

When you create node without pathauto_i18n:

English alias: en/articles/first_article
Italiano alias: not exist
Deutsche alias: not exist

When you create node with pathauto_i18n:

English alias: en/articles/first_article
Italiano alias: it/articolo/first_article
Deutsche alias: de/artikel/first_article


altering access callback in hook_menu_alter

function enge_events_menu_alter(&$items){
  $items['node/%entity_object/registrations']['access callback'] = 'user_can_manage_registrations';
  $items['node/%entity_object/registrations']['access arguments'] = array(1);
  $items['node/%entity_object/registrations/list']['access callback'] = 'user_can_manage_registrations';
  $items['node/%entity_object/registrations/list']['access arguments'] = array(1);
  $items['node/%entity_object/registrations/settings']['access callback'] = 'user_can_manage_registrations';
  $items['node/%entity_object/registrations/settings']['access arguments'] = array(1);
  $items['node/%entity_object/registrations/broadcast']['access callback'] = 'user_can_manage_registrations';
  $items['node/%entity_object/registrations/broadcast']['access arguments'] = array(1);
}

$items should be reference variable... For more information hook_menu_alter


You can do that by creating a block as follows

Go to admin/structure/block and add a new block as follows

set show block for anonymous user.

and set the Region where you want to display the link on Front page. and if you want to display the link only at front page. make the following settings


Leaflet views: how to zoom on the marker while clicking on it in order to get the popup

Install and enable jQuery update. Set the jQuery version to >= 1.7.

Create a module, then create a zoom.js JavaScript file and paste this:

(function ($) {
  Drupal.behaviors.MYMODULE = {
    attach: function (context, settings) {
      $(document).bind('leaflet.feature', function(e, lFeature, feature) {
        lFeature.on('click', function(e) {
          var lMap = Drupal.settings.leaflet[0].lMap;
          lMap.setView(e.latlng,8);
        })
      });

    }
  }
})(jQuery);

Use your module name instead of MYMODULE

Then use drupal_add_js() in your module to include zoom.js. Note the weight option:

  drupal_add_js(drupal_get_path('module', 'MYMODULE') .'/zoom.js',array('group' => JS_DEFAULT, 'weight' => -5));


I've never used panels, but it can be a permission problem. As far as I know, to view and publish unpublished content you need to have set the "administer nodes" permission. To let some roles manage certain unpublished content types without granting them more than they needed, once (in D6) I successfully used the view_unpublished and Publish content modules.

Hope it helps.


You can look at Multipage jumplist module which provides a block that allows you to access all multipages.

To apply the ajaxified multipage fieldgroups, use: Field Group Ajaxified Multipage module which allows you to enable AJAX for multipage groups
It also provides developers with special variables attached to form array regarding page status to allow them further customize the form (e.g. form_alter) depending on active page (in this case saving your pages).


Use the hook_preprocess_html:

function THEMENAME_preprocess_html(&$vars) {
  foreach($vars['user']->roles as $role){
    $vars['classes_array'][] = 'role-' . drupal_html_class($role);
  }
}


Quiz Module - Restart (Reload) the question of the quiz when it has been wrongly attempted four times

It's kind of hard to decide what to do without code samples, but the following ideas come to my mind:
First, you could try a simple PHP command in the form of header("Refresh:0");, calling that once the wrong answer count reaches 4.
My second idea is that you try to integrate some JavaScript into the module itself, attaching a click event to the buttons or whatever it your user is clicking on. The click event could keep track of how many wrong answers they've gotten, and once they hit the threshold, have the JavaScript call location.reload().


Redirect SimpleTest queries to a different database

It's not possible to do this on a storage engine level. You can't install Drupal on top of the HEAP storage engine, there are various missing features, the most obvious one being: "MEMORY tables cannot contain BLOB or TEXT columns." (copied from the link in the comments).

The qa.drupal.org testbot's have the complete MySQL data directory in a tempfs that is stored in memory, which is copied from the real file system during startup and back during shutdown. I don't think that's a doable setup for a development environment because, at least in my case, databases of real sites quickly get too big for something like this (Working on large sites with multiple GB of data). http://drupal.org/node/466972 has some more tipps and scripts for the tempfs thing. Make sure to read the comments.

Not sure what exactly takes 2,5m in your case, I can run a single test in ~10s (Note that every test method is a separate test that runs in a new installation).

I'm quite sure that I've already written quite a list of tipps on how to speed up tests in an answer somewhere but I'm unable to find it. The most important thing is defining $profile = 'testing'; in your test class, that will only install the absolutely required modules for Drupal to run. Speeds up test runs by ~50%. Another way is prefixing your different test methods with anything other than test and having a single public test method that calls all other. Downside is that your tests then run in the same environment and might affect each other. You e.g. can't have hardcoded node id's and things like that.

Another thing is optimizing your mysql configuration, than can speed up tests quite a bit as well, see http://techblog.md-systems.ch/blog/improve-mysql-performance for a start.

To actually override the used database connection, you need to completely overwrite the setUp() method where the connection is created and activated and instead use whatever connection you want, see DrupalWebTestCase::setUp().


If I understood right, you want a view to display players of each team. For that, you could:

1) Create a taxonomy vocabulary for each team (which you have already done)

2) Add an image field to the taxonomy term, as you would do to a CCK (admin/structure/taxonomy/[your_vocabulary]/fields

3) Create a CCK for "Player"

4) Add a field to the "Player" CCK of type "Term reference" (choose your Team vocabulary in the settings), so every time you create a new player you can select which team they belong to

5) Add the fields you need into your view, add a filter for the taxonomy term and expose it, so it will come out as a select list

I hope this helps a bit :)


How to load third party php library in drupal 7 module?

You can do the same way in Drupal for Facebook module and put these code in your custom module:

 $fb_lib_path = function_exists('libraries_get_path') ? libraries_get_path('facebook-php-sdk') : 'sites/all/libraries/facebook-php-sdk';
 $fb_platform = $fb_lib_path . '/src/facebook.php';
 try {
     if (!class_exists('Facebook') && !@include($fb_platform)) {
      //show error
      return NULL;
     }
     $fb = new Facebook(array(
       'appId' => $appId,
       'secret' => $secret,
       'cookie' => $cookie));
 }
 catch (Exception $e) {}

You can check the fb_api_init function of Drupal for Facebook module for more detail.


How to display calculated values in Drupal 8 views?

Create a field formatter for your euro-budget field and then select that for your field in your view.


Accessing the in-place editor with a keyboard hotkey ? (cross-platrofm Drupal question)

You can use my module, Instant Transmission.

  Why waste time moving the mouse cursor 7000 pixels or navigating drop
  downs or scrolling down the page to hit the save button, when you can
  use ... Instant Transmission.

  Instant Transmission allows you to quickly edit or configure nodes/blocks
  much faster than ever before.


You can use the Field collection module which lets you the possibility the regroup multiple fields (name, image, company, bio) into one collection (speaker). On that collection, you can put the number of values to unlimited.


Custom view mode for entity references - getting rid of title

You could do this with display suite as follows:

Enable display suite and display suite extras (important)
At structure > ds > list > extras > Other, enable Page title options
At Manage Display > [view mode] > [layout], enable a DS layout for your view mode
Manage Display > [view mode] > custom page title, hide the page title

DS has a lot going on. But if you need custom display modes and need to hide the page title in some cases it works well. Plus you get a lot of other nice features.


Single Sign On using PURL domain modifier and different TLDs

Have also been looking into this the last few days and came across this

http://drupal.org/project/services_sso_client

Seems that it will do exactly what you want to do.


A few things I see. const JOIN = 'n.vid = nr.vid'; this is dead code. Not sure where it comes from but as far as I am aware there's nothing in DrupalSqlBase or SqlBase that uses the constant JOIN. I am not sure what this even wants to be.

Your process copies the type and then in the destination I think you try to set the type/bundle to article but that's simply not how this works. Everything under the destination key is passed to the destination plugin as configuration and the way we designed and implemented this system the destination plugins do not change a thing, they just import.

So:

source:
  plugin: progweb_custom_blog
  constants:
    type: article
process:
    type: constants/type

In your particular case, you could use a map similar to und: en to map blog to article but if you want article nodes then you must use either the constants or the map.


On Imported content I am getting the error Text format field is required

You need to add default value for text format when you migrate content. Example body field

'body/format':
  plugin: default_value
  default_value: basic_html
'body/value': body

After update config migration you need update migration with command

drush mim MIGRATATION_ID --update


You don't need a Relationship to add the Tags sort (use the actual Tags field reference, not the generic "Terms on node").

But this way the results will be sorted by TID, not by term names. If your tags have been added chronologically then their TIDs will also be chronological and you can use this sort criteria (it doesn't matter if asc. or desc.).

But if your TIDs for years terms are mixed up you have to sort by term name. This is an alphabetical sort, not a numerical sort, but luckily it will work correctly in your "years" case.

To do that you have to:

Add the Relationship for your tags field, you can require it since you only want nodes that have the years tag to appear
Add Sort criteria Name from the Taxonomy term Category (it will automatically use the Relationship from above)

Now your results will be sorted by text 2015, 2016 etc.


How do I grab a list of all fields in a content type?

You can use the field_info_instances to get a list of all fields for a specific entity / bundle.  In your case the entity would be 'node' and the bundle will be your content type.


Select selection exposed filter using XML Views Backend

The Views XML has no idea of the data in your XML. Have you seen this tutorial video from the project page for Views XML Backend.

http://screencast.com/t/mnfEHRT7

They create a simple exposed filter for 1 xml "field" in the view that is searchable by a text filter. This is the simplest form of what you want. Using the exact same type of filter you could:

use hook_views_preview and change text field to a select list with options. You would build the options for the list by re-processing your XML file and using xpath queries to find the possible values you want in your select list. You'd likely want to cache these results to a drupal cache table.
you could also attempt to create your own Views Filter that does this; but thats harder too.


Migration into multi-value field collection

I ended up writing a drush command to run before the migration that would take the 'ingredients' field from the source db and create a new table with the ingredients each parsed into their own row and a delta column to keep them in order. I then configured the ingredients migration to point to this table instead of the recipe table.

My DB connection for this migration ended up looking like the following:

$query = Database::getConnection('default', 'legacy')
  ->select('_recipe_ingredients', 'i')
    ->fields('i', array('id', 'recipe_id', 'ingredient'))
    ->orderBy('i.recipe_id')
    ->orderBy('i.delta');


How to set up no result behavior of View field that uses "Views field view"?

How does Views know that The View Created By The Views Field View Module is not returning a result - on a row-by-row basis? I will hypothesize that Views is probably able to suppress the output of a field because very early on the process of creating/rendering the View, when the Views query is done, that field comes empty-handed from the database, and somewhere, internally, Views says: NO SHOW.

In my experience, I have never heard of a Views hook that allows a third-party module to short-wire this process and for example, arbitrarily command Views to render a field as it were populated, even if it is not, because a third-party module used that field as a contextual argument, created a view (or got data from somewhere else), and inserted that data into that otherwise empty field. This is what are you trying to do, and simply put, I am not sure if it is possible at all, at least in the way that you are trying to do it.

It would be possible however, for you to:

Create a primary view.
Create a custom preprocessor or template for that field. You would look for the proper name of the template by clicking your View's theme information link. A few caveats: For a preprocessor to be called, a matching template must exist first; Views won't recognize the preprossor (won't call it) if you declare it in a custom module, you will need to put it in your template.php; It isn't really necessary for you to create a preprocessor, however if you want to keep your templates clean (and any Drupalista worth his salt should want to) a preprocessor implementation is in order.
In your preprocessor, if that field is not empty, pass the results of that field to your secondary View's filter. This will require you to instantiate that View programatically.
If your secondary View returns any results, append those results to the current field.

So in essence, I think that what you want to do is 100% possible. I think your requirement will be possible (with Views) depending on A) How comfortable you are hacking with Drupal and it's theming layer, B) The performance requirements of your application.

If you are trying to do this for a high-performance site with a large number of visitors, I would be very wary of the solution that I am proposing, even with full Views caching turned on. So for performance and simplicity's sake, you can make your own database queries the ol' fashioned way. IMHO, your web server's CPU and whoever interacts with your site, clients and coders included, will appreciate it. Otherwise, if you still decide to go with my solution, here's a PROTIP:

Go to the Views advanced settings options.
Select show query.
Go back to your primary and secondary Views and test them. The query that is used to construct your Views will be revealed to you.
Copypasta this into your custom module for usage with db_query().
...
Profit!


7 - Add classes to individual fields of paragraph bundle

Most people add another field, such as a select list with predefined options, and turn that into a class using a preprocess, or merge in the paragraph twig template.  If don't have a predefined list, and you allow user input, you will need to sanitize the input.

How I do it in the twig template is like this:

{# Renders Width field. #}
{# Sets class name from values in database. #}
{% if content.bp_width|render %}
  {% set layout_width = content.bp_width['#items'].getString() %}
  {% set layout_width_classes = [
'paragraph--width--tiny' == layout_width ? 'paragraph--width--tiny',
'paragraph--width--narrow' == layout_width ? 'paragraph--width--narrow',
'paragraph--width--medium' == layout_width ? 'paragraph--width--medium',
'paragraph--width--wide' == layout_width ? 'paragraph--width--wide',
'paragraph--width--full' == layout_width ? 'paragraph--width--full',
  ]
  %}
{% endif %}

{# The template default set classes. #}
{%
set classes = [
'paragraph',
'paragraph--type--' ~ paragraph.bundle|clean_class,
view_mode ? 'paragraph--view-mode--' ~ view_mode|clean_class,
]
%}

{# Merges Width field with classes. #}
{% set width_field = content.bp_width|render %}
{% if width_field %}
  {% set classes = classes|merge(layout_width_classes) %}
{% endif %}

{# Prints div with classes, and content without Width field. #}
<div{{ attributes.addClass(classes) }}>
  <div class="paragraph__column">
    {{ content|without('bp_width') }}
  </div>
</div>

How do the Bootstrap styles get added?  Here is an excerpt from the LESS file:

.paragraph {
  .make-row();
  margin-left: 0;
  margin-right: 0;
}

.paragraph > .paragraph__column {
  .make-sm-column(12);
  .make-md-column(12);
  .make-lg-column(12);
  padding-bottom: @jumbotron-padding;
}

Which compiles into the following CSS:

.paragraph {
  margin-left: -15px;
  margin-right: -15px;
  margin-left: 0;
  margin-right: 0;
}
.paragraph > .paragraph__column {
  position: relative;
  min-height: 1px;
  padding-left: 15px;
  padding-right: 15px;
  padding-bottom: 30px;
}

You can overwrite that in your theme if needed.


Choosing between stable and development snapshot releases for a new high trafficked site

It's a difficult question to answer, because the status of a release (dev, beta, RC) is not necessarily a measure of it's stability, but rather an indication how well it has been tested before the maintainer released it. A module's dev version can (but does not need to be) more stable than the latest beta, RC or stable release.

IMHO, 200 is a huge amount of modules. If it's an option, consider reducing the number of modules. Often, 80% of a site's functionality is created with 20% of the modules, so the question is if the last 20% of functionality justifies the other 80% of modules.


You can use the #ajax attribute to load main part of the block via Drupal ajax.

namespace Drupal\generator\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\generator\Form\ProjektForm;

class GeneratorBlock extends BlockBase {

  public function build() {
    return array(
      'form_wrapper' => array(
        '#prefix' => '
',
        '#suffix' => '
',
        '#markup' => '',
      ),
      'load_form' => array(
        '#type' => 'button',
        '#value' => $this->t('Load form'),
        '#ajax' => array(
          'wrapper' => 'form-wrapper',
          'callback' => array(static::class, 'getForm'),
        ),
      ),
      '#attached' => array(
        'library' =>  array(
          'generator/generator-css'
        ),
      ),
    );
  }

  public static function getForm() {
    return \Drupal::formBuilder()->getForm(ProjektForm::class);
  }

}


How to redirect links to a single domain in a multi-domain setup?

There is a special module for that: https://www.drupal.org/project/domain_path_rewrite.

The idea is to automatically rewrite the relative links to the absolute ones so they always point to the proper domain. Something like:

/**
 * Implements hook_url_outbound_alter().
 */
function domain_path_rewrite_url_outbound_alter(&$path, &$options, $original_path) {
  if ($domain_path = _domain_path_rewrite_domain_path($original_path)) {
    $path = $domain_path['url'];
    $options['external'] = strpos($path, '//') !== FALSE;
  }
}

Of course, is's only possible if you're printing the links programmatically. Otherwise nobody knows to which domain the links belong to and most likely you need custom rewrite rule.


Where in the page generation pipeline can an HTML beautifier be placed?

Yes, in advagg is a good example, you have to get the response content with $response->getContent() in a response subscriber http://cgit.drupalcode.org/advagg/tree/src/EventSubscriber/ResponseSubscriber.php?h=8.x-3.x

  public function onResponse(FilterResponseEvent $event) {
    // Only care about HTML responses.
    if (stripos($event->getResponse()->headers->get('Content-Type'), 'text/html') === FALSE) {
      return;
    }

    $response = $event->getResponse();
    $html_markup = $response->getContent();
    // modify html markup
    $response->setContent($html_markup);
  }


Show Block view of Restricted Content Type

In the Views UI there is a setting under 'Advanced' called 'Query Settings'. Click on 'Settings' next to it, then in the next popup make sure to select 'Disable SQL rewriting'.

  Disabling SQL rewriting will disable node_access checks as well as
  other modules that implement hook_query_alter().


Does the SimpleTest method drupalGetMails() prevent actual emails from being sent?

That is only the getter.

// Use the test mail class instead of the default mail handler class.
variable_set('mail_system', array('default-system' => 'TestingMailSystem'));

in DrupalWebTestCase::setUp stops mails being sent. TestingMailSystem does nothing else but collect emails in the drupal_test_email_collector variable.


Turning on aggregration causes a SQL error

Aggregation can be sort of a pain in Drupal 8's Views implementation. Part of this is due to limitations in how MySQL handles GROUP BY.

As @Jonathan points out, for an aggregation function to work at all, you need to have at least one group by expression.  And if you want a function like COUNT or MIN to work as you expect, you only want the one group to be listed in the GROUP BY.

To get this to work right just now, you need to:

Under Advanced, you need to set Aggregation to "yes".
Under Format > Settings, you need to choose your Group by field.
You may not sort by anything other than the field you chose under Format > Settings, or your aggregation functions will give you bogus answers.

This is a bit limiting for some things you'll want to do, but as of 8.0.2, it's tricky to get better than this.

If anybody knows how to do better than this, I'd love to hear how :-)


You've defined a canonical link in the entity annotations, but this doesn't build a route automatically. If you don't want to do specify the route in a yaml file you need a route provider:

 *   handlers = {
 *     "route_provider" = {
 *       "html" = "Drupal\Core\Entity\Routing\DefaultHtmlRouteProvider",

If the custom entity should be part of the admin interface use AdminHtmlRouteProvider.


There really isn't a lot to go on here.  You really need to try to match up the ctime (creation timestamp) on the malicious files with the Apache logs to see what may have happened.

Other than that, you should

Take a backup.
Do a yum update on your server to make sure you have all relevant patches.
Clean out your temp folders on the server, and reboot it.
Bring Drupal core up to date.  You are several versions behind, and have other security vulnerabilities.
Bring your contrib modules up to date.
Double check all permissions that may involve PHP input, like the PHP input filter, block visibility rules, view rules, etc.  To be honest, I would disable the PHP input filter altogether.
Audit your custom code to see if there are any problems.


If you've enabled the PHP Input Filter, you could add the following into your node/page. The javascipt won't execute if disabled, leaving only the input field :)

<?php
    drupal_add_js('misc/jquery.js', 'core', 'header');
?>

<?php
function userEmail_form() {
    global $user;

    $form['email'] = array(
        '#type' => 'textfield',
        '#default_value' => $user->mail
    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Submit'
    );

    return $form;
}

function userEmail_form_validate(&$form, $form_state) {
    if (!valid_email_address($form_state['values']['email'])) form_set_error('email', 'Invalid Email Address');
}

function userEmail_form_submit(&$form, $form_state) {
    global $user;
    db_query('UPDATE {users} SET `mail` = "%s" WHERE `uid` = %d', $form_state['values']['email'], $user->uid);
    drupal_set_message('Email updated');
}

echo drupal_get_form('userEmail_form');
?>


Left join query between two custom tables

I found the way to do what I wanted.

The modified query:

    $query = $this->connection->select('publishing_options', 'po')
      ->fields('po')
      ->condition('po.pubid', $id);
    $query->join('publishing_options_bundles', 'pob', 'po.pubid = pob.pubid');
    $query->addExpression('GROUP_CONCAT(DISTINCT pob.bundle)', 'bundles');
    $query->groupBy(['po.pubid']);
    $result = $query->execute()->fetch();

I added the groupBy() methond and the addExpression() method with a GROUP_CONCAT

The results:

stdClass Object
(
    [__CLASS__] => stdClass
    [pubid] => 51
    [title] => Promote to blog
    [created] => 1549262900
    [modified] => 1549262900
    [bundles] => article,gallery,page
)


How to create page and restrict it to authenticated users?

You should try the Frontpage module - it allows you to set different home pages for authenticated and unauthenticated users.


You'll need to enable Rules Scheduler, which is a sub-module included as part of the Rules module.

You can watch a screencast on how to use Rules Scheduler from Node One here.


How can I make it so that users can add content to my site?

You only have to provide access to anonymous user to add content for the content type that you have created. For that go to permission page of Drupal:

admin/people/permissions

Check the following check boxes for anonymous user.

Basic (your content type) page: Create new content
Basic(your content type) page: Edit own content


Do Entity Field Queries respect grants and/or node access?

EntityFieldQuery will always check the user has the permission to access the field, if "DANGEROUS_ACCESS_CHECK_OPT_OUT" is not between the tags added to the query, but that is not done directly. It is done by adding a tag to the query, as field_sql_storage_field_storage_query() does.

if (!isset($query->tags['DANGEROUS_ACCESS_CHECK_OPT_OUT'])) {
  $select_query->addTag('entity_field_access');
}

It is then an implementation of hook_query_TAG_alter() that alters the query to check the permission. The Node module implement that hook with node_query_entity_field_access_alter().

function node_query_entity_field_access_alter(QueryAlterableInterface $query) {
  _node_query_node_access_alter($query, 'entity');
}

That is the reason why, before Drupal 7.15 (which introduced the "DANGEROUS_ACCESS_CHECK_OPT_OUT" tag), it was suggested to use $query->addMetaData('account', user_load(1)). The user #1 always have any permission, and checking the permission to access a field would be always positive.

_node_query_node_access_alter() contains the following code.

  // If $account can bypass node access, or there are no node access modules,
  // or the operation is 'view' and the $acount has a global view grant (i.e.,
  // a view grant for node ID 0), we don't need to alter the query.
  if (user_access('bypass node access', $account)) {
    return;
  }
  if (!count(module_implements('node_grants'))) {
    return;
  }
  if ($op == 'view' && node_access_view_all_nodes($account)) {
    return;
  }

  // Omissis

  // Find all instances of the base table being joined -- could appear
  // more than once in the query, and could be aliased. Join each one to
  // the node_access table.

  $grants = node_access_grants($op, $account);
  if ($type == 'entity') {
    // The original query looked something like:
    // @code
    //  SELECT nid FROM sometable s
    //  INNER JOIN node_access na ON na.nid = s.nid
    //  WHERE ($node_access_conditions)
    // @endcode
    //
    // Our query will look like:
    // @code
    //  SELECT entity_type, entity_id
    //  FROM field_data_something s
    //  LEFT JOIN node_access na ON s.entity_id = na.nid
    //  WHERE (entity_type = 'node' AND $node_access_conditions) OR (entity_type <> 'node')
    // @endcode
    //
    // So instead of directly adding to the query object, we need to collect
    // all of the node access conditions in a separate db_and() object and
    // then add it to the query at the end.
    $node_conditions = db_and();
  }
  foreach ($tables as $nalias => $tableinfo) {
    $table = $tableinfo['table'];
    if (!($table instanceof SelectQueryInterface) && $table == $base_table) {
      // Set the subquery.
      $subquery = db_select('node_access', 'na')
       ->fields('na', array('nid'));

      $grant_conditions = db_or();
      // If any grant exists for the specified user, then user has access
      // to the node for the specified operation.
      foreach ($grants as $realm => $gids) {
        foreach ($gids as $gid) {
          $grant_conditions->condition(db_and()
            ->condition('na.gid', $gid)
            ->condition('na.realm', $realm)
          );
        }
      }

Definitively, the code checks the user has access to the node.


When displaying a date field, Drupal typically converts it to the timezone of the currently logged in user. If no user is logged in, the site's default timezone is used. Perhaps you're logged in as a user that has a different timezone set?

Also, note that the time is internally stored as UTC, so you'll see a time that is off by an hour when simply printing the date's value or using a debugger. If you want to print the time in the user's timezone, try something like:

\Drupal::service('date.formatter')->format($date->getTimestamp());

This will use the user's timezone, or fall back to the site's default timezone.


How to change the theme for a particular admin page in drupal?

Yet another solution, in a couple of lines of code, is:

hook_custom_theme

  Return the machine-readable name of the theme to use for the current
  page. This hook can be used to dynamically set the theme for the
  current page request. It should be used by modules which need to
  override the theme based on dynamic conditions

e.g

/**
 * Implements hook_custom_theme
 */
function MYMODULE_custom_theme() {
  // Set path specific theme.
  if (current_path() == 'admin/settings/history') {
    return variable_get('custom_theme', 'theme_name');
  }
}

Core example: system_custom_theme

Update: To use a specific template you can override page.tpl.php

copy page.tpl.php to page--admin--settings--history.tpl.php, clear caches (theme registry) and use that.

More info: https://drupal.org/node/1089656


You could do that with Rules.

Add a new Reaction Rule (e.g: Update user gallery title)
Event: "After updating an existing user account"
Action: "Fetch entity by property":

type = node
title = [account:name]'s Photo Gallery

Loop over 'list item' and add action
Action: "Set data value": Set list_item item title
Save list_item.

Update: rule export:

{ "rules_update_gallery_title" : {
    "LABEL" : "Update user gallery title",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "user_update" ],
    "DO" : [
      { "entity_query" : {
          "USING" : {
            "type" : "node",
            "property" : "title",
            "value" : "[account-unchanged:name]\u0027s gallery"
          },
          "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "entity-fetched" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [
            { "data_set" : {
                "data" : [ "list-item:title" ],
                "value" : "[account:name]\u0027s gallery"
              }
            },
            { "entity_save" : { "data" : [ "list-item" ], "immediate" : 1 } }
          ]
        }
      }
    ]
  }
}


How can I add a wrapper to a group by in Drupal 8 views?

You can accomplish this by customizing the views-view-unformatted.html.twig file:

Use Twig debugging to determine which version of this template is currently being used. Most likely, it's views-view-unformatted.html.twig in /core/modules/views/templates
Copy that file to your theme's templates folder.
Rename the template to this: views-view-unformatted--your-view--your-display.html.twig where your-view is the machine name of your view and your-display is the machine name of your view display.
Add this code to the template file you created:

  {% for row in rows %}
    {%
    set row_classes = [
    default_row_class ? 'views-row',
    ]
    %}

    {% if loop.first and title  %}

{{ title }}

        {% endif %}
        {{ row.content }}

  {% endfor %}

Flush your site's caches

Please note that spaces in your machine name are repalced with dashes in the name of the template file.


Having multiple Drush instances for different core versions

Ideal way would be to use Composer to set up your projects. I'd recommend Composer templates for Drupal projects. Then add Drush to your project: composer require drush/drush.
Now install Drush Launcher on your machine, globally. Drush Launcher provides a drush command that always finds and uses the locally installed Drush from the /vendor folder.
$ cd MYDRUPAL
$ drush --version
Drush Launcher Version: 0.6.0
Drush Commandline Tool 9.3.0

But probably you can not simply rebuild your projects. Then you may want to install two different global Drush versions. See https://github.com/drush-ops/drush/releases for all available versions.
drush8
$ sudo git clone https://github.com/drush-ops/drush.git /usr/local/src/drush8

$ cd /usr/local/src/drush8

# Check the latest Drush 8 version at https://github.com/drush-ops/drush/releases
$ sudo git checkout 8.4.6

# Linux:
$ sudo ln -s /usr/local/src/drush8/drush /usr/bin/drush8

# Mac:
$ sudo ln -s /usr/local/src/drush8/drush /usr/local/bin/drush8

$ sudo composer install

$ drush8 --version
Drush Version   :  8.4.6

drush9
$ sudo git clone https://github.com/drush-ops/drush.git /usr/local/src/drush9

$ cd /usr/local/src/drush9

# Check the latest Drush 9 version at https://github.com/drush-ops/drush/releases
$ sudo git checkout 9.3.0

# Linux:
$ sudo ln -s /usr/local/src/drush9/drush /usr/bin/drush9

# Mac:
$ sudo ln -s /usr/local/src/drush9/drush /usr/local/bin/drush9

$ sudo composer install

$ drush9 --version
Drush Version   :  9.3.0

Source: Installing & Using Drupal Drush on Debian 7 (Bookmark this!)


SImplenews module. Where does the form come from?

To modify a form in Drupal you dont need to get where the form is built.

You can make use of hook_form_alter to modify the form

  Perform alterations before a form is rendered. One popular use of this
  hook is to add form elements to the node form.

hook_form_alter(&$form, &$form_state, $form_id);

  Parameters

  $form: Nested array of form elements that comprise the form.

  $form_state: A keyed array containing the current state of the form.
  The arguments that drupal_get_form() was originally called with are
  available in the array $form_state['build_info']['args'].

  $form_id: String representing the name of the form itself. Typically
  this is the name of the function that generated the form.

What is a Hook ?

Basically they provide a way for a module to extend the functionality of another module. They would go in a module and 'hook' would be replaced by the actual module name.

Please try

Examples for Developers

Drupal Hooks Explained


Drupal node templates which apply to more than one content type. Possible?

Implement a preprocess function that adds a template suggestion.

Assuming your theme is called EXAMPLETHEME, your content types are content_type_1 and content_type_2 and the template file is called node--example.tpl_php, add the following function to the file template.php of your theme:

function EXAMPLETHEME_preprocess_node(&$variables) {
  $node = $variables['node'];
  if ($node->type == 'content_type_1' || $node->type == 'content_type_2') {
    $variables['theme_hook_suggestion'] = 'node__example';
  }
}