How do I add a template suggestion for a node based on the current view?

You can leverage the views_get_current_view() function to get the current view being rendered.  I haven't tested the code below, but it should get you close to what you are trying to do.  Note that it could have unintended consequences if nodes are being rendered somewhere else on the page.

function themename_preprocess_node(&$variables)  {
  if (($view = views_get_current_view()) && 'featurefront' == $view->name) {
    $variables['theme_hook_suggestions'][] = 'node_view__' . $view->name;
  }
}

Views doesn't set template variables for nodes, which is why the technique above has to be leveraged.


Views Slideshow fixed 1st slide even though its random order

It appears as if your slides are always appearing in the same order in the source code.

Are you sure that the order in your view is set to random?

i.e
SORT CRITERIA,
Global: Random (asc)

nothing else.

Also I would really recommend not having that many nodes in your slideshow as It creates an insane amount of html markup which is not great for a number of reasons and performance will really take a hit. 5 or less slides would be ideal I would say about 10 should be an absolute maximum.


View does not display results when added as a block to a region

Verify which of the blocks you have enabled for the theme you're using. To do so, navigate to admin/structure/block. Somewhere your "block created with views" should be listed there. If it is within "Disabled" (near the bottom), then you need to indicate there in which region (like sidebar 1st, sidebar 2nd  or something similar?) you want that block to be displayed.

From what you seem to experience, it seems that hardly any block is enabled (most seem to be disabled).

PS: just to be sure, try to clear the cache ... it doesn't hurt, but sometimes that is what is required ...


Change the "For" setting in the header whenever changing almost anything.

If you want the setting to change on both displays choose "All displays":

If you want the setting to change on only one display choose "This block (override)"


How can I add a CSS class to the body tag based on the current path alias?

In your theme, you can add the following code in template_preprocess_html:
$current_path = \Drupal::service('path.current')->getPath();
$path_alias = \Drupal::service('path_alias.manager')->getAliasByPath($current_path);
$path_alias = ltrim($path_alias, '/');
$variables['attributes']['class'][] = \Drupal\Component\Utility\Html::cleanCssIdentifier($path_alias);


Rules Add an item to a List overwrites existing data

Your rule in your question seems to have "a few" (not just one) issues that need to be addressed. So I'll build a list of these issues here (and will add more of them later on if needed) ...

Issue 1:

Think about this: "Why have that 1st Rules action (a loop), if inside that loop there is nothing happening (as per the "DO" : [] in it)?". Either the loop is just redundant, or there is some Rules action(s) still missing inside that loop (more research needed).

If it was me to decide, for now I'd delete that Rules Action. And if needed I'd restore it later on if I have a real reason to do so (i.e. if there is at least 1 Rules Action that I know I'd need, as part of that loop.

Issue 2:

At the core of your question, there is your "It is not to overwrite the terms already present in the field". The typical mistake in using Rules is that someone incorrectly uses a Rules Action like "Set a data value" (for a multi value field), and that will remove all existing values for that field. The correct way is to use a Rules Action "Add to list" (that will preserve existing values). Your last Rules Action does indeed perform a "Add to list" (as it should be done to achieve your goal), but what is suspicious in that Rules Action is that you use entity-fetched:0 ... That is a single value (as per the ...:0 part of it, but entity-fetched is a multi value list (it has to be like that, otherwise you wouldn't use that ...:0 part in it). But nowhere there is an indication why "the first value" in the multi value list  (stored in entity-fetched), is the actual value you want to add to your list.

Issue 3:

The rules event your using (= node_view), combined also with the Rules Condition, is rather suspicious also. For 2 reasons: (a) what if the event and/or condition are not satisfied (in that case none of the Rules actions get executed) and (b) if you're sure the Rules event and Rules condition is "always" satisfied, then you might be doing those Rules Actions over and over again.

Though there is possibly only reasons to do so in 1 specific scenario. I.e. for those situations related to your "I have a rule which picks up the primary email & creates a taxonomy term from it" (let's call that your 1st rule, as compared to your 2nd rule shown in your question). It seems to me that your 2nd rule (as in your question) should be reworked like so:

Create a new Rules Component, with Rules Conditions and Rules Actions as you already have in your 2nd rule here.
Add and extra Rules Action to your 1st rule, which is simply/only to perform (= trigger the execution) of your 2nd rule.
In doing this redesign, you may have relevant / interesting data available in your 1st rule (like node id, user id, eMail id, term value, etc), which you can pass on to the Rules Component as a so called "Parameter" for that component.
And by having such parameters available in your Rules Component, you might possibly simplify the set of required Rules Actions needed to achieve your goal.
Don't forget to at least disable (or even delete) your current 2nd rule, after you reworked it to such Rules Component.

Possible other issues to be resolved

The above issues are, for now, only some suggestions to help you come closer to your goal. It's well possible (actually I'm about sure ...) you'll need other issues to be resolved also. But pretty sure the above issues will help you come closer. Btw, debugging is the art of taking away all possible reasons why it doesn't work ... as you want it to work.


How to bulk update text filter format on fields in drupal 7

Turns out this was solved in a different question, the answer is below:

Try this way, by making a loop for all nodes of certain type:
$node = node_load(nid);
$node->body[$node->language][0]['format'] = 'full_html'; // plain_text
node_save($node);

Kudos to Ek Kosmos for sorting this out.


How do I create an Events page listing all Event nodes?

You can use a Date field with an End Date (I don't have at this moment Drupal 8 installed to show you how)

With Views you can configurate your field to show the Start Date and the End Date. For use the format of Date in one place and Time in another place, you need to create a new Date format.

Maybe this question can be interesting for you: When should I use collect an end date for a field, instead of using 2 separated date fields?. Or have a look at How to Add a Custom Date Format in Drupal 8.


Access to core comment preprocess variables in a custom comment layout twig template?

Probably the twig changed, layout modules usually bring their own templates. You have to check which templates are used. To find this out use twig debug:

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

After you found the right twig you have to use the corresponding preprocess hook, which you find in the comments of the twig template.


How to create simple dynamic Views in Drupal 7

Ok, after some long researching, I found the solution over here --> [l]Context Filter with Path Alias in URL

Patrick and Stage many thanks, but your explanation indeed you don't have to add a bunch of modules or anything over complicated.  Here's what i did:

To recap in detail: I added a "Block View". This is important as it WILL NOT WORK in a Page View. I'm not too entirely sure why, but you'll get no results on your pages ...just only on the View preview will it show correctly. Perhaps it's due to the way the url's are created in Views .vs PathAuto. So a Block view here is the way to go.

My contextual filter is as follows:

WHEN THE FILTER VALUE IS NOT AVAILABLE
Choose: 'Provide default value' Type: 'Raw value from URL' Path component:'2'
Check: 'Use path alias'

WHEN THE FILTER VALUE IS AVAILABLE OR DEFAULT IS PROVIDED
Check: 'Override Title'. Add the value of '%1'
Check: 'Specify validation criteria' Validator: 'PHP Code'
Add the value of:
'$handler->argument = str_replace("-"," ",$argument); return true;'
then save

*Plus make sure to add the %1 to the Title  of the View as well.
 Save flush cache and your dynamic gallery will work by unique title!

Minor issues still:
- Need to find a way to remove special characters out of the title field when constructing the URL Validator. e.g. If a user uses "&" in their title name, then it can't create the url correctly. So I need a PHP string condition to handle special characters for instance: 'If !@#$%^&*():"; then just remove the character'


Hook on product page view in Drupal commerce

Since product displays are nodes, hook_node_view() is what you're looking for.


Your question is exactly about this issue:

  Allow instantiating Attribute objects within Twig

  Problem/Motivation

  Sometimes you have an array of attributes and it would be nice if you
  could addClass, removeClass, setAttribute, etc. rather than trying to
  do array manipulation.

  Proposed resolution

  Add a function to our Twig extension to allow creating an Attribute
  object from an array of attributes.

Issue: https://www.drupal.org/node/2616756

And the change record for 8.3.x:

{% set my_attribute = create_attribute() %}
{%
  set my_classes = [
    'kittens',
    'llamas',
    'puppies',
  ]
%}
<div{{ my_attribute.addClass(my_classes).addAttribute('id', 'myUniqueId') }}>
  {{ content }}
</div>
<div{{ create_attribute({'class': ['region', 'region--header']}) }}>
  {{ content }}
</div>

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


How can I change which view wins over two using the same path?

Use the internal path of the term:
/taxonomy/term/123

Route matching operates only on internal (unaliased) paths and route #2 having more fixed parts wins.
See https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Routing%21RouteCompiler.php/function/RouteCompiler%3A%3AgetFit/9.0.x


In the issue queue of the Google AdSense integration module your problem is reported: Support current CSE code

You could try to create a patch using the suggested information, test it and report back in the issue queue.


Localization vs Translation from a Drupal perspective

In Drupal, the terms "localize" and "translate" have special meaning (beyond the typical Internationalization/Localization meanings).

"translate" - this typically means that you end up with a "translation set" of objects. For example, an English source node with its German & French translated nodes (3 related objects). Or, a French source taxonomy term and its Spanish translated term (2 related objects).

"localize" - this typically means that you only have one "object" but can translate the textual information related to the object via string translation. For example, for a menu item, you have one English menu item but then translate the title of the menu item into Spanish (while both languages have the same link).

I've sorted this all out because I'm writing a book on Drupal 7 multilingual sites for Packt that will be out very soon: http://www.packtpub.com/drupal-7-multilingual-sites/book


Language detection method "Browser" doesn't work if I check "Cache pages for anonymous users"

have you seen and tried:

https://stackoverflow.com/questions/22792062/drupal-7-always-redirecting-to-default-language

  You might be affected by a bug in Drupal core. I had the same problem
  for a while and finally found the cause and a workaround for it.

  It goes like this:

  Add this code to a custom module (change "mymodule" to your modules' name):

/**
 * Implements hook_language_negotiation_info_alter().
 *
 * Remove the 'cache' setting from LOCALE_LANGUAGE_NEGOTIATION_BROWSER since
 * the code that utilizes this setting will in fact prevent browser negotiation.
 */
function mymodule_language_negotiation_info_alter(&$negotiation_info) {
    unset($negotiation_info[LOCALE_LANGUAGE_NEGOTIATION_BROWSER]['cache']);
}

  Clear all caches (e.g. "drush cc all")
  Go to admin/config/regional/language/configure and press "Save settings" once (this will rebuild the variable
  'language_negotiation_language').

  Now browser language detection should work properly.

  I'm also looking for a real solution but this requires changes in core
  and probably some discussion beforehand because of the nature of the
  bug. I've opened an issue here: Browser language detection for
  anonymous requests is broken

there is now a patch from Berdir


Get path of uploaded file inside a Twig template

Manage teaser Display : Change Format of your file field to Generic File From  admin/structure/types/manage/YouRContentType/display/teaser .
In your twig node--type--teaser.html.twig just print  {{
file_url(node.field_pdf.entity.uri.value) }} you will get the path to your file.
Note : As mentioned in comment it's uri Not url.


Using hook_form_alter to change from text filter to checkboxes

You probably want to use #type checkboxES (uppercase only for emphasis ;)), which is a list of checkboxes. checkbox is just a single checkbox that can either be checked or not, it can't have multiple options, so that property is ignored.


Yes, Drupal has a modular, hierarchical template system. Each of the components you mentioned can be themed individually. The main html template includes the page template, which includes other templates, that include other templates, and on it goes.

See About overriding themable output for the how/what/why.


I ended up making a couple of edits to quicktabs.js. At its most basic, in line 24 I changed 'click' to 'mouseenter' and changed the name of the quicktabsClick() function to quicktabsHover().

When the user clicked the link in the tab, though, the page refreshed; I added the following at line 25 (below the new call to quicktabsHover):

$(this).unbind('click').bind('click', quicktabsClick);

I also added a new function:

var quicktabsClick = function() {
    return false;
}


How to create paragraph of particular type using JSONAPI?

Issue was I didn't enable the "Paragraph Type Permission" module. Install it and go to drupal permissions.


Image field causes #access to reset to default

I would try refactoring your code, so that the part that produces the value of $is_younger first checks whether the triggering element is the field_dob field.

As an example:

// some other stuff here
$dob_date_combo_element = &$form['field_dob']['und'][0];
$dob_date_combo_element['#ajax'] = [
  'callback' => 'mrpeanut_form_record_node_form_minor_agreement_callback',
  'wrapper' => 'minor-ajax',
  'effect' => 'fade',
];

// Were we called by the #ajax-ified element?
if (isset($form_state['triggering_element']) &&
  $form_state['triggering_element']['#name'] === 'field_dob[und][0][value]') {
  $values = !empty($form_state['values']) ? $form_state['values'] : array();
  $is_younger = TRUE;

  if (!empty($values['field_dob']['und'][0]['value'])) {
      $dob = new DateTime($values['field_dob']['und'][0]['value']);
      $now = new DateTime();
      $age = $now->diff($dob)->y;
      $is_younger = $age < 18;
  }
  $form['field_minor_agreement']['und']['#access'] = $is_younger;
}
// Initial form loading.
else if (empty($form_state['input']) {
  // Place initial loading logic here for field_minor_agreement.
}


Why my Data Export View uses default value for an exposed Grouped Filter?

It could be that the export display is not attached to the page display. Try to edit the export display (typically you can not adjust the exposed filters on this page, as visiting the page will simply download all the results for the master view without considering any exposed filters).

Instead of getting your file by visiting the path of the data export, instead attach the data export to the page display where you placed your exposed filters.

You can do this by editing your data export display and adjusting the settings in your "Attach to" settings in the data export settings column (see screenshot below).

Once you click the Attach to link you'll be able to add your data export to any display in that view. Add it to your page.

Then, load the page in your browser, adjust your exposed filters until you see the results you want, and then scroll to the bottom of your page. You should see an icon that will enable you to execute the download of whatever file type you specified for your data export. For example, below I've filtered results for a page and set it to download as CSV.

By clicking the orange button, I'll download the filtered results on the page.


Drupal t() function does not replace placeholders for me

It looks like electrokate installed a Pattern Lab starter theme for Drupal that has a mock of the t() function that acts as a placeholder for prototyping the front end layer. It only returns the input it was sent, so it "works" under Pattern Lab - but running it inside of Drupal will cause this issue.

/**
 * @file
 * Drupal translate filter.
 */
$filter = new Twig_SimpleFilter('t', function ($string) {
  return $string;
});

This is meant to aid in making a Pattern Lab prototype outside of Drupal, but taking advantage of functions you will expect to use inside of Drupal so it is "Drupal ready".

edit: I may have linked to the wrong starter theme, but I can’t navigate it on mobile.


Error messages when running "drush verify-makefile" on a generated make file

EDIT: Not sure if the solution specified here is cosmetic but it did take care of the above question. I am not too familiar with Drupal project packaging.

This particular error was fixed with only making changes to the make file:

I switched the colons defining Drupal core and the API versions to equals
I changed the name for SlickGrid library to lowercase("slickgrid")

core = 7.44
api = 2

The rest of the make file still uses YAML convention. I wonder if that will cause problems down-the-road.


Change existing configuration at theme installation

i've found a solution: define the style of the image directly into the twig  template. As a theme can define new style of image when it is installed it's possible to use a non native style of image. In the example below i use the style "wide", created at the theme installation, instead of the native style "medium" used in the indexed content in the homepage.

 {% for item in content.field_image['#items'] %}
  {% set image = {
    '#theme':      'image_style',
    '#style_name': 'wide',
    '#uri':        item.entity.uri.value,
    '#alt':        item.alt,
    '#width':      item.width,
    '#height':     item.height
  } %}
  {{ image }}


Does having more enabled modules make the site slower?

Yes.
However, 30 is nothing to worry about. You're in trouble when you go over 100 ;)

Install a bytecode cache (APC or XCache) to eliminate most of the slowdown of including many files, and make sure to periodically remove unused modules (usually every project gathers modules that get unused at some point during development)


How can I override the node edit in Drupal 6?

I am not exactly sure what you are asking here, but if you are trying to change the layout of the node edit form, you might check out the http://drupal.org/project/nodeformcols module that allows you to change the node edit/create form with a pretty straightforward drag and drop interface within CCK.


This Link might be helpful :  http://www.lohmeyer.rocks/blog/2015/01/14/00187-print-your-themes-logo-path-drupal-8-twig.

I think you should define the logo path variable first into template.tpl in MyTheme_preprocess_page function.

One More thing you are trying to use {{logopath}} in 'span' tag and into 'src' its {{logo}}.


How to do you modify the URL created by a module?

These are just hints to help yourself:

Take the Theme developer module, and check what functions are involved in putting the URL together.
Set a break point inside the l() function just before theme('jl_custom_category_list', array('vid' => 3)) gets executed. The stack should show you the code building the URL.


Found solution in two ways.

Method-1:

Add language in filter criteria as mentioned below.

Method-2:

1) Add language in contextual filter

2) Provide a default value & select path component(I have selected 2)

3) Provide view path as "rest/nl/export" - EN or NL provide your language code


What's the best way to add a form in a node template?

The best way to do it is to create a variable for your template in hook_preprocess_node():

function hook_preprocess_node(&$vars)
{
  $form = drupal_get_form('form_name');
  $vars['my_form'] = render($form);
}

Now you can drop the form anywhere in your template as the variable $my_form


How to check if drupal_get_messages() returns an empty array

What you get is a syntax error not a parse error, meaning that the code never executed, but PHP couldn't parse it. My hunch is that the problem is in the code before the if statement. One way of getting this error would be to do:

$var = 'foo' // Missing ;
if (TRUE) {
  $var = 'bar';
}

This would result in the error message you got.

A lot of things could be wrong, but when it is a syntax error, the gist of it, is that you made code PHP couldn't understand.


A non-Views, Panels-compatible slideshow?

umm sure. you can always make a Block using admin/structure/blocks with like full_html. You could then easily make whatever HTML markup you need to get your images on the page.

Then in your theme file include a scripts[] = /path/to/your/js-slideshow.js.

A slideshow is just a slideshow. For example the slideshow at www.ucsb.edu is simply some HTML for images, 1 custom JS file, and CSS to hide all but the first image initially -- this is easily reproducible with Core Drupal. You could then place the block wherever you want with Panels.

The only caveat with this approach is uploading images from Drupal to power the slideshow is obviously harder since your keeping it very lean and not 100% drupal integrated.

Edit

Another example of getting remote images into drupal could be seen here by Fago making Entities from Google Picasa images and slideshows. Unless your comfortable with all this custom code, I dont recommend this type of approach. Drupal may have many approaches to getting something done, but as I mention in my last comment dont fight drupal's conventions or default way of doing something simply learn to embrace it. I've seen this idea spread by MerlinofChaos telling themers (im paraphrasing) "learn to use Views css, even though its ugly -- its feature complete". The same applies to drupal 7 "table per field" default storage structure. When you try to work around what you perceive is a shortcoming you simply fight an uphill battle to make drupal do what you want.


How to add a field to the contact form in Drupal 7?

This module http://drupal.org/project/contact_field will do what you want and I have know about it since D6, but the last time I try it in D7 it was buggy.

So far the best alternative I have found that works all the time like a charm is the webform module http://drupal.org/project/webform as you will be able to add or remove fields as need it and the email support works well and you also get the bonus of storing all the contacts attempts in case your email server or service was down for any reason.


How to display rss from external site into a view and sort them?

If feeds are read by drupal core aggregator module then you can do this with the help of views module itself.

Rough Example: Settings as per the screenshots

Create new view
Add fields to your view.

This will show feeds in view and you can easily do whatever you want to do with it.
Hopes this will help.


How to update a record with drupal_write_record?

drupal_write_record updates an entire record, not a single column. With drupal_write_record you could do this.

$node = node_load($nid);
$node->vid = $vid;
drupal_write_record('node', $node, 'nid');

But dealing with nodes, you can use node_save instead, which also handles saving fields and other data. Using node_save is recommended way of saving alterations to a node, since it also deals with revisions issues along with fields, hook notification ect. It's simple to use:

$node = node_load($nid);
$node->vid = $vid;
node_save($node);

If you want to update a single value in a datebase, you can use SQL (db_query) or the db_update function which is two ways of running SQL on your database. The db_update utilizes the Drupal query builder, and will work on any database backend the Drupal supports (now and in the furture):

db_query("UPDATE {node} SET vid = :vid WHERE nid = :nid;",
  array(':nid' => $nid, ':vid' => $vid)
);

$num_updated = db_update('node')
  ->fields(array(
    'vid' => $vid,
  ))
  ->condition('nid $nid)
  ->execute();

drupal_write_record will itself use db_update, a snippet of the code looks like this:

$query = db_update($table)->fields($fields);
  foreach ($primary_keys as $key) {
    $query->condition($key, $object->$key);
  }

Which basicly creates an update query, updating all of the fields, and using all of the values set in primary key as the condition.


I have a colleague with a similar problem on his OS Lion machine, but not a problem on our Snow Leopard machines. I stumbled across a solution that worked for me and may work for you. I can't see this portion of your code, but the URL that you are requesting is most likely an absolute path:

http://yourwebsite.com/someFolder/somePage.html

but what you want is a relative path:

someFolder/somePage.html

AJAX requires that all requests come from the same website. This is a principle of Same Origin Policy and is done for security reasons.

If you are requesting an absolute path to a link on the same website (as you probably are doing), the system should look and see that the request is from the same domain, in which case does not break Same Origin Policy. However, the person in charge of coding Lion's AJAX Same Origin Policy has a problem with their code that does not realize this is the case, causing the browser to think you are trying to run a Cross Domain Script. Hopefully they will realize this soon and fix it in the next update.


The web service endpoint returned a "HTTP/1.1 403 Forbidden" response

This is a pretty basic error most likely having to do with your digital ocean config than Drupal. You've got a named virtual host (casey.com) in your config file. Not sure how pointing us to an IP address helps us to help you.

Read through the digital ocean server set up documentation and make sure you've covered all your bases.


ckeditor in not showing up on one of my drupal site content type

I would click on "Configure" for CKEditor in Modules and make sure "Any content type" is selected. In these settings you can specify which content types CKEditor will be available for, so it's possible that that content type is not selected.


Module: See Last Modified Articles And Submitted Articles

What you're describing is pretty much available by default.  If there's specific changes you need, you should create a View that matches what you need.


FileField Paths works bad when upload image - the wrong way comes?

Updated

Assuming your installation code is not altered, I would suggest:

A.

Clear log messages at /admin/reports/dblog > "Clear log messages"
Try and re-upload your picture
Check your log messages reloading /admin/reports/dblog
You should find here some diagnostic about your issue.

B.

Check your Status is nice and clear [ admin/reports/status ]

If nothing wrong so far, you should check FileField Paths Issues for similar issues, and eventually submit your experience. Drupal community will appreciate!

Hope will help.


You have to pass the variable as reference.

So the function would should be

function custom_module_form_alter(&$form, &$form_state, $form_id) {


Solved.

I added hook_form_alter and checked if I am working with webforms (I suppose you can check if you are working with a specific webform), and then added a custom validation call-back:

  if (strstr($form_id, 'webform_client_form') !== FALSE) {
    if (empty ($form['#validate']['_set_next_page'])) {
      $form['#validate'][] = '_set_next_page';
    }
  }

In the _set_next_page function I get the value of the submitted component.  In my case there is only one question per page, but you can easily adapt that

$submitted = array_keys($form_state['values']['submitted']);

Remember if this is the first page (question), the array looks slightly different, so:

  if ($form_state['webform']['page_num'] == 1) {
    $Q = $submitted[0];
  }
  else {
    $Q = $submitted[1];
  }
  // Get the value that was submitted
  $value = $form_state['values']['submitted'][$Q];

Assuming $destination holds the 'form_key' of the question you want to jump too:

   if ($destination) {
    foreach ($node->webform['components'] as $component) {
      if ($component['form_key'] == $destination) {
        $nextPage = $component['page_num'] - 1;
        if (($nextPage > 1)
          && ($nextPage < $form_state['webform']['page_count']))
        {
          $form_state['webform']['page_num'] = $nextPage;
          break;
        }
      }
    }
  }

I set the page_num to the page_number for the destination component to one less, because webforms will increment this value once the submission is processed.

I am sure the code needs some re-finement (make sure that I do not crash and burn while accessing array elements / objects that does not exist) - but you get the idea.

Hope this helps someone else.


You have to add the following in your upjv.info.yml:

libraries:
  - upjv/global-styling

Make sure to clear cache after that by navigating to configuration > Development > Performance then clicking on Clear all caches under CLEAR CACHE.


Reset user password without using "Forgot password?"

It's easier these days:

$account = \Drupal::entityTypeManager()->getStorage('user')->load(1);
$account->setPassword('new password');
$account->save();


I have an alternative solution in case it is not working. Include title, body (trimmed) and global text contain

Read More

Make sure include node path and drag it above so that it appears in replacement pattern down below


There is no language option in drupal 7 site

It is be because you've installed Drupal with English. You can make Drupal Multi-lingual after it is installed, using the quick steps provided on HowTo: Basic Internationalization setup.

You can also have a look at the Multilingual guide for detailed information.


You need to attach library in your hook_form_alter():

/**
* Implements hook_form_alter().
*/

function <YOUR_MODULE_NAME>_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){

    /*Attach library, for Blazy implementation you will need
       $form['#attached']['library'][] = 'blazy/load';
    */
    $form['#attached']['library'][] = '<YOUR_THEME_NAME>/<library_name>';
    $form['#attached']['library'][] = '<YOUR_MODULE_NAME>/<library_name>';
    /*Pass even variable from this function to JS settings*/
    $form['#attached']['drupalSettings']['<YOUR_MODULE_NAME>']['<route_name>'] ['variable'] = 'PHP Value To JS';

    return $form;
}

If you pass variable with above mentioned method - $form['#attached']['drupalSettings']['<YOUR.... then that variable will be available in your JS file.

(function ($, Drupal, window) {
  Drupal.behaviors.helpers = {
    attach: function (context, settings) {
      'use strict';

       console.log(settings);
       console.log(settings.variable); //Should log variable value
    }
  };
})(jQuery, Drupal, window);

Add javascript to form by module


It can be done using Translation template extractor module

  If you are a translator, install the module on a Drupal site as you would with any other module. Once potx module is turned on, you can go to the "Extract strings" tab on the Locale administration interface, select the module or theme you want to have a translation template for, and submit the form. You will get one single template file generated.


How do I limit the allowed taxonomy terms basing on the content type?

According to my choice you should use hook_form_alter to bind taxonomy list based on article type.

function MY_MODULE_NAME_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'my_form_id') {
    $default_value = 0;
    $options = getArticles('Computer','Articles');
    $form['your_taxonomy_field_name'] = array(
      '#title' => t('Articlas'),
      '#type' => 'select',
      '#options' => $options,
      '#access' => 1,
      '#default_value' => $default_value,
      '#weight' => 1,
    );
  }
}
function getArticles($articleType,$vocabularyName) {
  //get the vocabulary
  $vocabulary = taxonomy_get_vocabularies();
  $vid = -1;
  foreach ($vocabulary as $item) {
    if ($item->name == $vocabularyName) {
      $vid = $item->vid;
    }
  }
  if ($vid != -1) {
    //get the parrent Term
    $query = new EntityFieldQuery;
    $result = $query
      ->entityCondition('entity_type', 'taxonomy_term')
      ->propertyCondition('name', $articleType)
      ->propertyCondition('vid', $vid)
      ->execute();
    $parrent_tid = array_shift($result['taxonomy_term'])->tid;
    //return children
    return taxonomy_get_children($parrent_tid);
  }
  return NULL;
}


Where does the menu trail get added into the $data parameter in pathauto_tokens()?

Token resolving is recursive. The caller of replace() is responsible for providing the data.

As far as this token is considered, it's not an active trail, it's just an array with strings that is combined together.

Your token probably looks something like [node:menu-link:parents:join-path]. If this doesn't receive the right parents then you need to look at where the parents are fetched and passed on, which is in token.module: https://cgit.drupalcode.org/token/tree/token.tokens.inc#n721

And if it is a different token then you need to look up whatever intermediate tokens you are using


Calling Jquery function from link onClick attribute

use an id on your anchors, no onclick:

Event2

then use the click event on it in the behavoir:

(function ($) {
    Drupal.behaviors.someClicks = {
        attach: function(context, settings) {
            $('#whatever').click(function() {
               console.log('vamoooh');
            });
       }
    }
})(jQuery);


Create a view block on a node reference field (using Node Reference)

UPDATE

There are some decent explanations on the internet

http://www.webomelette.com/related-content-block-views-drupal-7
http://www.webomelette.com/related-content-views-taxonomy-drupal

As well the eva module was suggested as being helpful in my situation, but I haven't tried it yet

Currently, this is still an issue for me.


Set node action for specific content type

The Rules module will be able to handle this, it's a next-generation version of the actions/triggers that are included with core:

  The rules module allows site administrators to define conditionally executed actions based on occurring events (known as reactive or ECA rules). It's a replacement with more features for the trigger module in core and the successor of the Drupal 5 workflow-ng module.

You can use the "After saving a new comment" event for the comments part, and the "After saving new content" event for the content part.

In both cases you'll be able to use conditions on your rules to make sure the actions are only fired for your required content types.


Render custom twig in a specific language

Currently, the only working way seems to be by passing local context - including a langcode in the render array and using |t([], {'langcode': 'XX'}) resp. {% trans with {'langcode': 'XX'} %} as mentioned in https://www.drupal.org/project/drupal/issues/2049241


How to get the value of a taxonomy term from entity reference using a token?

You try use hook_tokens

    /**
     * Implements hook_tokens().
     */
    function mymodule_tokens($type, $tokens, array $data, array $options, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) {
$replacements = array();
// $type is token type
      if ($type == 'node' && !empty($data['node'])) {
        foreach ($tokens as $name => $original) {
      // to do
        $replacements[$original] ='xxx';
       }
      }
      return $replacements;
    }

See more api hook_tokens()


Duplicate alias for different nodes after submitting form twice - Pathauto?

You can use unique_field module to prevent node creation on the basis of field value(unique field).

if this do not help then you can try to use hide_submit module to disable the submit button after first click.


How can I access the variable from other .tpl.php file?

You can add custom variables using hook_preprocess_node() in your theme's template.php file.

Here's how to add the account name:

function YOUR_THEME_preprocess_node(&$variables) {
  $variables['account_name'] = format_username($variables['account']);
}


What's the correct way to make it so that node_load both loads and caches additional, custom data?

The hook you're after is called hook_node_load(). I think the example from that page is probably the easiest to understand:

function hook_node_load($nodes, $types) {
  $result = db_query('SELECT nid, foo FROM {mytable} WHERE nid IN(:nids)', array(':nids' => array_keys($nodes)));
  foreach ($result as $record) {
    $nodes[$record->nid]->foo = $record->foo;
  }
}

The example loads some custom data from a table, based on the ids of the nodes passed into the function. It then loops through the query results, and adds the custom data to the relevant node objects.

When you call node_load() or node_load_multiple() for nodes that haven't been cached yet, your hook_node_load() function will be called and the custom data added.

Next time you call those functions for the same nodes your hook won't be called, but the node objects returned from the static cache will already have your custom data attached to them.


Whatever you pass to drupal_goto() will in turn get passed on to the url() function. If you're using url() on the path before hand, it'll get run through again and you'll get a double slash.

You can just pass the router path to drupal_goto() directly, and it will handle the alias for you:

drupal_goto('node/1234');


How to move nested links in menu edition?

If you don't have javascript error in the browser console try to click Hide row weight then you will see normal table drag behavior.


Post content via JSON API: CURL works, PHP not?

The 401 error is because you're not sending the basic auth creds like you are with your curl request. You need to add an Authorization header to your Guzzle request:
'Authorization' => 'Basic ' . base64_encode($user . ':' . $pass),
The 500 error is likely due to a malformed payload that JSONAPI can't parse. The value of json should be an associative array, not a JSON encoded string. See the Guzzle docs on uploading JSON data.


Rule to create a new view when a node is created

I think a better solution would be to use a single view with a contextual filter here.
I don't have experience with the Entity Registration module but since it's entity based it should have an Registration id contextual parameter which you can give a default from the url.


Yes its possible for anonymos users to subscribe to calendar events created using the Calendar module.


Node template.tpl.php for custom view mode?

You need theme_hook_suggestions.

    /**
     * Implements hook_preprocess_node().
    */
    function MYMODULE_preprocess_node(&$vars) {

      if ($vars['type'] != 'product_display'){
         return;
      }

      if($vars['view_mode'] == 'product_list'){

        $vars['theme_hook_suggestions'][] =  'node__' . $vars['type'] . '__' . $vars['view_mode'];
      }

  }

Now you will be able to use: node--product_display--product_list.tpl.php

Make sure you have to change MYMODULE.

If you want to use it from template php then use following code. I also assume you use zen theme:

function template_preprocess_node(&$variables) {
 if ($variables['type'] == 'product_display' && $variables['view_mode'] == 'product_list'){
// looks for node--node_type--view_mode.tpl.php in your theme directory
   $variables['theme_hook_suggestions'][] =  'node__' . $variables['type'] . '__' . $variables['view_mode'];
 }
}


Drupal 8 : Get a config settings value being stored in blocs

You need to load the block if your outside of the class, for that you need it's id.

$block = \Drupal\block\Entity\Block::load($bid);
$my_stored_value = $block->get('settings')['submit_action_amu_dud_form_block_settings'];

The id can be found in it's annotation if it's custom: @Block( * id = "my_fancy_block_id". If there are several instances of the block this may be altered and can be looked up in the DB, or the block config admin section - check the urls there.


Stopping 404 pages when adding get variable to the URL

You need a menu callback that accepts the variable. For more info, take a look at the Drupal docs.

Another way to do this is to pass your variable as a query parameter like http://mywebsite.com/my-content-url/my-content-url?var=myvariable. You can then use code to parse that parameter from the URL. You can get those parameters by using something like \Drupal::request()->query->all();


Defining module.links.action.yml with route parameters

I was on the wrong track the whole time.

The right way is to use entity.node.canonical as route (/node/{node}) and using other variables from node itself in the subscribe function ($node).

Thank you @4k4 for your help.


Below is a possible approach you may want to consider. It's using "State" names (like Florida, Illinois, etc.) instead of "Set 1, Set 2, etc" and "Cities" instead of "Songs".
If I was to implement this in a Drupal site, I'd use either of these "displays":

Option 1 - Master detail with nested blocks
Have a look at this example, which shows 1 "block" for each "State", and within each "block" it shows the "Cities" (and one of its attributes) in that "State".

Option 2 - Report that filters based on some lookup
Have a look at this example, which shows only the data about a specific "State", together with all the "Cities" (and one of its attributes) in that "State". To switch to another state, select the desired state from the Parameter form near the top ("IL" is used as the default in this example).

If you wonder "How did you do that?!?!" ... then this is the answer: that's really a piece of cake using the Forena module. Checkout the Community Documentation for details, and/or the documentation that comes with the module. The above 2 examples are actually delivered with the module (out-of-the-forena-box), though you probably don't notice that it is even not a typical "Drupal database". It could be such database instead, but in this case it's an SQLite (sample) database (it could also have been Oracle, MS SQL, Postgress or any PDO compliant database).
Disclosure: I'm a co-maintainer of Forena.


Ubercart Marketplace - Where is the ImageField for users?

It sounds like you need to check the permissions (/admin/user/permissions).

If you have field level permissions then you'll want to look for your CCK imagefield for your product images under the heading "content_permissions module." Ensure that the "view field_YOURIMAGEFIELD" permission is checked for all users.

Also if you're using imagecache on your product images there is also a permission for that as well.

Just for general knowledge the super admin user (user 1) completely bypasses the site permissions even if the super admin is assigned a role. It's a good idea to create a new user and create a new role to assign it to. Then use this user instead of 'admin.' We create a role called 'Site Architect.'

Hope that helps!


CSS Mime Type transferred as Zip in Chrome - 15 second delay

This is a TOTAL shot in the dark here, but:

1) are you running "Avast!" ?

2) If you load your site and look at network traffic (e.g. "Net" panel in Firebug), are there any 304 responses from the server?


"Page cache maximum age" is set to "no caching" but the block seems to be cached

To disable caching of the block add this to the php code:

  $build['#cache']['max-age'] = 0;
  \Drupal::service('page_cache_kill_switch')->trigger();

This is a similar question Caching of blocks for anonymous user


add watermark to all images uploaded in the site

Module ImageCache Actions is a well supported module that can add watermarks for Drupal 5,6,7.  It does this all by caching the image using imagecache.


Page not found without record about page

Is it something you're experiencing personally or are you just looking at the logs?

If you're just looking at the logs, it's usually a spammer/bot/crawler that's triggering the response. There are some security modules you can install that gives you a little more insight into those kinds of things (such as the IP address that triggered it), but I can only think of the D6 ones right now.


How can I avoid getting "This route can only be accessed by anonymous users"?

This issue happens because you are trying to access the user/login route when you have cookie maintained at your app level. You need to make sure you clear the cookies before visiting that route.

You can use https://github.com/joeferraro/react-native-cookies to make sure all the cookies are cleared before you try to log in.


How can I make a user-friendly account approval for admins?

There are two modules that you can take a look into

Admin Users

  This module helps to administrate all registered users. You can sort
  out users according to their status (active or blocked), the number of
  published nodes, the number of comments, the last visit or the period
  of registration. You can also change the role of any user, block or
  delete many users with one click just ticking them in the table.

Multi-admin pending approval notifications (MAPAN)

  Problem

  The current behavior in Drupal core when a new user registers
  requesting approval sends mail only to the site's contact address.
  Thus only one person is notified even though there may be several
  administrators/moderators.

  Solution

  This module improves this basic behavior by notifying all users that
  have the 'administer users' permission by default.
  Administrators/moderators get a setting to disable these notifications
  in their user profile form. A link is also appended to each of these
  notifications.


The tough thing here is that IE 8 is notoriously poor in terms of JS performance (compared to recent versions of FireFox, Chrome, Safari and even IE), and there's not a whole lot you can do to fix that.

However, in this case, I would consider one of two options:

Try to use different (faster) selectors besides :input[name="field_name[und]"] with Drupal's AJAX form states. If fields have IDs (they should, if the form is generated by Drupal), use the id instead, like field_name.
(If the above doesn't work) Try coding the visibility yourself (forgoing Drupal's FAPI #states system). You can optimize selectors and overall memory usage and performance by hand-tuning the jQuery or JavaScript yourself.

I'm guessing following #1 could fix your problem, though. For more reading on jQuery selector performance, see:

Your jQuery: Now with 67% Less Suck
jQuery Selector Performance Testing

However, for a form as large as yours, even hand tuning the JS might not be enough to get rid of that warning in IE. I have one form on a site I work on that always pops up that warning, and we sadly just have to tell users to ignore it. It's annoying, but it's acceptable to tell users to dismiss the warning in this particular case.


Search and Replace Scanner not publishing nodes after search?

It's a node setup thing. Adjusted Workflow/Revision settings to auto-publish, and we're all good.


If I understand correctly your question,
you should click "Use the administration theme when editing or creating content" in admin/appearance

Even better, try Administration theme module which will allows you to use you Administration theme on more pages like:

node/*/webform-results
node/*/webform-results/*


Can you try

function send_xml_form_user_profile_form_alter(&$form, &$form_state, $form_id){
    $form['actions']['submit']['#submit'][] = 'send_xml_edit_account_submit_function';
    drupal_set_message('<pre>' . print_r($form['#submit'], TRUE) . '</pre>');
}

Try clearing Drupal cache before you see the changes..


List all node titles to better iterate on a list of names

If you just need to create the nodes that don't have a specific title (which I guess it's just a country name), you don't need to use node_title_list(), whose purpose is rendering a list of node titles as links. Just load the nodes and check which titles aren't already used.
$country_list = ['Mexico', 'Tanzania', 'Brazil', 'Camaron'];

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'country_profile')
  // Remove the following line if you don't need to get only published nodes.
  ->propertyCondition('status', NODE_PUBLISHED)
  // Keep the following line, so Drupal won't check if the currently logged-in user has access to the nodes and the fields.
  ->addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT');
$result = $query->execute();
if (isset($result['node'])) {
  $country_list = array_flip($country_list);
  $nodes = entity_load('node', array_keys($result['node']));
  foreach ($nodes as $node) {
    unset($country_list[$node->title]);
  }
  $country_list = array_flip($country_list);
}

if (!empty($country_list)) {
  // There are nodes that need to be created; their titles are in $country_list.
}

Even better, load those nodes whose title is equal to one of the country names you already have.
$country_list = ['Mexico', 'Tanzania', 'Brazil', 'Camaron'];

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'country_profile')
  // Remove the following line if you don't need to get only published nodes.
  ->propertyCondition('status', NODE_PUBLISHED)
  ->propertyCondition('title', $country_list)
  // Keep the following line, so Drupal won't check if the currently logged-in user has access to the nodes and the fields.
  ->addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT');
$result = $query->execute();
if (isset($result['node'])) {
  $country_list = array_flip($country_list);
  $nodes = entity_load('node', array_keys($result['node']));
  foreach ($nodes as $node) {
    unset($country_list[$node->title]);
  }
  $country_list = array_flip($country_list);
}

if (!empty($country_list)) {
  // There are nodes that need to be created; their titles are in $country_list.
}


I think for that purpose, if I understood well, you need to use Views module with a user view you will be able to do create list or whatever you want.


If you are having trouble with hook_nodeapi (though I have never had problems with it), you could try using Rules.

There is a stock event After saving new content that you can try.  There is also a stock DO action, Send a mail to a user.  You then get the normalish token-based email form that you can configure.

We have used this on few projects with good luck.


One simplification could be the following:

Create just one content type called presentation that has speaker, agenda, time, title, and company as fields (and anything else you want).

Then you create one view which lists nodes of type presentation.

In the fields portion, you select all the fields you think are relevant to show in the table, perhaps just title and speaker.  The title can be a link to the full content.
Perhaps have the style be 'grid' and order the items by 'time', so the ones in the same time slot are on the same row.

That's one idea to make it simpler.  Does it work in your case?


How to get content language abbreviation ("en" instead of "English") in a View?

Assuming this is the language of a node. It should actually be stored in the database as en, es, etc and then being rendered.

To get the content from the database without it being rendered here are the steps.

Go to your view. Here's a sample one I'm using:
Check the Information link on the bottom right hand side.

When you click it, you should see a screen like so:

Here my two fields are listed as well as two other parts of the view where different things are occurring.
The names on the right hand side are different overrides you can implement to intercept the process of generating the display.  Depending on the name is the precedence. The further a name, the more specific it is.
Now, you need to decide how specific you want your change to be. I think using something like views-view-field--testlang--language.tpl.php is good. In my example, testlang is the name of the view and language the name of the field.
Click on the link next to the name of the field you want to override. It might be something like Field Content: Language (ID: language):. Once you have this, copy the content it's showing you.

Now that you have the name and the content of the field, go to your theme and create a file with the name you selected. If you have a templates folder on your theme, put it there.

Paste the code that your website generated for you,

<?php

/**
 * @file
 * This template is used to print a single field in a view.
 *
 * It is not actually used in default Views, as this is registered as a theme
 * function which has better performance. For single overrides, the template is
 * perfectly okay.
 *
 * Variables available:
 * - $view: The view object
 * - $field: The field handler object that can process the input
 * - $row: The raw SQL result that can be used
 * - $output: The processed output that will normally be used.
 *
 * When fetching output from the $row, this construct should be used:
 * $data = $row->{$field->field_alias}
 *
 * The above will guarantee that you'll always get the correct data,
 * regardless of any changes in the aliasing that might happen if
 * the view is modified.
 */
?>
<?php print $output; ?>

And now you modify it.

At the top you can see that you have the following variables available: $view, $field, $row, $output. The $row variable is the SQL result.
This is why I asked where you how it's stored on the database. I'm assuming up to now, we are using a node's language.

Well, if you take that <?php print $output; ?> and change it for <?php var_dump($row); ?>, it will give you the result from the database. If now you go to where you view is shown, or to the preview, you should see a line with something similar to:

object(stdClass)[94]
  public 'node_title' => string 'Consequat Nostrud Occuro Quadrum' (length=32)
  public 'nid' => string '26' (length=2)
  public 'node_language' => string 'es' (length=2)
  public 'node_created' => string '1479304373' (length=10).

Now, if you change your line to: <?php print $row->node_language; ?>, it should print the value as it's stored in the database in 2 letter country codes.

Good luck! Hope this helps.


its seems to me that pgid is wrong. Should be uid for users


How can I prepare a database statement and execute it many times with different input?

Prepared statements can be created after changing the statement class to PDOStatement. This technique is described in How to execute stored procedures in drupal?

// Get the Drupal database connection and change the statement class to PDOStatement.
// Save the current class for cleanup later.
$conn = Database::getConnection();
$saved_class = $conn->getAttribute(PDO::ATTR_STATEMENT_CLASS);
$conn->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('PDOStatement'));

// code from the question:
$check = $conn->prepare('SELECT COUNT(*) FROM other_tablename WHERE colname = :value');
$insert = $conn->prepare('INSERT INTO tablename (colname) VALUES (:value)');
foreach ($my_many_items as $item) {
  $check->execute(array(':value' => $item));
  if ($check->fetchColumn() < 1) {
    $insert->execute(array(':value' => $item));
  }
}

// Revert the connection to its previous statement class.
$conn->setAttribute(PDO::ATTR_STATEMENT_CLASS, $saved_class);


I have found that there is some translated nodes have the same
nid vid only langcode is different

When using translation, that's ok and normal.

However, what's never ok and not normal:

Duplicate entry '8a7e1ba8-9b75-4813-80d6-99104c82efa5' for key
'node_field__uuid__value': INSERT INTO {node} ("vid", "type", "uuid",
"langcode")

Universally Unique IDentifier cannot be the same, has to be unique. The error is telling you that you have two or more nodes, in the node table, with the same UUID.
So either you have 2 or more Nodes in D8 with the same UUID or perhaps you have a node that was already migrated to D9, but your migration is failing to see that and skip it.
If both are on D8, when you find which nodes have the same/duplicate UUID, via Drupal delete one and re-create it. Just in case, check that the other one didn't get deleted as well because it had the same UUID.


How do I programmatically fix local menus to be shown only for a content type?

I don't konw if there's a better way to do it now but few years ago I did it using a custom access: https://stackoverflow.com/questions/36496998/drupal-8-how-to-add-task-and-contextual-links-for-specific-node-type/36636263#36636263
In my case it was easier because I was creating the routes in my module.
Since your routes are created by views you would need to implement a RouteSubscriber to alter the route, add the _custom_access and _node_types requirements.
/!\ Warning: I am not sure since I never tried it on views routes but it might conflicts or breaks the rules you've set from the views UI to access this view. It should be compatible with a _permission rule, maybe not with an _entity_access rule.
yourmodule/yourmodule.services.yml
services:
  yourmodule.route_subscriber:
    class: Drupal\yourmodule\Routing\RouteSubscriber
    tags:
    - { name: event_subscriber }

yourmodule/src/Routing/RouteSubscriber.php
<?php

namespace Drupal\yourmodule\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  public function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('view.great_view_name1.page_1')) {
      $requirements = $route->getRequirements();
      $requirements['_custom_access'] = '\Drupal\yourmodule\Access\ByNodeTypeAccessCheck::access';
      // Replace 'my_node_type' with the name of the node type you want.
      // Since it's an array, you can add more than one node type.
      $requirements['_node_types'] = ['my_node_type'];
      $requirements['node'] = '\d+';
      $route->setRequirements($requirements);

      $options = $route->getOptions();
      $options['parameters'] = $options['parameters'] ?? [];
      $options['parameters']['node'] = [
        'type' => [
          'entity:node',
        ],
      ];
      $route->setOptions($options);
    }
  }

}

yourmdule/src/Access/ByNodeTypeAccessCheck.php
namespace Drupal\yourmdule\Access;

use Drupal\Core\Access\AccessCheckInterface;
use Drupal\Core\Access\AccessResult;
use Drupal\node\NodeInterface;
use Symfony\Component\Routing\Route;

/**
 * Check the access to a node task based on the node type.
 */
class ByNodeTypeAccessCheck implements AccessCheckInterface {

  /**
   * {@inheritdoc}
   */
  public function applies(Route $route) {
    return NULL;
  }

  /**
   * A custom access check.
   *
   * @param \Drupal\node\NodeInterface $node
   *   Run access checks for this node.
   */
  public function access(Route $route, NodeInterface $node) {
    if ($route->hasRequirement('_node_types')) {
      $allowed_node_types = $route->getRequirement('_node_types');
      if (in_array($node->getType(), $allowed_node_types)) {
        return AccessResult::allowed();
      }
    }
    return AccessResult::forbidden();
  }

}


FormStateInterface::setValidationHandlers not working properly?

You should add the below method in drupal 8. I hope it should work.
// buildForm

public function buildForm(array $form, FormStateInterface $form_state) {

    $form['company_name'] = array(
        '#type' => 'textfield',
        '#title' => $this->t('Company Name'),
        '#required' => 'TRUE',
        '#placeholder' => $this->t('Your company name'),
    );
    $form['actions']['submit'] = array(
        '#type' => 'submit',
        '#value' => $this->t('Save'),
        '#validate' => array('::validateForm', '::method1', '::method2'),
    );

    return $form;

}

public function validateForm(array &$form, FormStateInterface $form_state) {
   // do your code stuff..
}

public function method1(array &$form, FormStateInterface $form_state) {
  // do your code stuff..
}

public function method2(array &$form, FormStateInterface $form_state) {
  // do your code stuff..
}


In Drupal 8 you can use the drupal |render twig filter:

{{ myvar|render }}

Replace might be used as:

{% set customHTML = customHTML|replace({'[content]': content_section}) %}

having the variables all ready.

To convert your whole template to twig have a look at loops, also.


Issues migrating site config at various points in project lifecycle

My colleague proceeded to install Drupal also, also a standard install, composer install, drush cr etc., and then pulled the latest changes and ran drupal ci and ran into an error, namely:

Don't do that. Config import/export is meant to be used for the same site. That's exactly why the site UUID check exists, that's to tell you that what you are trying to do doesn't work.

Either you need to sync the database or you need to use something like https://www.drupal.org/project/config_installer to install based on an existing set of configuration.

Usually the process is that content and configuration flow in opposite direction. You have your production site where new content is created, from time to time you want to sync the full DB down to your staging/development and then you have configuration changes that you are creating locally and then deploying to dev/staging/production.

See also presentations like https://events.drupal.org/vienna2017/sessions/advanced-configuration-management-config-split-et-al for example.


Access field data in views row template (views 3)

This is pretty simple. All you need to do is go through following steps, which will let you create a same type of view which I have created on my system: The trick is to use relationship from field_image.

Create a simple view of articles (I created page), by default this will have a field_image. I am exporting a view below, import it.
In theme information override style output from "views-view-list.tpl.php". I am attaching code for both.

View:

$view = new view();
$view->name = 'article_view';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Article View';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Article View';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'list';
$handler->display->display_options['row_plugin'] = 'fields';
$handler->display->display_options['row_options']['default_field_elements'] = FALSE;
/* Relationship: Content: Image (field_image:fid) */
$handler->display->display_options['relationships']['field_image_fid']['id'] = 'field_image_fid';
$handler->display->display_options['relationships']['field_image_fid']['table'] = 'field_data_field_image';
$handler->display->display_options['relationships']['field_image_fid']['field'] = 'field_image_fid';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
$handler->display->display_options['fields']['title']['element_label_colon'] = FALSE;
/* Field: File: Path */
$handler->display->display_options['fields']['uri']['id'] = 'uri';
$handler->display->display_options['fields']['uri']['table'] = 'file_managed';
$handler->display->display_options['fields']['uri']['field'] = 'uri';
$handler->display->display_options['fields']['uri']['relationship'] = 'field_image_fid';
$handler->display->display_options['fields']['uri']['label'] = '';
$handler->display->display_options['fields']['uri']['element_label_colon'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'article' => 'article',
);

/* Display: Article List */
$handler = $view->new_display('page', 'Article List', 'article_list');
$handler->display->display_options['path'] = 'article-view';

Now the overridden template:

<?php

/**
 * @file
 * Default simple view template to display a list of rows.
 *
 * - $title : The title of this group of rows.  May be empty.
 * - $options['type'] will either be ul or ol.
 * @ingroup views_templates
 */

?>
<?php print $wrapper_prefix; ?>
  <?php if (!empty($title)) : ?>

<?php print $title; ?>

  <?php endif; ?>
  <?php print $list_type_prefix; ?>
    <?php foreach ($rows as $id => $row): ?>
      <li class="<?php print $classes_array[$id]; ?>" style="background-image:url(<?php print file_create_url($view->result[$id]->file_managed_field_data_field_image_uri); ?>);"><?php print $row; ?>

    <?php endforeach; ?>
  <?php print $list_type_suffix; ?>
<?php print $wrapper_suffix; ?>

This will do the trick for you. Let me know if you face some issues.


Why not use the Views Bulk Operations module? This is a great module for updating and deleting nodes from Views.


How to define the time-range for the Time Field in Webform 4.x

You can check with Clientside Validation Module. Otherwise you can alter the webform to add validation.

You may refer https://stackoverflow.com/questions/6785882/how-do-i-apply-webform-validation-in-drupal-7 link for a reference.


How to prevent from getting spammed in a contact form

That is why Mollom exists: http://drupal.org/project/mollom

  Mollom may block a post outright if it is from a known spammer. If
  Mollom is unsure how to classify a post, it may require the completion
  of a CAPTCHA to accept the post. Posts that do not match a "spammy"
  text pattern and do not originate from known spammers are accepted
  without the need to complete a CAPTCHA.

  A stand-alone CAPTCHA solution, which neither considers user behavior
  nor point of origin, can never achieve this level of informed
  protection, and generally requires users to solve a CAPTCHA on every
  post. Using Mollom's text analysis, users must only solve CAPTCHAs
  when Mollom is unsure about a post.


Clicking reset in Views UI causes PDOException Error

Something is trying to serialise a PDO object, which you can't do in PHP (unless you're running < 5.3 and are happy with nasty workarounds).

Drupal core doesn't do this; The Views module itself doesn't do this; so you'll need to disable custom/contributed modules you have installed one by one until you find the culprit. If/when you do, either fix the module if custom, or report the bug to the module's issue queue on Drupal.org for review.

If you're making use of the PHP filter in that View, remove the PHP code temporarily to see if that's the problem. If it is, consider re-implementing that logic in a more stable manner, i.e. using the hooks from the Views module.


The Drupal cart is a views display of commerce line items. Depending on your setup you'll have to alter the existing cart view and add one or two views relationships (in the advanced section).

The first relationship is from commerce line-item to commerce product. It is called something like Commerce line-item: Product. This exposes all product properties to the view.
If you use a product display with custom properties, you can also add Commerce Product: Referencing Node (depending on the fields you need this one is optional).

Now you have all field of your product (and product display) available to views and you can add them in the Fields section.


Yeah, no way to do it without major surgery to the Views Query class - the assumptions it makes are hardwired.

The only practical solution seems to be the Views Aggregator module, which has a D8 dev version. This provides a Views Table Style which performs aggregation functionality on the fetched records - in other words, you do an ordinary non-aggregated fetch and the module does the aggregating just before display.

It has the advantage that you can do all sorts of interesting things - far more than you can in SQL, against the fact that it adds to processing time for large data sets. (And I can think of other potential issues too.)

However it solves my problem, so that's good.

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

The conversion from D7 to D8 is minimal (still uses hooks instead of plugins) but, as I say, it works.


getting error while showing a user online or offline

I believe the field meh is referring to is provided by the user_stats module. Indeed, once installed it is possible to add that field in a views. There is also a patch for this error on the user_stats issue queue.


How to pass the nid from hook_node_view to the submit function?

You don't need to use form here. Just use l() with the button name and the link path.

function mymodule_node_view($node, $view_mode, $langcode) {

if ($node->type == 'my_type') {
   $node->content['redirect_button'] = array(
     '#markup' => l('Redirect button', 'yourpath/' . $node->nid);
   );
    }
}


Best method to upload / link to multimedia files in D6?

Have a look at ShadowBox, it supports a lot of formats and the FileField module which I think is essential for your set up:

  Media extensions supported:
  - Images (png, jpg, jpeg, gif, bmp)
  - Video (avi, mpg, mpeg)
  - Quicktime (dv, mov, moov, movie, mp4)
  - Windows Media Player (asf, wm, wmv)
  - Flash (swf, flv)
  - IFrame (asp, aspx, cgi, cfm, htm, html, pdf, pl, php*, phtml, rb, rhtml, shtml, txt, vbs)

Source: Comparison of Lightbox-type modules.

There's algo the Lightbox2 module with is aroung since a long time and have quite a big installed base.


How to display a custom block in a view twig file?

You probably are confusing {{ header }} and {{ view.header }}.
The first prints the header section including the block:
views-view.html.twig
{{ header }}

The second one returns ViewExecutable::$header, an array of handler plugins you have configured in the View. You can try to extract configured string values like in the first example but in case of a block entity you probably only find the block id and you have to load and render the block yourself. It would be much easier though to print {{ header }}.


Can I add a field collection to a block?

How about doing it through Views.

You can create a block view, add your field collection to the view, then use the view as a block.


Looking for solution to have specific terms have automatic tooltips whenever entered into content items

You could write custom javascript that wraps all strings you want to replace with the

here's a tutorial

// Pretending we have more than one paragraph to look through
jQuery('p').each(function(){
    traverseChildNodes(this);
});

function traverseChildNodes(node) {

    var next;

    if (node.nodeType === 1) {

        // (Element node)

        if (node = node.firstChild) {
            do {
                // Recursively call traverseChildNodes
                // on each child node
                next = node.nextSibling;
                traverseChildNodes(node);
            } while(node = next);
        }

    } else if (node.nodeType === 3) {

        // (Text node)

        if (/CMS/.test(node.data)) {
            // Do something interesting here
            alert('FOUND A MATCH!');
        }

    }

}


Display webform submitted data in profile page

If you're willing to use Webform Rules in combination with Rules, you can use the webform data (as submitted via the webform) in a custom rule (to copy those webform date to the relevant profile fields). Because you have access to all labels and all values of any field of a webform, ie:

[data:MachineFieldName-title] contains the Label of a field with machine name MachineFieldName.
[data:MachineFieldName-value] contains the Value of a field with machine name MachineFieldName

With that, you should be able to create a custom rule with:

Rules Event: After a webform has been submitted.
Rules Conditions: Check the form's id (possibly with other conditions to further refine them, eg that the user is not logged in).
Rules Action(s): Set a data value (for the appropriate profile fields, and using the values submitted via the webform).

For more details about this approach, and a prototype rule to understand the idea, refer to the answer to "How to create a node from a Webform using rules?":

the 1st attempt relates to using "Entity has field" (which doesn't work for Webform)
the 2nd attempt explains what to do in case of Webform.

PS: I'm assuming your question is about D7 ...


Migration bringing in duplicate taxonomy terms

I ended up biting the bullet and writing it myself.  I still don't know what was causing it to not work in the first place, but I replicated the desired behavior with this helper method in the migration class:

public function check_for_existing_term($taxonomy, $term) {
    $query = db_select('taxonomy_vocabulary', 'v')
        ->condition('machine_name', $taxonomy);
    $query->innerJoin('taxonomy_term_data', 'td', 'v.vid=td.vid');
    $new_tid = $query->fields('td', array('tid'))
        ->condition('td.name', $term)
        ->execute()
        ->fetchField();
    return ($new_tid) ? $new_tid : False;
}

In the constructor of the migration class I set $this->taxonomy = 'keywords'; and I used that in $this->destination = new MigrateDestinationTerm($this->taxonomy);, then I added the following prepareRow:

    public function prepareRow($row)
    {
        $new_tid = $this->check_for_existing_term($this->taxonomy, $row->NAME);
        if ($new_tid) {
            $this->map->saveIDMapping($row, array($new_tid),
                MigrateMap::STATUS_IGNORED, MigrateMap::ROLLBACK_DELETE);
            $this->rollbackAction = MigrateMap::ROLLBACK_DELETE;
            return FALSE;
        } else {
            return TRUE;
        }
    }

This tries to find a matching term in the database for each row.  If it finds it, it adds an entry in the map table and then returns FALSE so the migration won't do anything further for that row.  If it is a new term it returns True, and the migration continue happily, adding in the new term.


Services module, custom endpoint & authentication

In your code
Replace 'file' => array('type' => 'inc', 'module' => 'services', 'name' => 'resources/drupalsquare'),
with 'file' => array('type' => 'inc', 'module' => 'NAME_OF_YOUR_MODULE', 'name' => 'resources/drupalsquare'),
It seems you're wrongly defining your INC file.


What is the correct way to use a Symfony bundle?

Drupal 8 isn't using Symfony bundles, only some Symfony components. Therefore you should use https://github.com/KnpLabs/snappy instead of bundle you've mentioned. You should install it using composer and then use available classes in your Drupal code. If you want to create PDF-generation service, you should follow official Drupal documentation.


How to display User from Access Log in Views

You have to add a relationship to Users to be able to display user fields in the view.

Click on Add next to Relationships.
Check "Access log: User" then click Apply.
Click Add next to Fields then you should see the User fields including username.


How to implement a Comment Reply Form through Views and using JS?

Have you looked at Inline Ajax Comments?


Specify on which subdomain to show node (Multisite with shared Database)

You need this:

https://drupal.org/project/domain

On each node it will ask to affiliate content for specific domain and they would appear only over those for which you have selected.


Truncate field storage tables added by module before uninstall

I was able to solve this problem by implementing hook_uninstall() in my module's install file and explicitly deleting my custom entities.

For example:

function mymodule_uninstall() {
  //remove_fields_user();

  $results = \Drupal\mymodule\Entity\MeetEntity::loadMultiple();
  foreach ($results as $entity) {
    $entity->delete();
  }
  $results = \Drupal\mymodule\Entity\Team::loadMultiple();
  foreach ($results as $entity) {
    $entity->delete();
  }
}

See Drupal 8 hook_uninstall() docs for more details


Conditional fields module, "OR"-like operator

Maybe, the Views If Empty module could be of use to you. Here is a quote about it (from the module's project page):

  ...  enables a view to output a field if another field is empty.

  You need Views If Empty when you have a content type with an embedded video and an imagefield thumbnail. The nodes always have the images but occasionally have a video. You want your view to display the image field when the video field is empty, display the video field when available, and never display both.


Get User ID from a Profile Page to use in a View

In this case, /user/testuser is just an alias of /user/n where n is the user ID.  Which means the user ID is available in the unaliased URL, allowing you to do this.


how table aliases are created in joins is pretty simple - to have unique alias views takes names of both tables and combines them.
you can check more simple example:

SELECT node.created AS node_created, node.nid AS nid, users_node.mail AS users_node_mail
FROM
{node} node
LEFT JOIN {users} users_node ON node.uid = users_node.uid

users table is joined to node table and unique name becomes "users_node". For files table it would files_node.

I think it is the only way to have unique aliases. Also it is easy to understand from which join data is coming


Quantize/dither image using ImageMagick commands on image style actions

Imagecache actions has a 'custom' action which allows you to run your own actions. It may help you, though I used it years ago on a drupal 6 site with GD so can not say for certain if it will work for you.


How can I paginate the Views page itself where all views are listed?

If you have many views I would suggest you go to Views settings (admin/structure/views/settings) and enable Show filters on the list of views. This gives you the possibility to search and filter the list of views in various ways.


New measures to prevent spam in comments of nodes?

Maybe this module will help you: BOTCHA

There are more protection methods than just honeypot.


How to restrict who can VIEW content of selected content types using Organic groups?

Maybe you want to give it a try to use the Group module, either as an alternative for Organic Groups (as more and more people seem to be doing), or as an addition to it.

Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. It is designed to be an alternative to Organic Groups. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.

For this specific question, you'd enable the gnode submodule, and for each group type you would define the appropriate permissions (view, edit, delete, etc) for the various Content Types. That's it.

For more details about how Group compares to Organic Groups, refer to my answer to "What are the features of the Group module versus Organic Group module?".

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".


Display and Modify CSS variable ? (Module)

You have many options:

Make a system settings form that stores the value to a drupal variable. Read that value from your (themes) css. Then when that form is submitted in your theme form submit handler have code clears the cache:   cache_clear_all("{$theme}:css:*", NULL, TRUE);. Where $theme is your theme name. The CSS should be re-generated on page load.
I believe the LESS module allows you to easily make CSS variables applied to your files (in Less-3.x or greater for drupal). If you're not currently using LESS, then this is less helpful (pun NOT intended!)


Strategy for organizing category pages with Views and Panels

I don't know if you figured this out already, but I'll give a quick answer.

The magic you need: arguments / contextual filters. You want to have just one Views block that takes term IDs as arguments (in a contextual filter), so it will filter on the term present in the url. Instead of a regular views block, you can also use a Views content pane (for tighter integration with Panels).

As for Panels: you need one panel page to override the taxonomy system path. When you enable Page manager (part of CTools) some page override templates are provided, just activate the taxonomy one.

Add a variant (you can optionally add a selection rule if you want this override to only work on terms of one vocabulary) and add your Views block. Since this is a taxonomy system path, term IDs are already available as arguments for the view block (Panels is also excelent for manipulating which arguments the page will provide).

Page manager, Panels and Views are complex so it's a good idea to understand how it works. I recommend checking out NodeOne's Learn Page manager screencasts (especially Views content panes), and maybe also parts of the Views series (especially contextual filters).


Views - How to display results in nested groups?

I think this is more a question of styling than views itself. You could assign a class to the row output (e.g. with a replacement pattern token or something) and then style the css to show the output "nested".


CKEditor removes HTML/CSS when switching to plain texteditor and back

My CKEditor seems to remove formatting in a table

You need to add the HTML Table tags

to your Allowed HTML Tags


How to make the Webform submit button use an uploaded submit-image?

The easiest way to do this would be to write your own module. The place to start looking would be here: http://drupalcontrib.org/api/drupal/contributions!webform!webform.api.php/function/hook_webform_component_info_alter/7


There are many ways you can accomplish this, here a few ideas;

You could create custom templates based on the node ID of those
pages...Examples here: http://drupal.org/node/1089656
Also you could make use of the Context module:
http://drupal.org/project/context
You could also, create content in blocks, and set them to only show
on the specified paths under the page visibility settings of any
given block you create.


How does node import happen when importing from features module?

That kind of thing is not really possible. The problem is that the node id is serial, so on one machine it will have on id but on another machine it will have another id. Also the the node id is the primary identification, so changing it is not always that easy (if you have comments etc.)

For this kind of thing, UUIDs is really needed (Universally Unique ID). There are modules for this in Drupal 7 and it's being worked on in Drupal 8, but neither will effect the node id, instead it will maintain a UUID which will be the same on all machines that has the node imported.


The timeout happens because of large amount of operations within $a_batch_job['operations'] array. For every operation defined queue item is created and stored in the queue table of the database.

Check the _batch_populate_queue() method.

Workaround

Instead of defining Pre-set list of calls, you can take a route of Alterable list of calls. So in your case it could be like this:

function batch_import($ps_platform, $ps_input_file) {
  # Parsing the input file to my own class. The time spent for
  # different size files can be in the table above.
  $o_dat = new DatContainer($ps_input_file);

  # [1/2] Preparing the batch job array we will output
  #---------------------------------------------------
  $a_batch_job = array(
    'title' => t('Importing dat file'),
    'init_message' => t('Beginning dat import process'),
    // Pass our parsed file as a parameter to the batch operation callback.
    'operations' => array('process_entry', array($o_dat, $ps_platform)),
    'finished' => 'batch_finished',
  );

  batch_set($a_batch_job);
}

And your process_entry() would look like this:

function process_entry($o_dat, $ps_platform, &$context) {
  if (empty($context['sandbox'])) {
    $context['sandbox']['progress'] = 0;
    $context['sandbox']['current_entry'] = 0;
    // Assuming you implemented method for DatContainer class, that can
    // return number of records in the file and it's named rowCount.
    $context['sandbox']['max'] = $o_dat->rowCount();

    // Store the source file in the context.
    $context['sandbox']['source_file'] = $o_dat;
  }
  // Process 5 entries per iteration.
  $limit = 5;

  // Assuming you have method getRows to get N number of entries starting from X entry.
  foreach ($o_dat->getRows($context['sandbox']['current_entry'], $limit) as $po_entry) {
    $context['message'] = "Processing: {$po_entry->s_name}";
    $o_node = _get_entry_node_by_id($ps_platform, $po_entry->s_id);
    $_SESSION['http_request_count']++;

    $context['sandbox']['progress']++;
    // Assuming you have number for entry within file.
    $context['sandbox']['current_entry'] = $po_entry->entry_number;
  }

  // Inform the batch engine that we are not finished,
  // and provide an estimation of the completion level we reached.
  if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
    $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
  }

}

So now instead of N queue items you would have only one item, that would get called recursively as long as $context['finished'] < 1.

For more information about $context variable please visit callback_batch_operation() page. It's preferable to use this variable to store information used across batch operation callbacks, rather than $_SESSION.


"Load a list of entity objects from a VBO View" rules action not working

You want to pass the userid as a parameter also, similar to what is shown around 7:30 in the video about Using VBO to load list of objects into Rules. Here is a summary of what is shown in this video:

  You need a view that lists the entities you want to work on in Rules. Note that you don't need a display of the view – and it might even be better not to have one if you don't want the view to be displayed somewhere.
  However, you need one bulk operations field. The type of bulk operations field determines what entity type will be sent to Rules. Note that you don't need any actions enabled for the field – it is enough that it is present.
  You need a rule that, as an action, loads entities from a VBO. (This is available under the "Views bulk operations" group.) All view displayes with at least one VBO field will be selectable.
  The action provides a list of entities, that can be used just like other lists in Rules. Combine with loops, actions and Rules Scheduler to make awesomeness happen.


How to edit the content page fields column in the admin section?

You can use hook_form_FORM_ID_alter() and do your changes inside that.

Example:

function YOUR_MODULE_form_node_admin_content_alter(&$form, &$form_state, $form_id) {
 // YOUR CUSTOM CODE GOES HERE
}


What are the features of the Group module versus Organic Group module?

About

The Group module allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. It is designed to be an alternative to Organic Groups.

Organic Groups allows content itself to be groups, which isn't always what people want. It relies on an entity reference field to keep track of the ties between a group (node, term, ...) and its content (node, term, user, ...)

Group instead creates groups as entities, making them fully fieldable, extensible and exportable. Every group can have users, roles and permissions attached to it (refer to "What are the various roles supported by the Group module?" for more details about that). Groups can also act as a parent of any type of entity. Group provides an extensive API to attach entities to groups.

Advantages of Group as compared to OG

Group started in D7 only, taking full advantage of entities introduced in D7.
Group doesn't 'abuse' nodes by adding custom fields to them in order to make the module work.
Group does not allow you to have per-group roles or permissions. These are instead defined on the group type. So group types, group roles and permissions are configuration instead of content. Because of this approach, group types and roles exportable (with or without Features).
Organic Groups is commonly perceived as a huge module, which carries a lot of "legacy" from pre-D7 releases and makes it tougher to ever get upgraded to D8.
A D8 version of Group is already available (not so for Organic Groups).

Disadvantages of Group as compared to OG

As of today, Group only has alfa / beta releases (not any official release).
Even though some say it is self documenting, I think it is not (maybe because I don't want to digest the source code to find out what this module can do ...).
Not a lot of documentation available.
As of today, there is no group tag on drupal.SE, though there is an organic-groups tag, and there are already quite a few Group specific questions. Anybody interested in creating it (again), feel free to reuse my previously approved tag wiki and/or tag excerpt (no need for credits ...).

Integration with various modules

The Group module integrates with various other (popular) modules, including:

Rules, as illustrated in the answer to the question "How to bulk assign existing content to a group created with the Group module?".
Views, as illustrated in the answer to the question "How to show the content of a group on the group page when using the Group module?".
Pathauto.

The beauty, IMO, of these integrations are that they are more or less out-of-the box (not dozens of extra modules needed to make those integrations work).

Refer to Integrations with other modules and its "Related issues" about other modules for which integrations already exist, or are in the pipeline.

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".
Podcast "Using the Group module as an Alternative to Organic Groups in Drupal 7 and 8".
What are the alternatives for the Organic groups module?

What people say about the Group module

Similar to what you see in the Group issue queue: most (if not all) people who know about Group just love it ...


You could use hook_form_alter and unset the $form['#submit']. Then you add your own submit handler by using $form['#submit'][] = '_my_callback'; THen in your callback just copy the code of the Ajax redirect and alter it to your needs.


Drupal 8 Remove book child pages with in the content block

In D7 (not sure of D8) if you install Display Suite and enable the "Full Content" view mode for Books. You can then apply any layout you want to book pages and control where the book navigation goes for example.

Attempting to override the book behavior from Core can be very difficult ...


Why view is not firing hook_views_query_alter?

Please read hook_views_query_alter() API, which say:

  This hook should be placed in MODULENAME.views.inc and it will be auto-loaded. MODULENAME.views.inc must be in the directory specified by the 'path' key returned by MODULENAME_views_api(), or the same directory as the .module file, if 'path' is unspecified.

So double check that you're placing the hook in the correct place either in the main module file or MODULENAME.views.inc (not mymodule_views.inc) and make sure that you've MODULENAME_views_api function defined (unless it's already defined by Feature). After all that clear your all caches (including memcached if in it's in use).

See also: How do I use hook_views_query_alter()?

If there is still a problem, that means your view is implementing different query handler and possibly it implements views_plugin_query (which by default doesn't provide any alter code), so you have to find the right plugin query handler (a query class) and see which hooks they're using instead.

To find which plugin is in use.

Method 1: If view is already exported, check base_table name and which module is dealing with that table. If it's search_api_, then it's Search API module.

Method 2: Edit views/includes/view.inc, find the code which executes the query alter: $this->query->alter($this); and dump the $this->query object to see what class is used for that view.

Then find that class and its alter() method to see how it's implemented.

Here are few examples:

Views (class views_plugin_query_default extends views_plugin_query):

function alter(&$view) {
  foreach (module_implements('views_query_alter') as $module) {
    $function = $module . '_views_query_alter';
    $function($view, $this);
  }
}

Search API (class SearchApiViewsQuery extends views_plugin_query):

public function alter(&$view) {
  parent::alter($view);
  drupal_alter('search_api_views_query', $view, $this);
}

YQL Views (class yql_views_query_plugin_query_yql extends views_plugin_query):

function alter(&$view) {
  foreach (module_implements('yql_views_query_query_alter') as $module) {
    $function = $module . '_yql_views_query_query_alter';
    $function($view, $this);
  }
}

So as you can see, you need to use different hooks for different views types.

In your particular case collection_products views is handled by Search API, so you need to define hook_search_api_views_query_alter instead.


Selecting taxonomy term in article and showing all articles titles associated with this term

1) Create a View block, when you create it use Show: Content.

2) Under Advanced Contextual Filters add Has taxonomy term ID

3) Select provide default value Type: Taxonomy term ID from URL (this will automatically grabs the term from your node) If you want, you can limit the terms by vocab.

Even if your tax term reference field is limited to 1, maybe you should set it up as if it was unlimited, in case your client later wants to allow more than 1 value.

Change the multiple-value handling option to the 2nd one, share any term.

Scroll down to MORE and check mark allow multiple values.

Click Apply, to save the settings.

Now you want to exclude the current Article (node) from the list. No point in showing the Article the visitor is already viewing/reading.

4) Add another contextual filter of ID

5) Provide default value Type: Content ID from url (automatically grabs the ID from your node).

6) Scroll all the way down, and click on MORE, and check mark Exclude.

So your Advanced section should look like this:

To place the block in your article, there are several ways.

Go to admin/structure/block and click on Place Block, search for your View Block and click on Place Block.

In the configuration, under Visibility settings, select Content Types and check mark your content type.

Site Note: There are other ways to insert/place your view:

Through a template file.
Using Panels and or Display Suite (Note: I am not 100% sure on this as I have not played much with these modules in D8, in D7 I know you can).


How to create a view of all recent activity on a site?

You should take a look at the Heartbeat module.

  Heartbeat displays user activity on a website. This module is an API to log activity. The logged data contains message structures, attributes and variables. Once the activity messages exist in the database, they will be parsed and build into activity streams.


The tokens [site:current-page:path] & [site:current-page:url] will retrieve the current Drupal path & the full URL, respectively.