How can I update the block content programmatically? I have created a block plugin.
/src/Plugin/Block/Myblock
/**
 * Provides a 'Download component' block.
 *
 * @Block(
 *   id = "my_custom_block",
 *   admin_label = @Translation("My custom block"),
 * )
 */
class Myblock extends BlockBase {
  // Other code
}

The above block has a settings form also where I am uploading some files to the block.
I placed this block in two different regions on a page with different settings. (Uploaded different files)
Now I want to update the content of one of them i-e add a new file programmatically.
How will I do that? Because I can't load the block and update the field and save the block again because both returns me the same id my_custom_block.
$this->entityTypeManager->getStorage('block_content')->load('my_custom_block'));

And also this returns me null.
Any idea how will I do that? Just like we update the nod entity, I want to update an instance of this block plugin.
Updated code:
I get the block like this
$node = \Drupal::routeMatch()->getParameter('node');
 if ($node instanceof \Drupal\node\NodeInterface) {
    /** @var \Drupal\layout_builder\Field\LayoutSectionItemList $layout */
    $layout = $node->get('layout_builder__layout');
    $block = $layout->getSection(0)->getComponent('1bb8e7b4-8253-40bc-a1f9-7f02e90edb2f')->getPlugin();
    $block->setConfigurationValue('file', ['6338, 6336']);
 }

Now how will I save the node using the block new configuration values?
I tried this.
 $node->get('layout_builder__layout')->getSection(0)->getComponent('1bb8e7b4-8253-40bc-a1f9-7f02e90edb2f')->setConfiguration($block->getConfiguration());
 $node->save();

Placed blocks are stored in the config entity block. The IDs are more or less unpredictable but you can load the blocks by specifying properties:
$entity_type_manager = \Drupal::entityTypeManager();
$blocks = $entity_type_manager->getStorage('block')->loadByProperties([
  'plugin' => 'my_custom_block',
  'region' => $region,
  'theme'  => $theme,
]);

A code example to load all blocks placed for the custom block plugin, do some checks and modify the settings:
$entity_type_manager = \Drupal::entityTypeManager();
$blocks = $entity_type_manager->getStorage('block')->loadByProperties([
  'plugin' => 'my_custom_block',
]);

foreach ($blocks as $block) {
  if ($block->getRegion() == 'my_region') {
    $settings = $block->get('settings');
    // modify settings
    $block->set('settings', $settings);
    $block->save();
  }
}


How can I mock a service? i have this code:

/**
 * Defines a wrapper target around a paragraph bundle's target field.
 *
 * @FeedsTarget(
 *   id = "feeds_para_mapper_temp_target",
 *   field_types = {
 *     "entity_reference_revisions",
 *   },
 *   arguments = {
 *     "@entity.manager",
 *     "@entity_field.manager"
 *   }
 * )
 */
class TempTarget extends FieldTargetBase implements, ConfigurableTargetInterface,
{
  protected $entity_type_manager;
  protected $field_manager;
  public function __construct(array $conf, $id, array $def, EntityTypeManagerInterface $en_man, EntityFieldManagerInterface $f_man)
  {
    parent::__construct($conf, $id, $def);
    $this->entity_type_manager = $en_man;
    $this->field_manager = $f_man;
  }
  // Here is where i need the instance, and it's weird because it gets called
  // without instantiating this class:
  public function defaultConfiguration(){
    // This function create a form configuration and return it:
    $definition = $this->targetDefinition;
    $field = $definition->getFieldDefinition();
    $instance = $this->createTargetInstance($field,$this->feedType)
  }
  // Calls this plugin manager to get instance of another plugin
  public function createTargetInstance(FieldConfigInterface $field, FeedTypeInterface $feed_type){
    // This is where the test is failing:
    $manager = \Drupal::service('plugin.manager.feeds.target');
  }
}

what it does it calls a plugin manager in order to create instance definition,
whenever it gets tested i see this error:

\Drupal::$container is not initialized yet.

which i know is caused by calling to the service
i have tried this in the test file:

$container = new ContainerBuilder();
$manager = $this->prophesize('Drupal\feeds\Plugin\Type\FeedsPluginManager');
$container->set('plugin.manager.feeds.target', $manager);
\Drupal::setContainer($container);

Not working.
i tried as the answer suggested in the comment bellow to add implement ContainerInjectionInterface not working, and with ContainerFactoryPluginInterface as this article suggested, not working too, in both implementations the create() method is never get called
i tried to add this to he annotation:

 *   arguments = {
 *     "@entity.manager",
 *     "@entity_field.manager",
 *     "@plugin.manager.feeds.target"
 *   }

with this constructor:

public function __construct(array $$conf, $id, array $def, EntityTypeManagerInterface $en_m, EntityFieldManagerInterface $f_m, FeedsPluginManager $p_m)
  {
    $stop = null;
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->entity_type_manager = $en_m;
    $this->field_manager = $f_m;
    $this->plugin_manager = $p_m;
  }

and it's working only if this class is instantiated, and as i said it's not when the defaultCongiguration() get called, i can go without the plugin manager at this stage but i really prefer if i can have it in this function.

Update:

The reason why implementing either ContainerInjectionInterface or ContainerFactoryPluginInterface didn't work is because i added my dependencies in the arguments, annotation and in the create() method too.

This is probably a unit test (not mentioned in the OP). If so, the intention should be to test the methods of the TempTarget class, which means, that the first thing needed would be to instantiate an instance of that class, e.g.

/**
 * Instantiates and returns a TempTarget object.
 */
protected function getTempTargetInstance()
{
  $id = $this->generateId();
  $def = $this->generateDef();
  // This is where you mock the constructor dependencies/services.
  // You probably will need to create a mock like this:
  //   $this->getMockBuilder('Drupal\Core\Entity\EntityTypeManager')
  //     ->disableOriginalConstructor()
  //     ->getMock();
  $this->entityTypeManager = $this->getEntityTypeManagerMock();
  $this->entityFieldManager = $this->getEntityFieldManagerMock();

  // You can now call the constructor.
  $tempTarget = new TempTarget($id, $def, $this->entityTypeManager, $this->entityFieldManager);
  return $tempTarget;
}

At this point, your object should be instantiated and you can call methods on it to assert the assumptions you want to be testing. For example:

public function testDefaultConfigurationMethod()
{
  $tempTarget = $this->getTempTargetInstance();
  $formConfiguration = $tempTarget->defaultConfiguration();
  // Test different assertions given the $formConfiguration object.
}

However, at the time you call defaultConfiguration() you know that you need a container available that holds an entry for plugin.manager.feeds.target, so, you have to have that prepared in advance. The right place for that would be your setUp() method in your class, for example:

/**
 * {@inheritdoc}
 */
public function setUp() {
  parent::setUp();

  // Provide a mock service container, for the services our module uses.
  $container = new ContainerBuilder();
  $container->set('plugin.manager.feeds.target', $this->getFeedsTargetPluginManagerMock());
  \Drupal::setContainer($container);
  ...
  // Further setting-up of your testing class.
}

with getFeedsTargetPluginManagerMock() looking something like this:

/**
 * Creates and returns a mock for the feeds
 */
protected function getFeedsTargetPluginManagerMock() {
  $feedsTargetPluginManager = $this
    ->getMockBuilder('Drupal\feeds\Plugin\Type\FeedsPluginManager')
    ->disableOriginalConstructor()
    ->getMock();
  ...
  // Further mocking of the objects methods if needed.
  ...
  return $feedsTargetPluginManager;
}

Good luck!


How to migrate user passwords from D6 to D7 site using salt module? I need to migrate the user passwords from Drupal 6 site to Drupal 7 Website. I am using the migrate_d2d module for performing the migrations. But the problem I am facing is that the Drupal 6 site uses the salt module which appends an internal string to the users passwords before it is being saved to the database. So migrating the passwords as such doesn't work.

Can any one tell me if there is some way to migrate the user passwords in this case or its not possible??

It is not possible - both Drupal version stores user passwords in a way that was considered pretty secure when the major version was released. But these ways are incompatible. And by design you cannot recover passwords - it's a one way algorithm. Well, there are ways to hack passwords from D6 now (that's why it was changed in D7) but they are CPU-intensive, and in some countries attempts are outright illegal.

The best you can do is to use _user_mail_notify($op, $account, $language = NULL) - Set $op to 'password_reset' and call it inside foreach over all accounts after migration. That way all users will get an email saying they need to reset their password, with one-time link to do that. Probably there is already a module for that, too, but I couldn't find it.


Get a message if insert into table works The code I wrote that uses db_insert() and db_merge() works great. I can populate the database table well (also using a post http). Now I want to get a success/fail message.

How do I show a message after executing a query?

You can use drupal_set_message() to display a message in the browser, this can be marked as a status', 'warning' or 'error' message.

If you want to debug your code, the Devel module is recommended and provides the dpm() function. Besides being able to print a simple message, dpm() also allows to display an array or object quite easy.


can't group the ckk fields I am using drupal 6. I can create a group inside of a content type, but I can't see any way of attaching a field to the group. In a different installation of drupal on my computer, I see a box right under the new field name where you can enter a group, but this doesn't show up in this installation. Why would that be?

You can achieve this functionality by using the Fieldgroup cck module.


Internal server error on node save I'm getting internal server error on node save.

In db log messages there is no such error regarding this issue.

In apache error log I have these messages

mod_fcgid: read data timeout in 40 seconds, referer: http://test.com/node/add/photos
[error] Premature end of script headers: php-fcgi-wrapper, referer: http://test.com/node/add/photos

This was most likely caused by a rather long script that was timing out. The IPCCommTimeout on your virtual server is set to 40 seconds. If you encounter this problem again, you could edit the Apache directives that apply to this virtual server in /etc/apache2/sites-available/test.com.conf and set IPCCommTimeout, for example, to 300.

If you are using Virtualmin

Chose the virtual server that you want to edit from the drop-down
menu
Go to Services -> Configure Website -> Edit Directives
Modify IPCCommTimeout from 40 to, for ex. 300 (seconds)


Populate a field with the sum of two fields while content creation I have a content type named "ABC". Which has three fields

field_half(widget type list(text)),
field_full(widget type list(text)),
field_total(widget type float).

During content creation I want the field_total to be populated with the sum of two fields field_half and field_full.

E.g.

`field_total` = `field_half` + `field_full`

How can I do this.

Sounds liks a job for Computed Field

  Computed Field is a very powerful CCK field module that lets you add a
  custom "computed fields" to your content types. These computed fields
  are populated with values that you define via PHP code. You may draw
  on anything available to Drupal, including other fields, the current
  user, database tables, you name it.

You should just be able to set the field value literally as in your example (i.e. field = fieldA + fieldB)


Reasons to run Drupal on PostgreSQL What would be the strongest reasons for running Drupal on PostgreSQL, in terms of available features and performance? I.e. what postgres features of that are supported by Drupal are not available on mysql? For example, postgres is known for ACID conformance and transactions; does Drupal core take advantage of these or other features in any way?

This question is not about which is a better DB in general, rather whether there are any specific reasons why one might choose postgres over mysql. One obvious trade-off is that many contrib modules will be buggy running on postgres.

I am working with D6, but feel free to direct answers to any major version.

Personally, I think the only reason for choosing PostgreSQL over MySQL is if you (or your client) is already a PostgreSQL shop and have DBAs that know PostgreSQL well and know the ins-and-outs of babysitting it.  I would also say the same also applies for choosing MySQL over PostgreSQL, assuming you aren't using any contrib modules with MySQL-only functions in them.


drupal_add_js is removing jQuery I have the following in my module.

drupal_add_js(
    drupal_get_path('module', 'responsive_videos') . '/js/fluidvids.js',
    array(
        'type' => 'file',
        'scope' => 'footer',
        'weight' => 10,
    )
);

For some reason, when this module is enabled, jQuery and jQuery Once get removed from the head and the JavaScript console logs many "Uncaught ReferenceError: jQuery is not defined". Can anyone clarify why this is happening, and how to fix it?

Here is the info file, responsive_videos.info.

name = Responsive Video
description = Creates a fluid responsive video from YouTube or Vimeo embedded iframes.
core = 7.x

And here is the module file, responsive_video.module.

<?php
/**
 * @file
 * Makes YouTube and Vimeo embedded iframe videos responsive.
 */

drupal_add_js(
    drupal_get_path('module', 'responsive_video') . '/js/fluidvids.js',
    array('scope' => 'footer')
);

The JavaScript file being added does not leverage jQuery, so I don't quite understand how or if it might interfere with jQuery being added to the page, but here is the source of the "fluidvids.js" file.

// http://toddmotto.com/fluid-and-responsive-youtube-and-vimeo-videos-with-fluidvids-js/
(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    define(factory);
  } else if (typeof exports === 'object') {
    module.exports = factory;
  } else {
    root.fluidvids = factory();
  }
})(this, function () {

  'use strict';

  var fluidvids = {
    selector: ['iframe'],
    players: ['www.youtube.com', 'player.vimeo.com']
  };

  var css = [
    '.fluidvids {',
      'width: 100%; max-width: 100%; position: relative;',
    '}',
    '.fluidvids-item {',
      'position: absolute; top: 0px; left: 0px; width: 100%; height: 100%;',
    '}'
  ].join('');

  var head = document.head || document.getElementsByTagName('head')[0];

  function matches (src) {
    return new RegExp('^(https?:)?\/\/(?:' + fluidvids.players.join('|') + ').*$',     'i').test(src);
  }

  function getRatio (height, width) {
    return ((parseInt(height, 10) / parseInt(width, 10)) * 100) + '%';
  }

  function fluid (elem) {
    if (!matches(elem.src) || !!elem.getAttribute('data-fluidvids')) return;
    var wrap = document.createElement('div');
    elem.parentNode.insertBefore(wrap, elem);
    elem.className += (elem.className ? ' ' : '') + 'fluidvids-item';
    elem.setAttribute('data-fluidvids', 'loaded');
    wrap.className += 'fluidvids';
    wrap.style.paddingTop = getRatio(elem.height, elem.width);
    wrap.appendChild(elem);
  }

  function addStyles () {
    var div = document.createElement('div');
    div.innerHTML = '
x
';
    head.appendChild(div.childNodes[1]);
  }

  fluidvids.render = function () {
    var nodes = document.querySelectorAll(fluidvids.selector.join());
    var i = nodes.length;
    while (i--) {
      fluid(nodes[i]);
    }
  };

  fluidvids.init = function (obj) {
    for (var key in obj) {
      fluidvids[key] = obj[key];
    }
    fluidvids.render();
    addStyles();
  };

  return fluidvids;

});

fluidvids.init();

The reason it was breaking is because you’re doing drupal_add_js outside of any function or listener hook.

You need to add it to the appropriate build, alter or preprocess hook that suits your needs.


Headless Drupal 8 - cookie authentication I am successfully using a headless Drupal 8 setup that I am querying through Drupal 8 core REST API with basic auth from jQuery AJAX. Now I need to get closer to production conditions, so I started trying to use cookie-based authentication. Problem is that the exact same query that successfully POSTed content using basic auth now returns an HTTP 403.

Is there any working example of a POST request to create an article with cookie authentication? Am I missing something?

I have a fresh Drupal 8.3.1 install with REST UI, Serialization and HAL modules enabled. The REST endpoints are configured through REST UI. The /node/{node} endpoint is set up to allow all requests in all formats with cookie auth. Taxonomy and user endpoints are configured likewise.
The queries (POST & GET) to REST API are made from AJAX calls from jQuery. These queries work fine with basic auth. This is a query example.

$.ajax({
      url: 'my_drupal/entity/node?_format=hal_json&foo=bar,
      method: 'POST',
      headers: {
        'Content-Type': 'application/hal+json',
        'X-CSRF-Token': csrfToken, // I got that token by first GETting my_drupal/rest/session/token
        'Authorization': 'Basic ' + btoa(this.credentials)
      },
      data: JSON.stringify(node),
      success: function (node) {
         // success logic here
      }
    });

Please note that I already tried removing the Authorization header with no luck.

Monitoring HTTP requests, I do see the Drupal authentication cookie being sent along with my POST request.

It looks like maybe you are not successfully retrieving the CSRF token. The CSRF token can be retrieved from /rest/session/token.

See https://www.drupal.org/docs/8/core/modules/rest/3-post-for-creating-content-entities for examples on POSTing to core entity endpoints.


Blocks stopped showing on views page I was hoping you could help me with this problem on my website.

I have a views page "News" for a long time now. (q?=news)
I also have 2 blocks that I want to show on that page. On the configurations I set: All pages except those listed - and I listed all the pages i don't want the block to show (So I didn't write the News page).

Thing is, this was working fine and suddendly the blocks stopped showing on that specific page, and I have no idea why.

Any thoughts?

Thank you in advance!

P.S. I can't just try the "Only the listed pages" option because there are too many pages involved.

It's difficult to answer because I don't have enough information on what is happening, but here are some suggestions:

Give your views page a url alias of /news if you haven't already and in the block configuration make sure "news" is not listed there. Then you don't have to use "?q="
Make sure your spelling is correct so it's not q?=news and is ?q=news in your block configuration.
Views pages are not great to work with, personally I don't like them for a number of reasons. Instead, I use the insert_block module and I insert a views_block into my node, I get less problems like that and more flexibility.
The context module is also a good module for placing blocks in regions based on any type of page, but it's more difficult to manage.

EDIT: More things to check:

Make sure no styling is hiding those blocks. Check the markup loaded on the page and see if the markup for those blocks is loading on the page or not.
Make sure that the region you assigned those blocks to is actually loading on the views page.


How can I make Plupload in D7 start uploading automatically? I'm using the Plupload integration module and the problem is that once the users select the files, they think that they have already uploaded the files. No matter how obvious, bold and huge you make that "Start upload" button, most of them just ignore it. Plus it is not a good user experience.

What I need is for the "Start upload" button to disappear and the upload of the files into Plupload should begin automatically as soon as the files are selected. Would someone be kind enough to suggest how can this be done?

As given in the readme file of this module add following autoupload property to your form element as shown below.

$form['my_element'] = array(
  '#type' => 'plupload',
  '#title' => t('Upload files'),
  '#description' => t('This multi-upload widget uses Plupload library.'),
  '#autoupload' => TRUE,
);

I have tried it and in works fine.


Stop TinyMCE from applying styles I am building a Drupal 7 boostrap subtheme. I don't want users to be able to add their own fonts and styles to content. I want to force them to use the paragraph and heading tags as defined in my site's CSS.

When users paste in from other sources (eg word) I do not want the styles brought in. Additionally, our site uses Open Sans. This is not appearing in the TinyMCE font list, can this be fixed?

How does one do this with TinyMCE?

I had the same issue with CKEditor. the h1,h2,h3,h4,h5,p tags and color picker were available to the user But we wanted every available tag to has a custom color. To do so I put the CKEditor output which was body inside a DIV with some ID,say node-body-wrapper, then added styles like this

#node-body-wrapper h1{
     color : red !important;
}

...

In this way I solved the problem. I recommend you to do the same.


Add/edit node auto share to social networks Is there any way to add an option to share to social networks selecting with checkboxes and with predefined messages using token that a new node has been added or than an old one has been edited?

I had an idea about rules, and the Social Share module but I don't know how to implement it.

I used the Janrain module for getting similar functionality. It allows you to integrate social networking logins, set up buttons for social sharing and a lot of other stuff. Its actually pretty easy to set up the module

Some other modules include - Socialmedia, social login If you are just looking for sharing - Sharethis


Create a modal popup I want to show a modal popup in drupal 7. On searching the web I came to know that it can be done using the ctools module itself. Here is the code I tried:

function codeexpertz_menu() {
  $items['codeexpertz/%ctools_js/page'] = array(
    'title' => 'Demo CTools Page',
    'access callback' => TRUE,
    'page callback' => 'codeexpertz_ctools_page_example',
    'page arguments' => array(1),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function codeexpertz_ctools_page_example($js) {
  $output = "Sample CTools popup functionality for Demo purpose.";
  if ($js) {
    // Required includes for ctools to work:
    ctools_include('modal');
    ctools_include('ajax');
    return ctools_modal_render("Demo", $output);
  }
  return $output;
}

The link i referred is here

I added Modal Window to my page.tpl.php file directly for now to test it. However when I click on the link I get redirected on the destination page rather than showing the content in a modal.

I tried this is a fresh installation also, but all in vain.

You should use the ctools_modal_text_button function to render your "popup-opener" links.

ctools_include('ajax');
ctools_include('modal');
ctools_modal_add_js();
$link = ctools_modal_text_button('Open popup', 'codeexpertz/nojs/page', 'alt here', 'no-class');

You can have a look what the Modal Entities modue does in the modal_entities_generate_link() function for additional style settings.


Automatically translate double field select value, but not free text I have created a content type with a double field field configured as a Select list & Text field with a list of predefined allowed values for the Select List:

0|my option a
1|my option b
2|my option c

When I create a node for that content type in my default language, I get to choose between the 3 allowed values and can input some free text in the text field (as expected).

However when I translate my node, I am unable to translate the options from the select list (I can choose between them but can't change them).

I would like to be able to translate the allowed values list once somewhere (ideally at content type level, but I'm happy to have an alternative) and have those values enforced at node level when I translate.

For instance:

Default language (e.g English): I create 1 node with 1|my option b as the select value and some free text
Translation (e.g. Spanish): when I translate the node to Spanish, the select value becomes 1|mi opción b (which can't be changed) and I can translate the free text for the input field

Is there any way to automatically translate a double field select value (from one language to another), but not the free text (which can be translated freely) ?

Here is a simple workaround:

/**
 * Implements hook_field_widget_form_alter().
 */
function HOOK_field_widget_form_alter(&$element, &$form_state, $context) {
  if ($context['instance']['widget']['type'] == 'select_&_textfield') {
    foreach ($element['first']['#options'] as $key => $label) {
      $element['first']['#options'][$key] = t($label);
    }
  }
}


Reestablishing development workflow with GIT after doing it wrong At one point, I had the following proper Drupal development workflow: local development environment (using Mamp), dev server for testing and a production server, and I used GIT to deploy the changes from the local to the repository and then I would pull from the repository into the dev or production server. MAMP was causing me a lot of issues so I uninstalled it in favor of setting up a LAMP stack in a more traditional way. But I'm using a Mac and things got really wonky. I basically messed up my local dev environment beyond all repair and wasn't able to use it but I had an aggressive deadline for a project.

I began to make many changes to the website on the dev server and then doubling the work on the live site, no longer using the local environment or pushing the changes up using GIT. During this time, I didn't commit any of the changes to GIT either. Basically, GIT and the local dev have been out of the picture for the last several months.

Since my last commit, the following situations have changed.

created a new git repository that I want to use
my local dev stack is still non-functional
I want to set up a new host so I can test my existing dev site for current hosting issues

Where do I go from here in order to get back on track so that I can move the current website to a new host and preserve the GIT history without being able to use a local dev environment?

Commit the changes on the live site to the master git branch and then branch off this to create a develop branch.

The master branch should mirror live and development takes place on individual branches, when you're ready merge or pull request onto the develop branch. When ready to go live merge or pull request into master.


Problem with Drupal 6 built in "normal" caching - users getting data several days old on front page I have a site running Drupal 6. I was having performance problems so I turned on Drupal's built in "normal" level of caching performance -- which claims to not have any side effects.

Since I enabled this feature (about 3 days ago) I have users reporting that they are not seeing the latest content -- specifically the latest posts on the front page appear to be from several days ago. I believe this is happening both for logged in users, and anonymous users. I have not yet seen it happen as either a logged in user or an anonymous user.

What might be causing this and what steps can I take to troubleshoot it?

A couple of things to look at:

Adjust the Minimum cache lifetime set at on admin/settings/performance to something better suited to your users.
Make sure you have cron tasks in place to rebuild that cache on a regular interval. You can do it using Poormanscron in D6 (Built in core in D7).
Disable any server-side performace/caching mechanisms, such as APC, memcache, varnish etc...
Disable any extra Drupal caching mechanism, such as Boost.


Understanding $variables preprocess_views_view_field() According to this description of hook_preprocess_views_view_field(), $variables contains, among other things, $variables['field'].

However, if I do print_r($variables['field']) just to inspect the object it prints the entire object (to include my username and password!) and even causes the browser to crash.

I am trying to figure out how to check the field name but it is proving to be strangely non-straightforward.

How can I properly index $variables?

The browser is likely crashing because most of the views objects have circular references in them, and the output can be huge.

$variables['field'] is the field handler object for the field being rendered.  I am 97% sure these are all derived from \Drupal\views\Plugin\views\field\FieldPluginBase() (3% uncertainty because it is the end of the day and I am really tired).

You best bet is to do a debug(get_class($variables['field'])) to get the fully qualified class name, and then typehint in your preprocess, eg:

function MYMODULE_preprocess_views_view_field(&$variables) {
  /** @var \Drupal\views\Plugin\views\field\Boolean $field */
  $field = $variables['field'];
}

and then use your IDE to navigate through what you need to do.

To see what is in $variables, just do a

debug(array_keys($variables));

and go through a similar exercise to get the types; it's just a boring associative array where the keys are all strings.


How to count the number of unique views of a node? Is there any possible way to find the number of views of a node.

For example:

I have created a node called "Sample".

If i viewed it once then the count should be increased as 1 view and when i view the same node again it should not get increased.

Is there any module to do that..

Else what's the best way to do it ?

It depends how much traffic you site has and how big your server is. If you need to create a view count like this, it will require that you disable page cache making your site slower and demanding more resources from your server, or run expensive queries on every node view.

You could do this with Drupal, but there isn't a module that provides this functionality for you. The statistics module will count all views of the node. To implement this you would need to use either hook_node_view or hook_boot and write to a database the nid of the node being used and a token for the user. If you don't want to count anonymous users, you can use the uid, else you would have to use a combination of uid and session id to try not to count the same anonymous users twice.

A better way if you have a lot of traffic is to use an external tool like Google Analytics and then draw data from there.

Both solutions will require custom code though.


How to hack a module which has not API I am using the module Print for print/mail node's content. However, I have problems to send email. I want to hack the module, so it will use the PHP class PHPMailer instead, and will hard-code the sending of the email. Everythings works perfect, but the situation is that there is no API and I have hard-coded directly in the module, so when the module is upgraded, I will lost my coding. Is there any way of making a hook of the desired function so I will get the same working but will still be able to upgrade the module without problems? I will accept other solutions, but the question is more general (I maybe would need to do something similar with other modules which do not provide API in the future). Thanks!!!

Usually there are two situations: your hack may be useful for other users or your hack is very very custom and is not likely to be useful for other users.

In the second case you can go with arpitr answer.

If your hack can be useful for other users (like this case) you should open a new Feature request or bug issue in the module's issue queue where you can share your hack as patch to the module. This way:

Other people can evaluate and discuss your code and solution pointing out any mistakes or bugs you are not aware of, improving your changes.
Maintainers can commit your patch to the module so in next upgrade you don't lose your changes as changes are included in the new release.
Any ohter module's user can benefit from the new feature.

The drawbacks is that your code must fit the general usage of the module, so your feature should not break others module's functionalities or usages. This may imply more work but benefits are good enough.


MathJax(LaTex) equation shows in the CKeditor body area but not on the final webpage? I am using CKEditor module and have enabled MathJax option. When I use MathJax it works in the CKeditor and shows teh eqiation, but on the final display webpage instead just showing equations it is showing all code. What could be the reason and solution?

Check Manage Display in your content type and ensure it's using the proper text format. I think Mathjax has to be at the bottom of the list as well in the format settings.


REST interface to custom entity type getting constant 403's I created my module and the entity definition using the drupal console. It has not been modified at all. My entity is for a user but for various reasons I won't be using the pre existing user entity.

I installed restui, serialization, hal, basic auth. All working fine.

I have created a REST instance for my entity using the UI; POST & GET using json+hal and basic auth.

Using curl (and Postman) I can create and retrieve a node; I can also retrieve a custom user entity that I created through the UI. All the above was easy, no dramas, took no time at all.

Then it came to creating a custom user entity. No dice. I get persistent 403's and nothing in the message (and nothing logged in watchdog which is handy.)

The auth is using an admin account (in fact 2, I created a new one in a display of desperation); admin users have all permissions by default, but I did add extra permissions to authenticated role also in the off chance that it used that internally. (More desperation.)

I'm clearing the caches every 5 minutes also.

I have sent requests using the X-CSRF-Token header using a mix of fresh and old tokens (ie, requesting new ones before a full request and then trying old ones also). Anybody know how often we should be retrieving new tokens?

I've also tried with no tokens.

The issue is that I have no idea where this is falling over, so all I can do is flail my arms around in a vain attempt at hitting something useful (I'm sure this was a dungeons and dragons action?)

The body of my POST request has been changed also, but I'm not convinced that it would throw a 403 if incorrect, I'd assume a 'malformed' response would come back or at least a non 403. Can anybody confirm?

As my entity was created by the console and I can see all the CRUD permissions enabled on my admin roles, where can I go from here?

The answer is quite simple but easy to miss.

The URL I used when I made the GET request; http://apps.dev/app/apps_user/1?_format=hal_json is not the same as the URL required to make POST requests.

To make a POST request, you change it to http://apps.dev/entity/apps_user?_format=hal_json

None of the URL's in the returned _links property are correct for POST requests.


Using modules "not covered by Drupal’s security advisory policy" I would like to use a Drupal 7 module that is "not covered by Drupal’s security advisory policy", specifically the Conditional Fields module.

It would allow me to do exactly what I need. It looks like this module is pretty actively used and maintained but I am not sure how worried I should be about using a module that I won't get updates about if any security issue should arise.

Any advice? Is coding something like this (using hook_form_alter and states)  myself a safer approach?

According to the Security advisory process and permissions policy, modules that have an alpha, beta, or rc (relase candidate) status are not covered by this policy, and security advisories will not be reported for these projects. At the time of writing, Conditional Fields has recommended releases for Drupal 7 and 8 that are both in "alpha" stage. Even without security advisories, you can still choose to be notified when the module is updated.

Since module releases and their status are arbitrarily assigned by project maintainers, only you can judge whether you should use a module marked as not being covered by Drupal’s security advisory policy. One maintainer's "alpha" module, would be a "1.0" version to another maintainer.

You should examine the maintainer's credibility, history on Drupal.org, the project's popularity, and the speed at which issues are resolved or responded to. Many popular and public sites do make use of "beta" or other modules.

Coding your own module to duplicate the functionality of a module that already exists seems more likely to introduce security vulnerabilities that can potentially only be diagnosed or fixed by one person: you. Using an "alpha" module with a competent maintainer and an active community of users seems far more advisable.


How do I override the subscription block? I am developing a Drupal 8 website and I want to override the subscription block used by the Simplenews module. I know how to achieve that at Drupal 7, but the module is different now. For Drupal 7, I followed http://api.worldempire.ch/api/simplenews/theme%21simplenews-block.tpl.php/7-2.

I want to do the same for Drupal 8. How can I achieve it?

There is no exact equivalent currently. To override the actual block template for that block you can use 'block--simplenewssubscription.html.twig'. You can use the input and form templates to override other elements. I would suggest enabling debugging in Twig so you can see the template overrides.


field_groups - adding an inner div wrapper programatically I have some older code that used this method to add an inner div containing inline style.

Much like the linked question above. I am using hook_preprocess_node to attempt this.

However, the $variables['content'] array no longer seems to contain the groups in it and I'm not sure exactly what's changed. I haven't managed to find much else on this in the issue queue and elsewhere.

It is strange that this has changed and I can't really find any posts relating to it.

I'm going to update my code to use hook_field_group_build_pre_render_alter() as an alternative.


How do I create a view to re-arrange blocks or menu items? I would like to create an admin view that allows to reorder menu items. I know it is a standard admin feature, but I would like to display it in a panel.

How can I do that ?

You can use draggableviews to reorder the items.


Commerce Price Table: What would cause sporadic zeroing of prices when adding to cart? I'm having an issue where the prices in the price tables are sometimes being applied when adding items to the cart, and later, other items are set to zero when added to the cart. First off, I must mention that I am working with products that have 3 price tables, and each price table has 4 price breaks. I wasn't exactly clear on if/why support for multiple tables was or wasn't possible, but I am worried that this might be the culprit. If it's not safe to have multiple price tables for a product, please let me know right away!

Other details: Each of the 3 price tables for a product is for a different user role. I use field permissions on a multipage view to make this possible. What may make it complicated is that not every product has a price for each role. That is to say, not all products are available to all roles. To combat this, I added a filter to only show items where the price is not $0.

I'm very deeply entrenched in this module, as I have several commerce feeds going and thus have spent many hours formatting the incoming data in the CSV files, so Commerce Pricelist would not be a good alternative.

Obviously, something is wrong somewhere when the rules are firing to apply pricing. Read up on debugging rules and you'll likely find your problem.

One thing you may want to consider is just writing your own custom logic and then creating a new rule to call your custom logic, bypassing the logic of Commerce Price Table. You'll likely need to really spend your time adding your logic to commerce_price_table_get_amount_qty since that's where the actual field and price get determined.


Vertical Tabs for node Content? I would like to basically make a node with some tabs on the left that switch what's being viewed on the right. I can structure the content however I'd like since it's a node; is there a way to simply make the content display inside vertical tabs, like on the node editing forms, but when viewing the form?

Does the Render API allow rendering content in vertical tabs in a node?


How do I add an additional sidebar to a Zen sub-theme? I want to add an additional sidebar to my zen based theme with fixed columns.
I added it to the theme info, and printed it in the page.tpl.php file, but I don't know how to
configure its CSS files to make it look correct; I don't know how to make the content region expand to fill the available space when there is an empty region with no blocks in it like with Zen.

My theme contains 4 columns:

left sidebar 1 (130 pixels)
left sidebar 2 (255 pixels)
content (509 pixels)
right sidebar (130 pixels)

The total width would be 1024 pixels.

How can I do that?

You can do it with preprocess function at template.php template. I will write you just one example, and you can adapt it for your needs.

1.At Your template.php template.

function yourthemename_preprocess_page(&$vars, $hook) {
  $page = $vars['page'];
// if only left sidebar is present
  if ($page['left_sidebar'] && !$page['left_sidebar2'] && !$page['right_sidebar']) {
    $vars['class_content'] = t('yourclassforcontentwithsidebar');
    $vars['class_left_sidebar'] = t('yourclassforleftsidebar');
 }
// if no sidebar is present
  if (!$page['sidebar_left'] && !$page['left_sidebar2'] && !$page['right_sidebar']) {
    $vars['class_content'] = t('yourclassforfullwidhtcontent');
 }
}

You can find more variations here: php logical operators.

2.At your page.tpl.php, at all regions where you want flexible width, put extra class, for example for left sidebar:

   <?php if ($page['left_sidebar']): ?>
      <div id="left_sidebar" class="sidebar <?php print ($class_left_sidebar);?>" >
        <?php print render($page['left_sidebar']); ?>
      </div>
    <?php endif; ?>


Multi template files for a content type is it possible to use multiple templates select for a content type. I am thinking of having a select_list which will be shown while adding the content and you can choose how your page will look like, based on existing template files.

thanks

Sure.  You can use hook_preprocess_node() to do this, eg, something along the lines of:

function YOURTHEME_OR_MODULE_preprocess_node(&$variables) {

  $node=$variables['node'];

  $foo= /* get the value of this field from $node */ ;

  $variables['theme_hook_suggestions'][] = 'node__' . $foo;

  // or....

  switch ($foo) {

    case 'FIRSTVALUE':
      $variables['theme_hook_suggestions'][] = 'node__FIRSTSOMEOTHERSTRING';
      break;

    case 'SECONDVALUE':
      // etc etc etc

  }

}

and then Drupal 7 will look for a node--WHATEVER.tpl.php.

ADDITION:

If you are wanting the PAGE itself to be different based upon this field, then you would use hook_preprocess_page() with similar logic but using page__WHATEVER instead in the theme hook suggestions and page--WHATEVER.tpl.php in the template names.


Turning/unloading off jquery? I'm working on themeing a single site of a multi-site Drupal install.  The organization that set up the site has jquery 1.2.6 installed which is fine for most things... but as I'm planning on using a few other javascript libraries and maybe a few $.ajax calls, I was hoping for a more up to date jquery for the sake of compatibility.

Is there a way I can write a javascript call to remove the:

<script type="text/javascript" src="/misc/jquery.js?K"></script>

and then call my own?

You cannot just push a newer version jQuery by adding/replacing the  tag. Drupal and some modules bundles their own JavaScript that rely on that specific version of jQuery, updating jQuery may break these JavaScript. Most of these script require the jQuery object (from jQuery 1.2.6) to be binded to $.

If really needed, you can load an newer version of jQuery in noConflict mode, treating the old jQuery as a an other library. So $ will still be the old jQuery object for the existing script. Andyou can use newer jQuery version using jQuery in your script. Properly written plugins and libraries should access the jQuery object using jQuery instead of $ and so should be loadable (after calling the noConflict() method). IF not, you may need to fix them.


display selectable drop down options based on a checkbox selection I am trying to create a form in Drupal. I want to create the following situation: if a  checkbox is selected I want to display a drop down menu. can you please suggest a way to do it.

Programatic way

  $form['checkbox_form'] = array(
    '#type' => 'checkbox',
    '#title' => t('sometitle'),
    '#default_value' => variable_get('checkbox_form', TRUE),
  );

  $form['selectbox'] = array(
    '#type' => 'select',
    '#title' => t('sometitle'),
    '#default_value' => variable_get('selectbox'),
    '#options' => array(
          TRUE => t('Yes'),
          FALSE => t('No'),
     ),
    '#states' => array(
      'visible' => array(
        ':input[name="checkbox_form"]' => array('checked' => TRUE),
      ),
    ),
  );

Second form element visible makes the trick.

Module Way

Use Conditional Fields module.

  Conditional Fields allows you to manage sets of dependencies between
  fields. When a field is “dependent”, it will only be available for
  editing and displayed if the state of the “dependee” field matches the
  right condition. When editing a node (or any other entity type that
  supports fields, like users and categories), the dependent fields are
  dynamically modified with the States API. A simple use case would be
  defining a custom “Article teaser" field that is shown only if a "Has
  teaser" checkbox is checked, but much more complex options are
  available.


Conditional display of CCK fields I was wondering if there is any other way apart from coding (and, possibly, using the rules module) to make the showing of a field dependent on the existance of another field.
Say you have in a node, a video and a photo. You want to show only the video in teaser but if you have not provided a value for the video, then the video field should not be showing, and instead the photo field should be showing.
If you have provided a video, then the photo field should not be showing.
Any ideas?

The only solutions I know except coding it by yourself its Content Templates module. This module allows you to change the template directly from you back office.

The advantage it's that you don't need to deploy your code if you need small change.

You've also Display Suite that seems promising, I never tried but the description sounds good for what you need.


Link to Existing View from another view Im trying to create a view that should have a field which links to a pre-existing view (And Permissioned appropriately). Ive looked into various modules and field options but cannot find it (Newbie to Drupal!).

Basically, I have a view(called, Recipe_Filter) where I have some filters for selecting recipes based on various conditions. I have another view where I show recipes for a particular user and also want to create an "Edit" link that points to Recipe_filter. The problem is that I dont want normal users to see the "Edit" link and only certain roles to be able to view this.

I tried suggestions like the one in this but if I do as in that link, I see a "Edit" link and clicking on it shows a "You are not authorized  to access this page" text. I would like to disable the Edit Link if the user doesnt have access.

Are there modules that will allow a link to an existing view and permission it (like how the standard "Edit to content" or "View to content" works). Any help or pointers would help a lot.

I was able to solve it using Views PHP Using some custom PHP to show the "link" only if the user has permission. Not sure if thats the most elegant way.

I would like to know if there is a better approach to solving this. Thanks!


Are there any modules that can export and import nodes while preserving node id's? Our website uses VBO + Views Admin screen for the admin/people screen. Today one of the user admins deleted some old user accounts, by checking the checkbox next to the names and selecting the "Delete" option from the Actions dropdown. What he didn't know (+ I didn't know) was that by using the "Delete" option he also inadvertently deleted all the content created by those users as well.

I've got a backup of all the nodes that have been deleted, however I'm at a bit of a loss on what's the best option to restore these. The site has 10+ content types, and loads of custom fields (field_x_revision + field_x_data tables!! for each field). I need to preserve those node ID's. I'm going to be doing this locally and the once I've got a completely merged database I'm going to put it back on the live site.

Are there any drupal modules that can export nodes and also import them (and preserve the old node id's)?

If your backup contains the previously existing users, you could try to recreate your production site locally... Here are the steps I would follow (never tested though):

install a local drupal site with your backup (files should be restored as well) in the production site, via VBO
put your production site in maintenance mode
target all the new / updated nodes since the incident
export them via Node Export
reimport them locally (the nids should be preserved thanks to NodeExport and UUID)
reinstall your local db in production


Is it possible to patch a non-dev version of a module? I can create patches from dev copies of modules just fine thanks to this documentation, but when I try to create a patch from a non-dev version I get troubles. If possible, How do I do this?

There would be a few differences from the process described on that documentation page.

In Step 1, when creating the topic branch, specify the commit from
which to create the branch. You can do this by appending a commit
ID, a tag name, or an existing branch name to your git branch
command. Tag name should work, because Drupal project releases are
tagged with the project version number. So if you wanted to patch
off of the 7.x-1.5 version of a module, instead of this:

  git branch [issue-number]-[short-description]

You would do this:

  git branch [issue-number]-[short-description] 7.x-1.5

You would skip Step 4 and 5, since those steps are for making apply
to the most recent dev version.
In Step 6, when using the git diff command to create your patch
file, you now want to diff against the commit that represents the
unmodified version. Again, we can use the tag/version name.

  git diff 7.x-1.5 > [project_name]-[short-description]-[issue-number]-[comment-number].patch


How to add a CCK field to custom template file? I am working on a Drupal 7 site, and I am setting up a template that will be used with the Print module when PDFs are created using that module. The PDFs will draw from pages that list specifications of products, and the PDF itself will act as the printed spec sheet.

I want to completely customize the output of the PDF so that I can choose where each and every field will be placed. Unfortunately, the PDF creation is currently not respecting all of the layout specifics on the website page, so I have decided to customize the print.tpl.php file (part of the Print module) to enact those specific layout elements.

The part I am stuck on is... how do I call in the various individual fields/fieldsets from the content item and have them show up on the template file for printing? For instance, the content type is "Shirts" and one of the fields in question is "Color" ("field_shirtcolor")... how can I access that field/print that field in my custom tpl file?

Thanks!

Add to your print.tpl.php code like next for printing certain field:

<?php print render(field_view_field('node', $print['node'], 'field_shirtcolor')); ?>

If field is multiple:

<?php
  $field = field_get_items('node', $print['node'], 'field_shirtcolor');
  $delta = 0;  // Put here index of multiple field or use `foreach ($field as $val) {}` for scanning multifield values.
  print render(field_view_value('node', $print['node'], 'field_shirtcolor', $field[$delta]));
?>

If field is image:

$image = field_get_items('node', $print['node'], 'field_image');
print render(field_view_value('node', $print['node'], 'field_image', $image[0], array(
  'type' => 'image',
  'settings' => array(
    'image_style' => 'STYLENAME',
    'image_link' => '',
  ),
)));

p.s. Drupal 6 CCK in Drupal 7, 8 called as just Fields.


How to hide webform block for users who submitted the form already? I have created an inquiry form using the Webform module. I displayed it using block by enabling Available as block (Form Settings -> Advanced Settings) which is working fine and the form submitted by all (Anonymous, Authenticated user).

I want to add a visibility that if a user has already filled the form, the form should not be visible to that user until the site is close.

Have a look at the Rules block visibility module. Here is a quote from its project page:

  The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.

  The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless:

  Need to show a block only for users registered more than a month ago?
  Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
  What about displaying or hiding a block based on current weather conditions?

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

With that, and as per the "if you can do it with Rules, you can use it to control block visibility" above, you may have a possible solution for your question, provided you can think of an appropriate rule to be used for it. Using the Webform integration with Rules, you should be able to catch (=Rules Event) the submission of a form by a user. And combine this with some type of Rules Action so that the form is no longer visible to that user.

For an illustration of how to use this module, refer to my answer to "How to stop a Views block from displaying to admins, such as user/1?".


How do I change the node view mode before rendering? I have a content type with a custom view mode. How do I make sure node always get rendered with my custom view mode?

What would be the right way to programmatically change the node view mode before rendering?

If you want to make sure that a content type is always rendered with a custom view mode, use the following hook in a module. (I assume the module machine name is mymodule.)

mymodule.module

/**
 * Implements hook_entity_view_mode_alter().
 */
function mymodule_entity_view_mode_alter(&$view_mode, $entity, $context) {
  if ($entity->getEntityTypeId() == 'node' && $entity->bundle() == 'my_content_type') {
    $view_mode = 'my_custom_view_mode';
  }
}


Can't login: user/login redirects to index page My Drupal 7 user, user login and admin pages all redirect to the index page. I am unable to login at all. This problem came up recently after the site had been unchanged for months.   I can't think of a single reason this started happening all of a sudden.

http://sohp.us/?q=user
... ?q=user/login
... ?q=admin

Nothing looks funny when I debug in my browser. I have the following details based on my research:

No errors are appearing.
There were no updates, automatic or manual, to the site or modules.
I'm not using Secure Pages, Ubercart SSL, or any other SSL modules that might interfere. The site is pretty basic, simple Zurb Foundation theme, Views, and a couple other small modules, nothing fancy.
$base_url = 'http://sohp.us'; // NO trailing slash!  Is specified in my settings.php file (located in root/public_html)
The Drupal instance was installed through cPanel's Softaculous
I downloaded the default .htaccess for Drupal 7 and replaced the existing one (no changes required).

It seems like the PHP for bringing up the login isn't working correctly, but I could definitely be missing something obvious or compeltely different from what I've been trying. If anyone has any suggestions on things to test out to get myself back in, it is much appreciated.

Thank you.

Do you have drush installed? I would try clearing cache as a first step, probably won't fix it but worth a shot. After that try renaming the theme that you are using to force Drupal to use a different theme, or change the theme manually in the database. Try disabling modules one by one to see if any of them might be interfering. Start with any module that changes paths (like PathAuto...). I also noticed that no matter what your site will not throw a 404 page not found error. If that was intended, then whichever process you used to redirect 404's to index.php could possibly be causing an issue.


Conditionals with Combining Fields in Views I'm having issues with rewriting the results of a field. I am trying to rewrite the field to be a combinations of 3 fields:

[field_products]
[field_downloadable_products]
[field_product]

When I preview my field I see this:

Is there a way to add a conditional statement to fix the issue where the other tokens are showing when there isn't a value there for those tokens?

Here is a view of my rewritten results:

Instated of

 [field_products} [field_downloadable_products] [field_product]

Try

[field_products] [field_downloadable_products] [field_product]


preserve format of node body for output display I used http://foundation.zurb.com/docs/components/accordion.html

I have the following code:

About Us

<?php foreach ($view->result as $key => $value) {?>
<img class="media-object" src="<?php print $GLOBALS['base_path']."sites/default/files/about/thumbnails/".$value->_field_data['nid']['entity']->field_about_us_image['und'][0]['filename'];?>" alt="">

<?php echo $value->node_title;?>

    <a href="#pane<?php print $key;?>">
    <?php print $value->_field_data['nid']['entity']->body['und'][0]['summary'];?>...
    <div id="pane<?php print $key;?>" class="content">
     <?php print $value->_field_data['nid']['entity']->body['und'][0]['value'];?>

  <?php } ?>

I want to preserve the format HTML  of

<?php print $value->_field_data['nid']['entity']->body['und'][0]['summary'];?>

and

<?php print $value->_field_data['nid']['entity']->body['und'][0]['value'];?>

How Can I achieve this with Drupal 7?

Are you talking about the spacing in the html itself? So the code looks visibly nested? Such as:

         something

If that's the case, you might want to try a WYSIWYG and add WYSIWYG CodeMagic


Translate label of Comment Body with String Override I'm using i18n and string overrides for translating fields in the front end. I opened up the comment-section for several content types and it's working great. The only thing is: I can't find a way to translate "Comment" to german to "Kommentar".

I just found out, that the Comment-Form doesn't get a specific language-tag. So it is und(efined) which leads to the english word Comment.

The easiest but a little dirty way to fix that is to translate it by hand with the hook_alter_form in the template.php

Is there a more cleaner way to do that?

Thanks

Yes there is you should try out
Localization client

This would help you out, and translate the content in t()


Is there advantage to using Drupal.settings, as opposed to directly passing json-encoded var to javascript function Inside my custom views template, views-view-myview.tpl.php, I have a variable ("$myvar"), which I need to pass to a custom javascript function.  Here is how I am currently doing it:

A.  json-encode $myvar

<?php
$my_json_var = json_encode($myvar);
?>

B.  Pass the variable as an argument to my custom function, on page load

<script>
Drupal.behaviors.mystuff = function (context) {
  my_js_function(<?php print $my_json_var; ?>);
});
</script>

I am noticing that Drupal developers generally pass variables to javascript using Drupal.settings, and I am wondering whether I should switch and use Drupal.settings instead.

Question:
Is there any disadvantage of doing things my way, as described above?  Is there any reason it would be better to switch to Drupal.settings.
Note:  $myvar is relatively large, say 100k.

Thanks very much

The advantage of having in Drupal.settings is the values can be globally accessed across the JavaScript functions. In your case the function "my_js_function" only can access it because of its scope. It is based on the need and if you feel it is unnecessary to have it in settings then you can go with your method.

But best practice is to use Drupal settings. This method will never fail you.


How to render youtube field? How can I render a Youtube field to get the full code for embedding?

field_view_field('node', $o, 'field_testvideo', $display)

What are the settings for $display?

$display should be one of view modes (full, teaser, rss or ...) or display setting array:

$display = array(
    'label' => 'hidden',
    'type' => 'file_rendered',
    'settings' => array(
        'file_view_mode' => 'media_original',
    ),
);


Allow user to request resend of activation email I would like to code a way for a user to request the activation email be resent. Is there a function I can call from within a form-submit hook that will accomplish this?

(using Drupal 7)

First you need to create a custom form page using hook_menu() to allow users to enter their emails.

 /**
 * Implements hook_menu().
 */
function custom_user_menu() {
  $items = array();

  $items['user/trouble'] = array(
    'title' => 'trouble logging in',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('custom_user_trouble_logging_in_form'),
    'access callback' => TRUE,
  );

  return $items;
}

Second, you need to create form structure

function custom_user_trouble_logging_in_form($form, &$form_state) {
  $form['mail'] = array(
    '#type' => 'textfield',
    '#title' => t('E-Mail address'),
    '#size' => 60,
    '#required' => TRUE,
  );

  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Resend activation email'),
  );

  return $form;
}

Third, validation step (check if user email already registered)

/*
 * Validation function
 */
function custom_user_trouble_logging_in_form_validate($form, &$form_state) {
  $account = user_load_by_mail($form_state['values']['mail']);

  if(!$account) {
     form_error($form['mail'], t('Invalid user email'));
  }
}

Fourth, resend user activation email on form submission.

/*
 * Submit function for the 'Re-send welcome message'.
 */
function custom_user_trouble_logging_in_form_submit($form, &$form_state) {
  global $language;

  $destination = array();

  if (isset($_GET['destination'])) {
    $destination = drupal_get_destination();
    unset($_GET['destination']);
  }

  $account = user_load_by_mail($form_state['values']['mail']);
  $user_register = variable_get('user_register', 2);

  switch ($user_register) {
    case 0:
      $op = 'register_admin_created';
      break;
    case 1:
      $op = 'register_no_approval_required';
      break;
    case 2:
      $op = 'register_pending_approval';
      break;
  }

  $mail = _user_mail_notify($op, $account, $language);
  if (!empty($mail)) {
    watchdog('user', 'Welcome message has been re-sent to %name at %email.', array('%name' => isset($account->realname)? $account->realname : $account->name, '%email' => $account->mail));
    drupal_set_message(t('Welcome message has been re-sent to %name at %email', array('%name' => isset($account->realname)? $account->realname : $account->name, '%email' => $account->mail)));
  } else {
    watchdog('user', 'There was an error re-sending welcome message to %name at %email', array('%name' => isset($account->realname)? $account->realname : $account->name, '%email' => $account->mail));
    drupal_set_message(t('There was an error re-sending welcome message to %name at %email', array('%name' => isset($account->realname)? $account->realname : $account->name, '%email' => $account->mail)), 'error');
  }
  $form_state['redirect'] = $destination;
}

Note: custom_user is the name of the module that I used. You can change to whatever you like.


Do I have to update to 8.3.0 first before I can update to latest stable release? I pritty messed up my site by updating my 8.2.6 site as followed.

Step 1: I edit my composer.json file. I replaced the replace to require
"replace": {
        "drupal/core": "~8.3" to

"require": {
        "drupal/core": "~8.3"

Because I wanted to update core and vendor I did this composer command
step 2: composer update --with-dependencies

step 3: Site was broken unexpected error (500) using WAMP 2.4.23, php version 7.0.10 and mysql 5.7.14.

Do I have to update to 8.3.0 first before I can update to latest stable release?
- example: composer require drupal/core:8.3.0

It depends on your modules. If you are using DisplaySuite there is an issue with updating because of the change from layout_plugin to the layout_discovery module. See this issue. And have a look at the 8.3.0 Release Notes for broken changes and affected modules.


HTML template for Custom Content Type I'm reasonably new to Drupal... I've known about it for quite a number of years and have played around with it in the past, but only in the past 4 months have I started to make a serious website with it. Possibly a bit harder to configure than say WordPress, but so much more worth it when it's finished!

One thing that I'm trying to do is work with custom content types. What I am trying to do is create a custom content type called "Talk." In this I want to be able to specify a small description, an embed video URL and a link to PDF notes. I am having a really hard time to try and work out how to do that, and be able to customise it in a way I want.

What I want ultimately to be able to do is specify a HTML template for a custom field. That HTML then specifies where the fields appear (which may become problematic when there can be an undetermined number of entries for a particular field, but there could always be some way.)

Basically, let's say I specified the following

Summary: This is my summary
Embed: http://player.vimeo.com/video/51254497?title=1&amp;byline=1&amp;portrait=1
Notes: http://link/to/notes.pdf

I then want to be able to take those values and put them somewhere in HTML. For example...

[Summary]

Download corresponding notes

Is there any way that I can create a custom content type that would give me that much control over my field? I've had a look but haven't been able to find any way, even with a module (though there's a good chance I haven't seen the right module!)

Thanks for any help,
Josh.

Think your looking into this a bit too deep for what it is.

For your fields you use the following:

Summary: Default field with any content type
Embed: http://drupal.org/project/youtube (not sure if theres something for
vimeo)
Notes: Create a field that accepts PDf file extension

You then have loads of options for how you can present your content type. How about just creating a template file for that content type so...

node--type.tpl.php

You can then manipulate the output of the fields, for example...

    print render($content['youtube_field']);

    print render($content['pdf_field']);


Custom js added with drupal_add_js doesn't actually get added if I enable "Aggregate JavaScript files" or "Cache blocks" The site is the most stock, only Drupal 7 core is installed.
included my theme, where the page.tpl and html.tpl theme files are copied from core
I created a Yandex.Maps module, this is a block where js is added.
<?php
  function yamap_block_info(): array {
    $blocks['yamap'] = [
      'info'  => 'Block Yandex.Map',
      'cache' => DRUPAL_CACHE_PER_ROLE,
    ];
    return $blocks;
  }

  function yamap_theme(): array {
    return [
      'main-yamap' => [
        'template' => 'yamap-block',
      ],
    ];
  }

  function yamap_block_view($delta = ''): array {
    if ($delta == 'yamap') {
      $module_path = drupal_get_path('module', 'yamap');
      drupal_add_js($module_path . '/src/js/yamap.js', ['scope' => 'footer', 'weight' => 40]);
      drupal_add_css($module_path . '/src/css/yamap.css');

      return [
        'content' => theme('main-yamap'),
      ];
    }
  }
?>

When I enable cache and aggregation, js falls off .. there are no errors on the page and in the console.
Drupal.settings.my_data does not exist too. But, if I turn off the block cache or aggregation, then everything is ok

Is the site in D7 or D8/9?
Because in 8+ you should use  #attached instead of drupal_add_js/css


How to embed a view in a specific node? I try to embed a view in a specific node. I found tutorials for doing this with Drupal 7 and PHP-Templates:

<?php print views_embed_view('view_name'); ?>

But I look for a way in Drupal 8 with twig-Templates. I tried to call the views_embed_view() function in the hook_node_view() and assign it to the node so that I can print it out in the twig-Template. But it seems that this hook never gets called.

Any hints/solutions how to do this in the Drupal 8 way?

Twig Views Embed

  This module allows to embed views with a twig function.

{{ views_embed_view('view_name', 'view_id') }}

The above module was depreciated in favour of

Twig Tweak

  Twig Tweak module provides a Twig extension with some useful functions
  and filters that can improve developer experience.

Ex:    <dd>{{ drupal_view('view_name', 'view_machine_name') }}</dd>

You can find the view_machine_name over here


Date field comparison in Rules I'm trying to check if a date field value has been changed on a node update. (Rules Drupal 7)

Here's my rule configuration:

    { "rules_node_update" : {
    "LABEL" : "Update",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_presave--expedient" : { "bundle" : "expedient" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node-unchanged" ], "field" : "field_tria" } },
      { "NOT data_is" : {
          "data" : [ "node-unchanged:field-tria" ],
          "value" : [ "node:field-tria" ]
        }
      }
    ],
    "DO" : [ { "drupal_message" : { "message" : "UPDATED DATE" } } ]
  }
}

Event: Before saving (i have already tried with node update)

NOT data comparison
Parameter: Data to compare: [node:field-tria], Data value: [node-unchanged:field-tria]

What i'am trying to do here is... IF the (new) date value IS NOT EQUAL to unchanged field value (old)... THEN do something. (like print message on screen)

The result of the data comparison returns always TRUE and don't know why.

Notes:

Having proven the suggested changes, the result remains the same. I edit a node, and whether I change the value of the "tria" field or not, it still returns true.
If I (temporary) OMIT the data comparison it shows the final message. Here's an example of what i'm getting with my setup: Edit a node of this content type, the node already has a date data in the "tria" field. Without making any changes, just save. It shows the message. If i change that field value to another and then save. It also shows the message. So, i think node-unchanged value must me empty because she's not doing the data comparison the right way.
Here is the debug of the variables after saving/updating a content : Debug value Parameter: Value to debug: [node-unchanged:field-tria] ... (Array, 1 element) 0 (Array, 6 elements) value (String, 19 characters ) 2001-01-10 01:00:00 value2 (String, 19 characters ) 2001-01-10 01:00:00 Debug value Parameter: Value to debug: [node:field-tria] ... (Array, 1 element) 0 (Array, 10 elements) value (String, 19 characters ) 2001-01-20 01:00:00 value2 (String, 19 characters ) 2001-01-20 01:00:00 Values are there, and they are different! as expected!
The rule evaluation log shows this once the node has been updated with different values:

The rule evaluation log shows this once the node has been updated with no changes on the values... just saved

Part 1 - Just to be sure

Add an extra Rules condition like "entity has field", related to that field-tria, before your existing Rule Condition where you do that data comparison.

If that doesn't seem to help, then (temporary) remove the data comparison, to make sure your message is shown for those scenarios as in your Rules Event / Condition (that the entity has that field). If you even don't get the message in this case, then something is really wrong with your rule (eg: you'd be using the wrong Rules Event).

Part 2 - Rules debugging needed

If the above doesn't help, I suggest you start some Rules debugging, as detailed in "How can I display the value of a variable inside a condition?", to get more details about why your rule doesn't seem to work as you'd want it to.

Part 3 - Why your data comparison cannot work

As per your additional comment "this is a multi value field": THAT pretty much explains why your rule seems to behave bizarre ... But sorry, it's rather that you're trying to make Rules do something (compare 2 values), without providing Rules all the info it needs.

If I was to show you 10 glasses of beer (each with their own label say), and I also show you another glass and ask you "is this other one the same?", then the predictable question that would come up is "as compared to which of those 10 glasses?". So that's similar to what's happening in your current rule.

How to move forward

Your Rules Event is pretty sure OK, but you're missing a crucial Rules Action: a Rules Loop. If you're not familiar with such loops, then I strongly recommend to have a look at the tutorial titled "Lists and loops".

In your case, you should add a loop related to that list of dates (which you confirmed to be a multi value field). After you do, you should iterate over each item in that list (= each date). And for each iteration you should then perform the "equivalent of the Rules Condition" you are trying to get to work, whereas you should be using the list item being processed in the current iteration step).

To be honest, I'm afraid that the above will get you closer to the complete solution, but the remaining challenge appears to be "how to specify the date value (a single one) that is to be compared with each of those date-list-items?". Correct me if I'm wrong, but your question is still not clear on that.

PS: this answer (cearly) relates to D7.


SEF URLs in Drupal 7.7? I've enabled Clean URLs which has tidied my URLs up a bit, however I need them completely rewritten for SEO purposes. For instance my 'blog' content type should be '/blog/blog-entry/' rather than 'node/etc'.

I've looked around but I can't find a stable solution for 7.7 ?
Either a module or hook function in my theme would be fine

Thanks in advance

Go get pathauto http://drupal.org/project/pathauto
With pathauto you can set up automatic path aliases to do exactly what you want. It will basically allow you to set up patterns for how to build token based paths for new pages at the time of their creation. It's one of the most widely used Drupal modules and is an absolute necessity for any site.

Also, once it's enabled and you've set up your paths the way you want them you can regenerate existing aliases in bulk at the content overview page.


Is there a way to order views grouped fields? I am using views to group a list of nodes by taxonomy term and display these groups as accordion headers (displayed by the views accordion module).

eg:

  Yellow:

node1
node2

  Green:

node1
node3
node4

  Mauve:

..

I have the nodes sorted by node:title (asc), but with or without the title sort, putting in a sort in for term:title does not seem to order the accordion headers as I had hoped. This might normally be a small niggle, but in this instance the end users are librarians...

I suppose I could go down the custom module route and devise my own block to display the terms/nodes without going through views. I would very much prefer not to do this, as it will be another maintenance demand for a quite complicated site.

The best I have found in looking for a solution is this discussion, but no solution is proposed, and I just have a nagging feeling that there must be a way to do this.

I would be really grateful for any suggestions.

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


One image style not generated UPDATE:
After investigting this I have concluded that the problem concerns ALL new image styles, but "old" ones are still working. Old ones are the built-in (e.g. thumbnail) and one image style of my own.

Also:
I use the patch to create the in core/modules/image/image.module, if it is a factor.

I have run a really strange problem: New image styles I have created don't work on one server (of course the production). I have tried to re-create the image styles, flush the caches etc ad nauseaum, but still the same thing. I have an exactly similar (apart the dimensions) image style that works just fine. The file permissions and owners are the replica of the working one...

The effect is Focal Point Scale and Crop (working dimensions 550 x 250, non working 1290 x 400). And in the development it's working just fine.

Any ideas, anyone?

wbr
hank

How large is the original image? It could be your production server php memory limit is being reached. Have you checked the error logs on the server?

Drupal needs to put the original image into memory to create the styled version so if this image is quite large it can cause memory to run out. Especially if you're on a cheap hosting


Will Drupal 8 Twig have template inheritance like Drupal 7? Drupal 7 you can style down to the fields on the page will we have this type of control with twig? I have reviewed a lot of documents about twig and didn't see anything that lets you have that same inheritance as the Drupal 7 template engine. If this is not built in to twig, is Drupal 8 going to be building it in?

I think you might be confusing inheritance with granularity. Twig actually does have the concept of template inheritance (see extends), while Drupal 7's theme engine doesn't.

The short answer is yes, you can expect the same from Drupal 8 as you did from Drupal 7. Specifically for fields, the example in the docs for field.html.twig will give you some insight:

  For example, for a field named 'body' displayed on the 'article' content type, any of the following templates will override this default implementation. The first of these templates that exists is used:

  field--node--field-foo--article.html.twig

  field--node--field-foo.html.twig

  field--node--article.html.twig

  field--field-foo.html.twig

  field--text-with-summary.html.twig

  field.html.twig

These can be altered/added to using hook_theme_suggestions_alter(), or the more specific hook_theme_suggestions_HOOK_alter().


How to make product views display also show up for Anonymous users in Drupal Commerce? I created a Product listing view with Add to Cart Buttons. The view displays perfectly for the Super User, but it is not displaying for Anonymous or Authenticated users.I do have a relationship "referenced product" but it is still not working for anonymous users.

What I did to solve the problem is to go to the permissions page and give everybody the "view all products" permission. This works. BUT: It might open up a security issue. Please let me know what am I doing wrong?

Inspired by what's written in some of the comments to issue nr 1276450, such as in comment nr 158 of it:

  edit your View: > "Advanced" > "Query settings" : check "Disable Query Rewriting"

For sure worth trying to see if it helps in your case. If it does, it'll be way better then the permission you granted as described in your question I think.


Is it safe to update a field value direclty on the Database When updating a field attached to a node, Drupal calls several hooks and add a record on the appropriate field revision. Is there any risk if I by-pass this process and update the field value via a sql query.

It is not recommended, there is a way of doing this using field_attach_update which should give you the performance benefit of not saving the whole node while using drupal api. Example:

$node = new stdClass();
$node->id = $id_value;          // node id
$node->type = $bundle_value;  // aka content type

$node->field_fieldname[LANGUAGE_NONE][0]['value'] = 'some value';
field_attach_update('node', $node);

Sources:

updating field value of a content type with query

https://www.urbaninsight.com/2011/10/24/saving-nodes-fields-without-saving-node-itself

https://api.drupal.org/api/drupal/modules%21field%21field.attach.inc/function/field_attach_update/7


Send email from non system email address using Drupal API From what should be a non-trivial task, I find this very confusing. My requirement is to send HTML email upon webform submission. Here is what I have now.

If from address is set as domain email address (info@domain.com) that is set as system's email address, set via Admin >> Configuration >> System, the email was sent as non HTML email. This is strange, because I dpm the email content before executing drupal_mail, and it shows up as properly formatted HTML. I could tolerate this for now. Here comes the trivial part.

If from address is set as non-domain email address, such as info.domain@gmail.com, the email sent, never reached the recipients, but is logged as sent (I use mail_logger module) under appropriate email key. I have checked spam folder but it is not there either.

My question is, does drupal 7 require the from email address to be that of the same domain or set as system email? (I would have expect a failed message and is logged into mail_logger)

Any suggestions would help.

This happens becouse Gmail seems to block these messages as they are often used for spoofing. Using the SMTP mailer plugin https://www.drupal.org/project/smtp and authenticating using your info.domain@gmail.com should solve the problem.


How to add Javascript in Head Tag I want to add Javascript in Head Tag. I found answer as below from this link

How to add script to <head>? , but it is not working used in tempalte.php.

function mytheme_preprocess_page(&$vars, $hook) {
    drupal_set_html_head('<script type="text/javascript" src="http://use.typekit.com/12345.js"></script>');
    $vars['head'] .= drupal_get_html_head();
}

Can we do adding Js script in head tag through page.tpl.php? or any suggestions

Here's the link to the full document on module developing aspect which I assume is not your main goal, there are some ways that you wanna skip for now, my suggestion is depending on the theme you are using, is to do it via .info file.   the easiest and common way.

This link is a very good guide for adding js files to omega subtheme, you may find it useful.

The .info file approach:

first open your theme's .info file that it should be something like YOURTHEMENAME.info

if you are using a subtheme there must be already some js files in there, you can find them and use them as an example.

what you wanna do is to add your js file like this:

scripts[] = somescript.js

this way the js file will be added to head of your website, remember after each time of editing a .info file you need to clear cache.

Adding External js to your site:

In your theme's template.php file use drupal_add_js() to the page preprocess method (or an equivalent preprocess).

function hook_preprocess_page(&$vars) {
  drupal_add_js('http://cdn.jquerytools.org/1.2.6/jquery.tools.min.js', 'external');
}

Edit: also with the extra info you just provided regarding using functions in the header you need to make a custom tpl file, locate the file that has <head> tag in your theme, it most likely be html.tpl.php (depends on the base theme you are using) if you couldnt find it you can copy it from modules/system/html.tpl.php and paste it into your theme's folder. edit the name of your file as this:
html--node--id.tpl.php like html--node--1.tpl.php and clear cache afterwards. edit the file as you wish and you must be good to go.


Adding a non-link element to the end of the breadcrumb For example, in a "blog post" page I'd like the breadcrumb to display like this:

  Blog > Recipes > Recipe

I'm controlling all breadcrumbs from a single place, a class that implements BreadcrumbBuilderInterface. Its build method looks like this:

public function build(RouteMatchInterface $route_match) {
  $b = new Breadcrumb();

  $node = $route_match->getParameter('node');

  if ($node && $node->getType() == 'blog_post') {
    $b->addLink(Link::createFromRoute($this->t('Blog'), 'blog.home'));
    $b->addLink(Link::createFromRoute($this->t('Recipes'), 'blog.recipes_landing'));

    //I want this next item to not be a link, and to show "Recipe" and not the node title.
    //$b->addLink(Link::createFromRoute($this->t('Recipe'), 'nothing!'));
  }

  return $b;
}

How can I make this happen? I saw somewhere (not sure where, in a code comment perhaps) that this last item is supposed to be added in the theme layer, but I don't want to split my logic, especially since I don't just want all breadcrumbs to show the page title as the last item (instead, for example, I want it to say "Recipe" if the content type is blog_post).

You can do almost like in your suggestion. You just need to use '<none>' instead of 'nothing!'.

$b->addLink(Link::createFromRoute($this->t('Recipe'), '<none>'));


Views block element with Panels viewes I have a content type foo, that has a media field and a body with text. I want to list the most resent foo on  whit a specific visualization: double column layout for a foo that has media which is previewed left and on the right is a summery of the body. If there is no media then simply show the summary of the body.

I can create a block bar in Views module, that list all the foo and show this block on .
I can create a Node template of type foo with Panels module that has the required layout but I don't know how to apply that on the list of foos in bar.

Do I need to use in Panels Node template?
My selection rule is: This panel will be selected if NOT (media is set to ""), and Current path is "front". (not working).

If you use a special layout only here, maybe the display suite module is enough for you.
The main part of the solution is you have to create a view mode for the node, that you will use to display a media/description in the views.
You have to set the proper layout here, so something 50/50 and the two fields. If you are done with this new view mode, you have to go into the views. In the Format section you will see the Show line there you have to change from Field to Content. If you set the Content you will see a second column which is listing the available view modes for your content, here you need to select the recently created view mode.


How to publish in an organization with hierarchy? My Drupal experience is limited to a single site with custom content types and standard roles. Please take a look at the use case below, involving content being routed through multiple organizational levels, so there is consolidation at each level and some content being "highlighted" for the next higher level.

My company has weekly activity reports. Each member submits an activity report and then the team lead chooses a few to be submitted to our section manager. Then our section manager chooses a few (from multiple teams) to be submitted to our division manager. Then our division chooses a few (from multiple sections) to be submitted to our top level manager.

What stuff should I look into to accomplish content going through different levels like this?

Have a look at the Group module (commonly perceived as an alternative for Organic Groups).

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. The Group module creates groups as entities, making them fully fieldable, extensible and exportable. Which also makes it integrate very well (out of the box) with commonly used modules such as Rules, Views, etc.

Some more questions you may want to look at for more details:

What are the various roles supported by the Group module?, which explains the various types of roles that can be used.
How to bulk assign existing content to a group created with the Group module?, a typical issue when adding this module to an existing site.
What are the features of the Group module versus Organic Group module?

Sample configuration

Below is an example of a possible configuration, which may help to get you started with possible configurations (using the Group module):

Group type ID ! Group type ! Group role ID ! Role
--------------+------------+---------------+------------
 1            ! Class      ! 3             ! Instructor
 1            ! Class      ! 4             ! Student
 2            ! Customers  ! 5             ! Lead
 2            ! Customers  ! 6             ! Prospect
 2            ! Customers  ! 7             ! Licensed Customer
 2            ! Customers  ! 8             ! Sales
 2            ! Customers  ! 9             ! Support
 2            ! Customers  ! 10            ! Accounting
 2            ! Customers  ! 11            ! R&D
 3            ! Project    ! 12            ! Project Manager
 3            ! Project    ! 13            ! Developer
 3            ! Project    ! 14            ! Customer

Group Types

The above example consists of 3 group types:

Class.
Customers.
Project.

Group Roles

For each of the 3 group types, there are specific Roles defined, some more details about some of them:

for the Class group, these are the 2 roles that are configured:

Instructor.
Student.

for the Project group, these are the 3 roles that are configured:

Project Manager.
Developer.
Customer.

These are the Group Specific Roles: these roles can be configured per group type and will only be available on groups of that group type. As an example, for group type "Class", the defined roles are Instructor and Student (which are not available for the other group types.

On top of the group specific roles, there are also Special Global Roles: These are the special (hardcoded) roles named Outsider (= a signed in user that did not join a group) and Member  (= a signed in user that did join a group). These cannot be defined by the Drupal administrator, and they are always available for any group. These roles can have different permissions sets for each group type. Special case: the role Anonymous is related to a user that is not signed.

Groups

Each of the configured group types can have any number of Groups.

Examples of groups:

for the Class group type, there could be these Groups:

Getting started with Drupal.
Drupal for site builders.
Become an expert in using the Rules module.

for the Customers group type, there could be these Groups:

Service Requests.
Order Processing.
Sales Orders.
Relationship Management.

Permissions

For each of the configured group types, you can then also configure for each Content Type which Role has what kind of access (= none, view, create, edit, delete). Be aware: even though this looks similar to Drupal's permission configuration, these permissions are not the same permissions (they are specific to the Group module).

Your usecase

In your case, your challenge seems to be about this:

  ... content going through different levels like this?

Translated to an implementation using the Group module, it seems to me that all that's needed is to assign, and later on re-assign, each node (content) to an appropriate group. Whereas you use appropriate group permissions/roles to accutally perform these assignments.

And for the required group types to be configured, I'd start with these specific group types:

Teams (with groups Team T1, Team T2, ..., Team Tn).
Sections (with groups Section Sa, Section Sb, ..., Section Sx).
Devisions (with groups DevX, DevY, DevZ).

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".


How do I add custom template files? Currently, I am using the following code.

/**
 * Implements hook_theme_registry_alter().
 */
function MY_MODULE_theme_registry_alter(&$theme_registry) {
  // Defined path to current module.
  $is_admin = Drupal::service('router.admin_context')->isAdminRoute();
  $node = \Drupal::routeMatch()->getParameter('node');
  if (isset($node)) {
    if ($node->getType() == 'MY_CONTENT_TYPE' && $is_admin == 0) {
      $module_path = drupal_get_path('module', 'reveal_js');
       $theme_registry['html']['path'] = $module_path . '/templates';
       $theme_registry['page']['path'] = $module_path . '/templates';
    }
  }
}

This works, but when going to another page, I have to rebuild cache in order for it to re-evaluate whether the node is 'MY_CONTENT_TYPE' or a different type.

It looks like hook_theme_registry_alter() is only executed when the theme cache is rebuilt. This means that what you need to do is use one of the theme_suggestion_alter hooks, such as hook_theme_suggestions_alter() or hook_theme_suggestions_node_alter(). These get run for each page before it is cached, I believe, instead of only once on cache rebuild.

So, what you want to do in your module is create a theme implementation using hook_theme(). That would look something like this:

function MYMODULE_theme($existing, $type, $theme, $path) {
  return array(
    'my_theme_implementation' => array(
      'path' => drupal_get_path('module', 'reveal_js') . '/templates',
      'template' => 'my_theme_implementation',
    ),
  );
}

And then your hook_theme_suggestions_node_alter() would be something like

function MYMODULE_theme_suggestions_node_alter(&$suggestions, $variables) {
  $is_admin = Drupal::service('router.admin_context')->isAdminRoute();
  $node = $variables['elements']['#node']
  if ($node->getType() == 'MY_CONTENT_TYPE' && $is_admin == 0) {
    $suggestions[] = 'my_theme_implementation';
  }
}

Does that all make sense?


How do I create a Url object from the public file URI? How can a Url object be created from a file URI? Using the URI for a public file as a parameter for Url::fromUri() gives this error.

  UnexpectedValueException: External URLs do not have internal route parameters. in Drupal\Core\Url->getRouteParameters().

$file = File::load($file_id);
$file_uri = $file->getFileUri();
$menu_link['url'] = Url::fromUri($file_uri);

Here is the class and method in question:
https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Url.php/function/Url%3A%3AfromUri/8.2.x

Note that I don't need to get the actual URL in string format, I need to generate a Url object from the Url class that points to a file. This is because I am attempting to modify the path of a menu link and unfortunately that is not a simple matter of providing a URL string in Drupal 8.

This is the code I am using.

function teeprop_preprocess_menu__main(&$vars) {
  foreach($vars['items'] as $key => $menu_link) {
    if (!empty($menu_link['url']->getRouteParameters())) {
      $node_id = $menu_link['url']->getRouteParameters()['node'];
      $node_entity = Node::load($node_id);
      $node_type = $node_entity->getType();

      if ($node_type == 'pdf') {
        $file_id = $node_entity->get('field_pdf_file')->getValue()[0]['target_id'];
        $file = File::load($file_id);
//         $file_url = $file->url();
        $file_uri = $file->getFileUri();
        $vars['items'][$key]['url'] = Url::fromUri($file_uri, ['absolute' => TRUE]);
      }
    }
  }
}

I believe that the following should do what you need:

Url::fromUri(
  File::load(1)->url()
);

(I've tested this in a local 8.4.2 installation, and it yields a Url object that can be rendered without an error.)

The functions are admittedly named very misleadingly. Even though ::fromUri() sounds like it should accept the return value of ::getFileUri(), namely public://..., it actually only accepts internal:, base:, entity: and "external" URLs.

So you need to use ->url() to get the external URL of the file, and then pass that to ::fromUri().