Programatically retrieve a block and print it in a page

I'm not sure on which page you want to print the block. This is an example that prints the block in a custom page.

/**
 * Implements hook_menu().
 */
function mymodule_menu() {
  $items = array();
  $items['my/page/path'] = array(
    'title' => 'Block in A Page',
    'page callback' => 'mymodule_block_page',
    'access callback' => TRUE,
  );

  return $items;
}

/**
 * The page callback which display the block
 */
function mymodule_block_page(){
  $block = module_invoke($module_name, 'block_view', $delta);

  return $block['content'];
}

hook_menu() registers a menu path which will display the block. mymodule_block_page() is invoked when the menu path is accessed like http://example.com/my/page/path.

module_invoke($module_name, 'block_view', $delta); will return the block ready to render. Please find out the module name and delta. I guess $module_name would be webform. If you go to the block configuration, e.g. admin/structure/block/manage/comment/recent/configure, the module name is comment and the delta is recent.

If you want to print the block on every page except the front page, create a variable in hook_preprocess_page() of template.php.

function MYTHEME_preprocess_page(&$variables) {
  if (!drupal_is_front_page()) {
    // It is not the front page.
    $block = block_load('module_name', 'block-delta');
    $variables['myblock'] = _block_get_renderable_array(_block_render_blocks(array($block)));
  }
}

In page.tpl.php, you can place the following code snippet where you want.

<?php if (isset($myblock)): ?>
  <?php print render($myblock); ?>
<?php endif; ?>


How to copy blocks placement and settings between themes?

I changed a little bit the code and it worked:

Before running this code you should be sure that both themes have the same regions and, if needed you will have to create the missing regionsin the new theme.

DELETE FROM block WHERE theme = 'NEW-THEME'

INSERT INTO block (module, delta, theme, status, weight, region, custom, visibility, pages, title, cache, i18n_mode) (SELECT module, delta, 'NEW-THEME', status, weight, region, custom, visibility, pages, title, cache, i18n_mode FROM block WHERE theme = 'OLD-THEME')


Gmap cluster different marker types seperatly

The Comparison of mapping modules includes this:

GMap is considered a legacy module.

So maybe you want to have a look at the IP Geolocation Views & Maps module. Partial quote from its project page:

Despite what the name may suggest, IP Geolocation Views & Maps (IPGV&M) is first and foremost a mapping engine.
The module makes it very easy to create Views-based mapping solutions using the map renderer of your choice (Google, OpenLayers or Leaflet) with any location storage module of your choice, e.g.:

Get Locations,
Geofield,
Geolocation Field
Location.

This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
Like beautiful animated marker clustering on Google or Bing or Mapbox ... any of various map providers.
But more importantly IPGV&M adds some features you won't find as conveniently packaged elsewhere.
These include marker differentiation based on field values or ranges (2nd screenshot) with or without font icons, various centering options, super-imposing the current visitor's location, allowing multiple content types to be displayed on the same map, full screen button and mini-map inset (bottom screenshot), polygon support (Geofield), marker tags and tool tips and cross-highlighting of associated content on the page when markers are hovered (and vice versa).

Head over to its (impressive) project page for even more information about it (it would be way too long to include a quote of it all here). That project page also includes various screenshots.


I had came to this thread as we also require this feature. Could not find a satisfactory solution anywhere. Prepared a patch for views module and submitted at https://www.drupal.org/project/drupal/issues/3156711#comment-13732219
Posting here as somebody might find it useful.


How to hide block while field in database is empty?

Part 1: Install the Rules block visibility module (and Rules)

You should be able to get this to work using 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've reduced your question to making Rules intercept the value of your field video (i.e. if it is empty or not).

Part 2: Create 2 appropriate Rules Components

The Rules block visibility module doesn't have a lot of documentation, except in the README.txt that comes with this module. Here is what the crucial part of it is (to get the idea):

  Configuration is done on a per-block basis. To control a block
  visibility using a rule component, go to the block settings page,
  scroll down to the "Rules" tab, and select the Rules component that
  you want to use.

  Notice that to be able to be used by this module, a Rules component
  must be constructed in a very specific way. See the next section for
  more information.

This module comes with 2 sample Rules Components, that should help to understand its concept.

By looking at these samples, I was able to create another Rules Component which looks like so:

{ "rules_block_visibility_hide_block_for_user_1" : {
    "LABEL" : "Hide block for user 1",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "IF" : [
      { "NOT data_is" : { "data" : [ "site:current-user:uid" ], "value" : "1" } }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

You should be able to import this rule in your own environment.

What this Rules Component does is "only" return a boolean (1 or 0), based on the condition if the user's uid is YES or NO equal to 1.

With that, we're coming close to an actual answer to your question: create 2 such Rules Components (1 for your block 1, and 1 for your block 2). And within each of those 2 Rules components, you only have to adapt the Rules Condition (as compared to my sample Rules Component here, apart probably from its machine name or so):

Rule 1 (which will be used to manage the visibility of Block 1) should have a condition like "field video is NOT empty".
Rule 2 (which will be used to manage the visibility of Block 2) should have a condition like "field video is empty".

Part 3: Set Block Visibility using the Rules Component

Head over to the "Block" settings for each of your 2 blocks. At the bottom of its settings, within the typical "Visibility settings", there is now (after you enabled the Rules block visibility module as in Part 1) an extra tab labeled "Rules". Using that tab will allow you to select a "Rules Component" that will do what's documented below that selection list field, ie: "Show this block only if the selected rule returns a positive value. Important: to be listed here, a block visibility rule must have specific parameters and return values.".

Obviously, all you have to do is select Rule 1 for Block 1, and Rule 2 for Block 2.

Note: it doesn't matter what type of block it is (created by a view, or something else), it works in all cases.


Open Menu Link In New Browser Tab/Window

Doing a review of how \Drupal\system\Controller\SystemController::overview builds an Admin Overview page and I found that template_preprocess_admin_block_content was only constructing each link item as an array values that did not include a URL object. While menus built by the admin Toolbar did. The importance of the URL (Drupal\Core\Url) instance being generated is that it includes an Attributes (Drupal\Core\Template\Attribute) instance that Twig can use to render an item's HTML attributes.

The fix:

The template_preprocess_admin_block_content function can be located in a custom module but, there is the requirement to add an overriding template file in the admin theme so it is best to locate the function a custom admin theme. (It is important that you remember the difference between your front-end theme and your admin theme as they are not the same)

/themes/myadmintheme/myadmintheme.theme

/**
 * Implements template_preprocess_admin_block_content().
 */
function myadmintheme_preprocess_admin_block_content(&$variables) {
  if (!empty($variables['content'])) {
    foreach ($variables['content'] as $key => $item) {
      $variables['content'][$key]['attributes'] = new Attribute(empty($item['options']['attributes']) ? array() : $item['options']['attributes']);
    }
  }
}

/themes/myadmintheme/templates/admin-block-content.html.twig

{#
/**
 * @file
 * My admin theme implementation for the content of an administrative block.
 *
 * Uses unordered list markup in both compact and extended modes.
 *
 * Available variables:
 * - content: List of administrative menu items. Each menu item contains:
 *   - url: Path to the admin section.
 *   - title: Short name of the section.
 *   - description: Description of the administrative menu item.
 *   - attributes: HTML attributes of the administrative menu item.
 * - attributes: HTML attributes to be added to the element.
 * - compact: Boolean indicating whether compact mode is turned on or not.
 *
 * @see template_preprocess_admin_block_content()
 * @see seven_preprocess_admin_block_content()
 * @see myadmintheme_preprocess_admin_block_content()
 */
#}
{%
  set classes = [
    'admin-list',
    compact ? 'compact',
  ]
%}
{% if content %}

    {% for item in content %}

{{ item.title }}
{{ item.description }}

    {% endfor %}

{% endif %}

In the example code here the theme My Admin Theme (/themes/myadmintheme) is a child theme of Drupal's default admin theme Seven.


Problems while migrating drupal website from localhost to server

To avoid requiring ?q=user or ?q=some/page/path you should assure ModRewrite is enabled on your Apache webserver. If you're on shared hosting you made need to ask your host provider to enable this module of Apache.
Moving a Drupal site is essentially moving all the PHP + MySQL data from 1 computer to another. Pick you're tools: mysqldump + zip, rsync, scp, ftp ... Drush whatever ... but the procedure is essentially the same -- move everything in it's entirety.

Why you have 2 less tables between your Drupal installs is unfortunately simply bad project management on your behalf -- good luck tracking down the differences.

Comparing drush pm-list between the 2 Drupal installs should help to find any modules on 1 system and not on the other. I like using drush archive-dump and drush archive-restore to move Drupal sites around -- but under your time constraint I recommend using SQL migration tools and code migration tools your comfortable and most familiar with.


Print all the pages in the same level in a book

This should work out of the box if you add the book navigation block to a region.

EDIT:

Sorry, I didn't realise that I was on on of the book pages so the book block expands in this case but not on non book pages. The way around this is to use Menu Block and create a menu block that starts at your About Us. Make sure you go into the advanced options of the menu block and select Expand all children of this tree.


Modifying a views organic groups exposed filter

It would seem to me that you would want to modify that filter in the Views UI. Is required checked? Also, a standard practice that I've seen for Drupal select is having all actually keyed with _none rather than ALL.


Having problems with OpenLayers in Drupal 7

The errors you are seeing, are mostly harmless. PHP on your server is configured to be very strict, which is a good thing, and the Openlayers have previously not been very strict about the coding standards.

I haven't looked specifically at the errors you are seeing, but when I've seen similar issues, I've almost always found the problem fixed in the dev version.

As no-one is actively maintaining the module, there is not likely going to be  a new release any time soon. You're best option is probably to try dev, and report the issue if that doesn't help.

The ugly workaround is to turn down strictness on the error reporting on your php install.

You can also give the less feature rich but newer Leaflet module a try.


How can I have different templates for newly created content?

Here's one way to solve this. In a nutshell:

Create a custom view for your entity using Display Suite or Entity View Modes.  Display Suite is preferred, as it allows you to also create custom fields and custom layouts for your entity display. This is the custom view your authors will see when they submit the entity create form.
Alter the entity creation form and add a new submit handler (be sure not to delete the default submit handler, as that will take care of creating and saving the entity before your custom handler is called).
In the new submit handler, create a form_state['redirect'] to a custom menu item
Create a custom menu item (with hook_menu) that will load your entity and pass it to a page callback
The page callback will build and return the entity custom view you defined in step 1.

Here's the code for all this (except step 1). PLEASE NOTE: since I don't know what custom entity you are using, this example uses Basic page node (content) type. You will need to adapt to your custom entity. All this code goes in a custom module called my_custom_view.module.

Also note: the custom view I created in Display Suite is called custom (see node_view() in the page callback).

<?php

function my_custom_view_form_page_node_form_alter(&$form, $form_state, $form_id) {
  $form['actions']['submit']['#submit'][] = 'my_custom_view_form_submit';
}

function my_custom_view_form_submit($form, &$form_state) {
  $form_state['redirect'] = 'custom-node-view/'.$form_state['nid'];
}

function my_custom_view_menu() {
  $item = array();
  $item['custom-node-view/%node'] = array(
    'page callback' => 'my_custom_view_page',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
  );
  return $item;
}

function my_custom_view_page($node) {
  return node_view($node, 'custom');
}


PDOException Error upon saving node with computed field

I encountered a similar error on my current project and fixed it by adjusting the size of the related field.

Try using PhpMyAdmin to view the 'field_computed_label_value' table and then select the structure tab.  It will list the type as varchar(###) where ### = the character limit for the string.

Try increasing the size of the type for the field value by selecting the 'change' icon for the value row and then adjusting its length.

Remember to back-up before trying this in case it does not solve our problem.


How to call php snippet which is save as basic page?

I think you should use hook_menu to define the path the drupal way and rewrite your form using drupal FAPI. This gives you a clean system.


Show metatags on node add/edit pages on custom theme

Actually it was related to Bootstrap custom theme and vertical tabs. So fields where only hidden in my theme and it was a style issue. Nothing to do with privileges.


Clear (not reset) Views Exposed Filter Values

I'm pretty sure that the better exposed filters module has an option for a reset button, but it may reset the view too.

You could also add some javascript that listens for the click event on the button and resets the fields you want.


The "needs a higher bootstrap level" error means that you're not in the right directory to call drush.

Where's your drupal source directory ? cd to that directory , and try your drush command again...


Sending email notification based on flagged node being linked via entity reference

I found the answer to this, or at least, a way to do this. In a custom.module:

Firstly, this checks if something is required to happen (creating a 'blogpost'), and if so, then gets the NID of the item the user is following (e.g. field_linked_item).

function custom_node_presave($node) {
if ($node->type == 'blogpost' && $node->is_new) {
    $linked_node_nid = $node->field_linked_item['und'][0]['target_id'];
    if ($linked_node_nid) {
      $emails = custom_get_blog_follower_emails($linked_node_nid);
      if ($emails) {
        custom_schedule_mass_email($linked_node_nid, implode(',', $emails), 'email_blog_post_linked');
      }
    }
  }
}

This function gets the email address for all users who flagged the blog that is linked to this blogpost (via linked_item) and returns the list to the function above:

function custom_get_blog_follower_emails($nid) {
  $query = db_select('flagging', 'fc');
  $query->join('users', 'u', 'fc.uid = u.uid');
  $query->join('flagging', 'fc2', 'fc2.entity_id=fc.entity_id AND o.entity_type=\'node\' AND fc2.fid=5');
  $query->leftJoin('field_data_field_opt_out', 'o', 'o.entity_id=u.uid AND o.entity_type=\'user\' AND o.deleted=0');
  $or = db_or();
  $or->condition('o.field_opt_out_value', 0);
  $or->condition('o.field_opt_out_value', NULL);
  $result = $query
    ->fields('u', array('mail'))
    ->condition('fc.entity_type', 'node')
    ->condition('fc.entity_id', $nid)
    ->condition('fc.fid', 4)
    ->condition('u.status', 1)
    ->condition($or)
    ->orderBy('fc.timestamp', 'DESC')
    ->execute()
    ->fetchCol();
  return $result;
}

If email addresses are found by the function above, the original function then uses this to send emails via a pre-created rules message:

function custom_schedule_mass_email($nid, $to, $action) {
  $state = new RulesState();
  $state->addVariable('nid', $nid, array('type' => 'integer'));
  $state->addVariable('to', $to, array('type' => 'text'));
  $task = array(
    'identifier' => 'custom_' . $action . '_' . $nid,
    'date' => time(),
    'config' => 'rules_' . $action,
    'state' => $state,
  );
  rules_scheduler_schedule_task($task);
}

You need to create a rule to accept the 'to' and 'nid' (nid in my use is to allow rules to get some information about that post). In my case, the rule is called 'email_blog_post_linked'.

This is pretty specific to my requirements, but hopefully it will point people in the right direction.


Submit button calling wrong submit handler

Drupal uses the name and value of submit buttons to identify which was pressed, and subsequently which submit handlers to run. If the names and values of all three buttons are the same, the FAPI will only be able to use one of them (in this case the last one).

To fix it you can assign a unique #name property to each of the buttons.


Is it possible to use a Display Suite Code Field in Views?

Instead of using Views fields, just use the Content -> Display Suite view modes in the view, that way you can just render the DS view mode with the custom field of the returned nodes in views.


How can I change the Add to Cart button text on specific product forms?

Take help of hook_form_alter. Get the ID of the form for the product display where you are trying to change the text & do something like this --

function MYMODULE_form_alter(&$form, &$form_state, $form_id){//replace your module name with MYMODULE
  if(strpos($form_id, 'commerce-cart-add-to-cart-form-65') !== false){//my form ID is "commerce-cart-add-to-cart-form-65", replace it with your form ID.
    $form['submit']['#value'] = t('Check Out');//Put the text which you want to make appear instead of "Add to cart".
  }
}

I also have several product display with custom text for "Add to cart". It took some time for me figure out the easy way. Have Fun :)


I need to display a different link for anonymous users and register users for same content

In build > elements you will need to create 2 html markup or Advanced HTML/Text elements

Each one will have the links mentioned

There is a setting access that you can choose who has access to it

For the other link you can choose anonymous

For one of the elements you will choose authenticated

If this solution is not satisfactory 100% you will need to override webform


Integrating websockets server to the database

First, Drupal (PHP) makes a lousy websocket server (it’s completely engineered the other way around for it) with php 8 we are getting closer but that’s out of scope for drupal.
But Drupal services (with possibly a JWT or openID Connect endpoint) seems like the best path forwards.
(That would be a variant of option 3)


Unable to debug $items variable in hook_menu_alter(&$items)

It is not working because hook_menu() and hook_menu_alter() are invoked when the menu list is rebuild. This generally happens when a module is installed, or uninstalled, but modules can force the menu to be rebuild setting a Drupal variable, as with the following code:

variable_set('menu_rebuild_needed', TRUE);

When hook_menu_alter() is invoked, Drupal could also not serving a page that is visible on the browser. The function that rebuilds the menu, menu_get_tem(), is called by menu_execute_active_handler(), which is called every time Drupal bootstrap, even when an AJAX callback is invoked. In that case, the output of the debug function is not visible (nor would JavaScript get it).

In such cases, I think it is preferable to write the output to the database using watchdog(). The output is not immediately visible, but will be logged even when an AJAX callback is invoked.


You can turn them off in "Global: Custom Text" field setting. Just check the "Customize field HTML" and "Customize field and label wrapper HTML", and set both elements to "None" in "Style Settings". See below screenshot for details.


After rearranging field order in a view, how do I export this modification in features?

I found out there was no component to add to the feature: the modification was already there even if the feature status didn't change.
The field order is stored into the file: 'feature_name.views_default.inc'.  In order to update the file with the modification, the feature must be 'generated'. (Go to feature --> recreate--> advanced options --> generate feature)


How to create popup for email link with major email provider links?

First take a look here. Lots of JQuery plugins that integrate with Drupal.

I think Lightbox best fit here but check the rest. It provides a pop-up overlay similar to Craigslist's

I myself don't have any experience with these but since no one has answered thought I could try point you somewhere useful.

I did a quick search and also found these that could lead somewhere:

http://www.lullabot.com/articles/announcing-beautytips-jquery-tooltip-plugin
http://www.jquerypopup.com/

Anyway, I hope those hints helps you in some way.


Did you gave node type ? Try the following body data.

{
 "data":
  {
     "attributes": {
            "title": "title of your new node",

        },
         "relationships": {
            "field_body": {
                "data": {
                    "type": "paragraph--text",
                    "id": "b0247bf8-a3c0-4a45-8e05-4f4901011000"
                }
            }
        },
      "type": "node--yournode"
    }
  }


Converting existing autocomplete field to custom Drupal field

I ended up solving this by using hook_menu() to create an AJAX tie-in with a custom callback function and then tied the form field to the AJAX path with 'autocomplete path' => '/...' in the field parameters. No need for any custom JS to make it work.


How to establish a relation among two content types in drupal 7

It looks like you need Entity reference module:

  Provides a field type that can reference arbitrary entities

Just add product reference to review content type.


"I fixed the issue by setting the bandwidth optimization to: Aggregate and compress CSS files." said kine456.
kine456 answered his own question.

This is because js files like respond.js that comes with the zen theme must get applied after you aggregate the css files for it to look correctly in ie8. I'm pretty sure its documented in the theme's readme.


How do I prevent a "Page not found" error for URLs containing non-Latin characters?

Consider trying the Transliteration module. Here is a quote from its project page:

  ... it takes Unicode text and tries to represent it in US-ASCII characters (universally displayable, unaccented characters) by attempting to transliterate the pronunciation expressed by the text in some other writing system to Roman letters.

As a sample, it transforms an URL like mydomain.com/последние-новости-в-Украине-и-мире in something like mydoamin/poslednie-novosti-v-Ukraine-i-mire.

Other modules that might help to solve this question:

Global Redirect.
Pathauto.


How to get rid of empty blocks on the dashboard?

I think this is a long-standing issue with dashboard blocks. See the discussion, and several patches, here: https://drupal.org/node/936798

I haven't tried any of these patches myself.

If you just want to get rid of the error, I believe you can delete inactive blocks in the database directly, as described here: https://drupal.org/node/1202500

The gist is that you look for and remove blocks in the block table where region = dashboard_inactive


You probably can't get 100% exactly what you want but you can get very close.  The problem is that we don't have a definitive history of the order in which revisions were created or edited.  You may be able to make some assumptions if, for example, you know that you always force the creation of a new revision any time an edit is made, but I don't know enough of your business logic to speak to that.  Regardless, I can get you most of the way there and build a view that shows nodes that currently have a title that differs from other revisions of the same node.

In my solution, you can end up with the following fields (amongst others):

Current Title
Previous title
Date previously-titled-revision was last updated
Date currently-titled revision was last updated

First, create a view based on Node Revisions.

When you do this I believe your view will, by default, have a relationship to the node table based on the vid.  It will be called "Content revision: Content".  You want to remove this.  There's another, identically named relationship that you actually want to add instead; it has a description that reads "Content revision: Content, The revision NID of the content revision."  Add that relationship.

After doing this you may find that you need to click on and re-save the settings for the "status" filter on the view as it will be set to use the old relationship. Or, if you want to see all nodes (even those that are un-published) just remove this filter entirely.

Now, add 2 fields to your view:

Content Revision: Title -- this one probably already exists as it's added by default.  This is the title of the revision and can be considered "previous title" for your use-case.
Content: Title (this will use the relationship we just created) -- this is the title of whatever the "current" revision of the node is.  This can be considered "current title" for your use-case.

At this point, you should be seeing a list of all revisions of all nodes, regardless of whether the title has ever changed.  To limit the view to only show those where the title has changed we need to add a new filter called Global: Fields comparison.  Configure the filter such that the "Left Field" is set to "Content revision: Title" and the "Right Field" is set to "Content: Title".  Set the operator to "is not equal to".

Your view should now be more-or-less what you're looking for.  Feel free to add the appropriate date fields, though none of them will be able to tell you exactly when the title itself was changed, per se.

Also note that this will give you one row per different title a node has ever had.  So there may be multiple rows per node.


override variable in template.php with variable from module_preproccess_node

If I am understanding/reverse engineering your question correctly, in your module, you can do something like this:

function YOURMODULE_preprocess_node(&$variables) {

  if ( // whatever logic ) {

    $colors = array('blue', 'red', 'green');
    $variables['group']['color'] = $colors;
    $variables['size'] = 'regular';

  }

}

This will create variables that can be accessed inside node.tpl.php and its variants.

In template.php you can then do something like this:

function YOURTHEME_preprocess_node(&$variables) {

  if (!isset($variables['size'])) {
    $variables['size'] = 'double';
  }

  if (!isset($variables['group']['color'])) {
    $colors = array('black', 'white');
    $variables['group']['color'] = $colors;
  }

}

which will set them to your defaults if they haven't already been set.

Then you can do whatever you want with them in node.tpl.php.


How to redirect the user to a specific page after node is added/edited by user

You can use the Rules module to do that. If you haven't used it before you can take a look at this video tutorial.


Alter webform messages found in WebformMessageManager

The beauty about Services is that they can be overridden to your liking.

So all we have to do is extend the WebformMessageManager so we inherit all of it's properties and methods and simply alter the method you need to modify.

my_module/src/CustomWebformMessageManager.php

<?php

namespace Drupal\my_module;

use Drupal\webform\WebformMessageManager;
use Drupal\webform\WebformMessageManagerInterface;

class CustomWebformMessageManager extends WebformMessageManager implements WebformMessageManagerInterface {

  /**
   * {@inheritdoc}
   */
  public function get($key) {
    // Get custom message from settings.
    if ($custom_message = $this->getCustomMessage($key)) {
      return $custom_message;
    }

    $webform = $this->webform;
    $source_entity = $this->sourceEntity;

    // Get custom message from settings with arguments.
    switch ($key) {
      case WebformMessageManagerInterface::PREVIOUS_SUBMISSION:
        $webform_submission = $this->entityStorage->getLastSubmission($webform, $source_entity, $this->currentUser);
        $args = [':href' => $this->requestHandler->getUrl($webform_submission, $source_entity, 'webform.user.submission')->toString()];
        return $this->getCustomMessage('previous_submission_message', $args);

      case WebformMessageManagerInterface::PREVIOUS_SUBMISSIONS:
        $args = [':href' => $this->requestHandler->getUrl($webform, $source_entity, 'webform.user.submissions')->toString()];
        return $this->getCustomMessage('previous_submissions_message', $args);
    }

    // Get hard-coded messages.
    switch ($key) {
      case WebformMessageManagerInterface::ADMIN_PAGE:
        return $this->t('Only webform administrators are allowed to access this page and create new submissions.');

      case WebformMessageManagerInterface::ADMIN_CLOSED:
        $t_args = [':href' => $webform->toUrl('settings-form')->toString()];
        return $this->t('This webform is closed. Only submission administrators are allowed to access this webform and create new submissions.', $t_args);

      case WebformMessageManagerInterface::ADMIN_ARCHIVED:
        $t_args = [':href' => $webform->toUrl('settings')->toString()];
        return $this->t('This webform is archived. Only submission administrators are allowed to access this webform and create new submissions.', $t_args);

      case WebformMessageManagerInterface::SUBMISSION_DEFAULT_CONFIRMATION:
        $t_args = ['%form' => ($source_entity) ? $source_entity->label() : $webform->label()];
        return $this->t('New submission added to %form.', $t_args);

      case WebformMessageManagerInterface::FORM_SAVE_EXCEPTION:
        $t_args = [
          ':handlers_href' => $webform->toUrl('handlers')->toString(),
          ':settings_href' => $webform->toUrl('settings')->toString(),
        ];
        return $this->t('This webform is currently not saving any submitted data. Please enable the saving of results or add a submission handler to the webform.', $t_args);

      case WebformMessageManagerInterface::HANDLER_SUBMISSION_REQUIRED:
        $t_args = [':href' => $webform->toUrl('handlers')->toString()];
        return $this->t('This webform\'s submission handlers requires submissions to be saved to the database.', $t_args);

      case WebformMessageManagerInterface::DRAFT_PREVIOUS:
        $webform_draft = $this->entityStorage->loadDraft($webform, $source_entity, $this->currentUser);
        $t_args = [':href' => $webform_draft->getTokenUrl()->toString()];
        return $this->t('You have a pending draft for this webform.') . ' ' . $this->t('Load your pending draft.', $t_args);
      case WebformMessageManagerInterface::DRAFTS_PREVIOUS:
        $t_args = [':href' => $this->requestHandler->getUrl($webform, $source_entity, 'webform.user.drafts')->toString()];
// ALTER THE LINE YOU WANT
        return $this->t('MY CUSTOM VIEW PENDING DRAFT MESSAGE.') . ' ' . $this->t('MY CUSTOM VIEW PENDING DRAFT MESSAGE..', $t_args);

      case WebformMessageManagerInterface::SUBMISSION_UPDATED:
        $t_args = ['%form' => ($source_entity) ? $source_entity->label() : $webform->label()];
        return $this->t('Submission updated in %form.', $t_args);

      case WebformMessageManagerInterface::SUBMISSION_TEST:
        return $this->t("The below webform has been prepopulated with custom/random test data. When submitted, this information will still be saved and/or sent to designated recipients.");

      case WebformMessageManagerInterface::TEMPLATE_PREVIEW:
        $t_args = [':href' => $webform->toUrl('duplicate-form')->toString()];
        return $this->t('You are previewing the below template, which can be used to create a new webform. Submitted data will be ignored.', $t_args);

      case WebformMessageManagerInterface::PREPOPULATE_SOURCE_ENTITY_TYPE:
      case WebformMessageManagerInterface::PREPOPULATE_SOURCE_ENTITY_REQUIRED:
        return $this->t('This webform is not available. Please contact the site administrator.');

      case WebformMessageManagerInterface::PREVIOUS_SUBMISSION:
        $webform_submission = $this->entityStorage->getLastSubmission($webform, $source_entity, $this->currentUser);
        $args = [':href' => $this->requestHandler->getUrl($webform_submission, $source_entity, 'webform.user.submission')->toString()];
        return $this->getCustomMessage('previous_submission_message', $args);

      case WebformMessageManagerInterface::PREVIOUS_SUBMISSIONS:
        $args = [':href' => $this->requestHandler->getUrl($webform, $source_entity, 'webform.user.submissions')->toString()];
        return $this->getCustomMessage('previous_submissions_message', $args);
    }

    return FALSE;
  }

}

my_module/my_module.services.yml

services:
  webform.message_manager: # The service ID you want to alter
    class: Drupal\my_module\CustomWebformMessageManager // Your Custom Class
    arguments: ['@current_user', '@config.factory', '@entity_type.manager', '@logger.channel.webform', '@renderer', '@messenger', '@webform.request', '@webform.token_manager']

  Important: Make sure you give your module a higher weight
  than webform so your service alter runs.

You could use the Modules weight module.

OR

In Devel's execute php, execute module_set_weight('my_module', 10);


Keep submenu expanded when parent or children are active

Menu Trail By Path sets the active-trail on menu items according to the current url.

For example if you are at yoursite.com/blog/category1/article1
Menu Items with these paths will get the active-trail class on them and expand accordingly.

blog
blog/category1
blog/category1/article1

This is particularly useful if you want a lot of nodes to appear as children of certain nodes / taxonomy term / views / referenced nodes / etc, but do not want to add them all to the menu. eg. hundreds of blog articles.


How do I add a super admin, either programmatically or directly through the database or another

You have to create a super admin role(admin/people/permissions) and check all the boxes. And then you need to assign this role to the user.


How to Trigger Existing, Non-Form Ajax from JavaScript Event

If you don't want to ajaxify the link with "use-ajax" and trigger an Ajax request programmatically use:

Drupal.ajax({url: endpoint}).execute();

This creates an Ajax object with the endpoint as url and executes it.

More options you'll find in the comments of Drupal.ajax in ajax.js:

/**
   * Provides Ajax page updating via jQuery $.ajax.
   *
   * This function is designed to improve developer experience by wrapping the
   * initialization of {@link Drupal.Ajax} objects and storing all created
   * objects in the {@link Drupal.ajax.instances} array.
   *
   * @example
   * Drupal.behaviors.myCustomAJAXStuff = {
   *   attach: function (context, settings) {
   *
   *     var ajaxSettings = {
   *       url: 'my/url/path',
   *       // If the old version of Drupal.ajax() needs to be used those
   *       // properties can be added
   *       base: 'myBase',
   *       element: $(context).find('.someElement')
   *     };
   *
   *     var myAjaxObject = Drupal.ajax(ajaxSettings);
   *
   *     // Declare a new Ajax command specifically for this Ajax object.
   *     myAjaxObject.commands.insert = function (ajax, response, status) {
   *       $('#my-wrapper').append(response.data);
   *       alert('New content was appended to #my-wrapper');
   *     };
   *
   *     // This command will remove this Ajax object from the page.
   *     myAjaxObject.commands.destroyObject = function (ajax, response, status) {
   *       Drupal.ajax.instances[this.instanceIndex] = null;
   *     };
   *
   *     // Programmatically trigger the Ajax request.
   *     myAjaxObject.execute();
   *   }
   * };
   *
   * @param {object} settings
   *   The settings object passed to {@link Drupal.Ajax} constructor.
   * @param {string} [settings.base]
   *   Base is passed to {@link Drupal.Ajax} constructor as the 'base'
   *   parameter.
   * @param {HTMLElement} [settings.element]
   *   Element parameter of {@link Drupal.Ajax} constructor, element on which
   *   event listeners will be bound.
   *
   * @return {Drupal.Ajax}
   *   The created Ajax object.
   *
   * @see Drupal.AjaxCommands
   */
  Drupal.ajax = function (settings) {

Your second question, is an XMLHttpRequest the only way to make JavaScript interact with the route/PHP? If so, what path should be used?

You can use a normal non drupal jQuery.ajax(), then you have no restrictions for the format, you can use json (which Drupal uses for it's own ajax) or any other format. You can set up a route for an arbitrary path and use this in $.ajax().


How to get event node to pull in data from a seperate node?

As I understood from you question you want to know the best way to display some information from the location inside the event node view page, if this the case you might need to create a  block view (from views module) takes the reference node location (nid) in the current node event being viewed, and as you have the view you can display all the information needed.

I hope this will help.


A better way to accomplish this is to use the Drupal Console's  container:debug command. This command outputs a list of Drupal service ID's and its corresponding namespace & class.

$drupal container:debug

 Service ID                 Class Name
 class_loader               Symfony\Component\ClassLoader\ApcClassLoader
 kernel                     Drupal\Core\DrupalKernel
 service_container          Drupal\Core\DependencyInjection\Container
 cache_context.ip           Drupal\Core\Cache\Context\IpCacheContext
 cache_context.headers      Drupal\Core\Cache\Context\HeadersCacheContext
 cache_context.cookies      Drupal\Core\Cache\Context\CookiesCacheContext
 ...

This command can be employed along with grep to search for a specific class name or service ID. For example: drupal container:debug | ag 'DatabaseStorage' to find a DatabaseStorage class.

Also of interest is the PhpStorm / IntelliJ Drupal Symfony Bridge plugin if you use PHPStorm.


have you tried toggling off the "Convert line breaks into HTML (i.e. <br> and <p>)" setting on the text input format?


Access multivalued field collection tokens in webform email

Try using the [webform_submission:node] to access field related tokens.  I think you might need to try [webform_submission:node:field_campaign_email_collaterals:0] or [webform_submission:node:field_campaign_email_collaterals:0:html]


React if user's text changes in existing node are major

I would use Diff and implement hook_entity_diff() (see diff.api.php), which allows modules to provide a comparison about entity properties.

Here you go:

function MYMODULE_entity_diff($old_entity, $new_entity, $context) {
  if ($context['entity_type'] == 'node') {
    $old_body = $old_entity->body[LANGUAGE_NONE][0]['value'];
    $new_body = $new_entity->body[LANGUAGE_NONE][0]['value'];
    $matching = similar_text($old_body, $new_body, $percent);
    $results['line'] = array(
      '#name' => t('Body'),
      '#old' => 'Number of matching chars: ' . $matching,
      '#new' => 'Percentage difference: ' . $percent,
    );
    return $results;
  }
}


You can check the hook_field_widget_info()

function hook_field_widget_info() {
  return array(
    'text_textfield' => array(
      'label' => t('Text field'),
      'field types' => array('text'),
      'settings' => array('size' => 60),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_DEFAULT,
        'default value' => FIELD_BEHAVIOR_DEFAULT,
      ),
    );

}


I found I was able to do this by changing the flag link text (in the flag configuration) to [node:flag-machinename-vote-count], which gave the number of flag for that node.

Then, modifying line 57 of the flag theme file: flag.tpl.php to

<a href="<?php print $link_href; ?>" title="<?php print $link_title; ?>" class="<?php print $flag_classes ?>" rel="nofollow"><?php print format_plural($link_text, '1 Flag', '@count Flags') ; ?>&nbsp;

Note that this is actually only changing the small php snippet that displays the link text to us the format_plural function:

this <?php print $link_text; ?>

to this <?php print format_plural($link_text, '1 Flag', '@count Flags') ; ?>


here you go: :)

$length = 50;

// strip html tags from body
$body = strip_tags($data->body);

// check that the body's actually longer than your snippet length
if (strlen($body) <= $length) {
  return $body;
}
else {

  // find a random starting point between the beginning and 50 chars from the end
  $max = strlen($body) - $length;
  $start = rand(0, $max);

  // set ellipsis variables
  $prefix = $start ? '...' : '';
  $suffix = ($start == $max) ? '' : '...';

  return $prefix . substr($body, $start, $length) . $suffix;
}


Use Drupal as a 'cloud system' frontend, what is your opinion?

You might want to look at Aegir.
It will let you manage multiple Drupal sites across multiple servers; you can add new servers via the Aegir master controller and once the servers are known to the controller you can create complex Drupal installs via the UI (Aegir master) with db on one server and code on other, mix and match, etc.

One of the cool stuff is that Aegir can also take a drush make file and assemble a Drupal install for you; it supports Drupal distributions which let you not only install Drupal, but also Open Atrium, Pressflow, Open Publish, etc.

If I were you I would definitely look at Aegir even if it doesn't take care of all my needs as it will be the only logical place to start extending.

For an introduction see An introduction to the Aegir Hosting system.

There are so many Aegir videos online; these are some of my favorites:

http://greenbeedigital.com.au/content/drupaldojo-introduction-aegir-hosting-system
By Miguel: http://greenbeedigital.com.au/content/installing-aegir-04-beta1
Again by Miguel; it's a must watch: http://greenbeedigital.com.au/content/building-drupal-applications-drushmake-provisioning-sites-aegir

If you like looking at code, here is the code for provisioning system which does all the magic: http://git.aegirproject.org/?p=provision.git;a=summary.


Clean URLs enabled but main-menu keeps replacing clean URL with ugly node/ URL

You need to also install the Global Redirect module to handle redirection to aliases.


Duplicate view results when adding a filter related to field with multiple values?

You can do this by enabling Aggregation or set distinct in Query settings

Go to your View->Advanced->Use Aggregation -> set YES
Next in your field filter criteria chose - Count DISTINCT

One more way -
  1. Go to your View->Advanced->Query Settings -> check DISTINCT


I didn't get the first part. About the expiring date you can use Scheduler.

You can decide when you want to unpublish or publish some content (Product display in your case).


The method below works superbly. hook_page_alter is the way to go and the #attached method. (as suggested in a comment instead of hook_preprocess_page I didn't know this would work for external js but it does. Pretty cool. With this method and a nested array with weight, it works as expected.

function MYTHEME_page_alter($cache) {

  if (drupal_is_front_page()) {
    // Render leaflet only on the home page
    $leaflet = array(
      '#attached' => array(
        'js' => array(
          '//cdn.leafletjs.com/leaflet-0.7.2/leaflet.js' => array(
            'group' => JS_LIBRARY,
            'weight' => -999
          ),
        ),
      ),
    );
    \Drupal::service('renderer')->renderRoot($leaflet);
  }
}

Also of note is that we use JS_LIBRARY instead of JS_THEME here.


Number of contents created by a user in a organic group

If you are happy to use the rules module or the user points module, this is relatively simple. I don't think it's possible using only views.

I would add an integer field to User and have a rule

Event: After Saving New Content
Condition: Entity is of type > Content Type B
Action: Calculate a value > Input 1 = site:current user:field / Operator + / Input 2 = 1

Then display that field in your view.

User points is another option but is unnecessary if you already use rules.


Is this a reasonable use of hook_user_presave?

If you look at the documentation page for Drupal 8, you will notice that sentence is not used anymore.

  Act on a user account being inserted or updated.

  This hook is invoked before the user account is saved to the database.

  Modules that want to store properties in the serialized {users}.data column, which is automatically loaded whenever a user account object is loaded, may add their properties to $account->data in order to have their data serialized on save.

The fact the hook has different parameters in Drupal 8 doesn't change its purpose. In fact, with Drupal 8 you could use the following code.

$account->mail = $account->original->mail;

$account->original contains the value returned from entity_load_unchanged().

Although on Drupal hook_user_presave() is normally used for the purpose you noticed, you could use it for the purpose you described.

The alternative would be to add a form submission handler to the user edit form which is executed before the default form submission handler. The pro of using hook_user_presave() is that it works also when a module programmatically save a user object using user_save().


Set number of values for a field in an entityform type based on a fixed value

After hours of searches I found a solution: https://www.drupal.org/node/2868353


How to add a description to the node title field in form

After several trial and errors this is the code working:

$form['title']['widget'][0]['value']['#description'] =  \Drupal\Core\Field\FieldFilteredMarkup::create('hallo');


You need to enable Organic groups access control module. This will let you set your groups to public/private.

There is a tutorial series on Organic Groups which explains everything you need to know about the configuration at http://modulesunraveled.com/organic-groups


drupal_goto forcing redirects to https when external link is http

drupal_goto() takes a $path and $options which in turn sends them to url().
As you can see in the docs  for url()

https://api.drupal.org/api/drupal/includes%21common.inc/function/url/7

  'https': Whether this URL should point to a secure location. If not
  defined, the current scheme is used, so the user stays on HTTP or
  HTTPS respectively. TRUE enforces HTTPS and FALSE enforces HTTP, but
  HTTPS can only be enforced when the variable 'https' is set to TRUE.

so in your case the redirects will be https by default, which means you will have to set the them individually each time to use only http e.g.

drupal_goto($path, array("external" => TRUE, "https" => FALSE));


Are there migration plugins for D8 sources?

Yes there is. Drupal core has a content_entity source plugin that's a part of the Migrate Drupal module.

The one caveat with this plugin is it can only handle scenarios where the source/destination DB is the same, which sounds like your scenario here.

If source/destination DB isn't the same, the Drupal 8 migration provides a d8_entity source plugin that does support this scenario.


How do I manage core and module updates along with config management between environments?

Yes, the referenced issue is related but I think this deserves a separate answer.

I agree this situation isn't fully satisfactory, but it's not too much of a problem.

In most environments, it won't be possibly to avoid manual configuration changes on production entirely. For example, contact forms are configuration (and not just a single file but 3 + 2 * number_of_fields) and users will likely create new ones without going through staging.

That basically means that you have to live with the situation that there can always be changes on production that are different from what happened on staging/dev. And that you have to treat the configuration on production as the master, unless you're deploying specific changes.

My process for deploying configuration changes usually looks like this:

Do the changes, commit them to a feature branch.
Export the configuration from production and commit it to whatever branch you use for that (for me, that's usually a branch called "production")
Merge your changes into that. Resolve conflicts if necessary.
Deploy the code to production.
Verify the configuration changes, make sure that ther are only known changes that know you prepared for deployment.
Import the configuration.

Module updates add the additional problem of update functions. If you have those, you need to run them between steps 4 and 5. Usually, those aren't a big problem unless they create new configuration with new UUID's. Then you have a problem if you want to import the same configuration entities from the staging config since those would have different UUID's and it would lead to deleting and re-creating them. You have to merge back the changed configuration from production before you can do that.

In general, I'd recommend to not mix module updates with feature/configuration deployments. Do module updates first, export the configuration again, then deploy again with new configuration.

Note that enabling new modules isn't affected by this, unless the module is installed by an update function. But if you deploy new modules through an updated core.extension module list, the config system supports that explicitly by taking the new configuration from your configuration export and not the module's clean default installation. So it's perfectly supported to enable a module on staging, customize its default config (not just simple configuration but also views and so on) and then deploy it to production.


It looks like your re-ordering script is buggy. Make sure it saves the state of the ordering. There should be something in your re-ordering script that tracks the order. Make sure it works. This can be fixed if you have access to the re-ordering script.


How can I use the grouped nid in a views template with two content types?

Here's one way to solve this. This is the easiest way to solve it through the interface, without the need for templating or coding.
It may not be the best option performance-wise because of combining data from two db tables through Views, but then again you'd probably need to build a very custom query to optimize, and caching might solve possible lags.
It can all be done through the Offers Views, without Relationships and Contextuals, but with the help of View Modes.
View Modes don't have anything to do with Views module, so this is something to keep in mind, I wish they were named Display Modes or something along those lines. You've probably already used two of them before: Full and Teaser.
View Modes are different ways you can display your entity Fields. Each mode controls which fields are shown, in which order, and with which display settings.
You need to create two additional View Modes for your Business CT (you can do that on the "Manage display" page of your CT or through Structure > Display modes > View modes, it will appear among the tabs). One mode will be for the top Business info (so you should include the fields you want to show there), and the other for what is shown bellow the Offers.
In your Offers Views add the Offers Fields how you want them displayed.
Then add two Business Entity Reference fields as well.
Rearrange the fields so you have one Business reference on top of the fields list, and the other on the bottom.
Configure the top one's Formatter to Rendered entity and choose the View mode you created earlier for it. Exclude it from display and save, then choose it as the 1st grouping field under Format Settings.
Configure the bottom Business reference to also format as Rendered entity but choose the second View mode you created for it.
You should now have it all groupped by Businesses and displaying correct info in correct places. Be mindful of the pagination you set because it can "break" one Business to display on two pages depending on the number of offers.


Change a normal submit 'input' type to 'button' type with button tag

Well that was quick... I used my intuition and was able to accomplish it by doing the following:

In mytheme.theme:

/**
 * @param $suggestions
 * @param array $variables
 */
function mytheme_theme_suggestions_input_alter(&$suggestions, array $variables) {
  $element = $variables['element'];

  if (isset($element['#attributes']['data-twig-suggestion'])) {
    $suggestions[] = 'input__' . $element['#type'] . '__' . $element['#attributes']['data-twig-suggestion'];
  }
}

/**
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 * @param $form_id
 */
function mytheme_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form['#id'] == 'views-exposed-form-search-results') {
    $form['actions']['submit']['#attributes']['data-twig-suggestion'] = 'search_results_submit';
    $form['actions']['submit']['#attributes']['class'][] = 'search-box__button';
  }
}

In input--submit--search-results-submit.html.twig

{#
/**
 * @file
 * Theme override for an 'input' #type form element.
 *
 * Available variables:
 * - attributes: A list of HTML attributes for the input element.
 * - children: Optional additional rendered elements.
 *
 * @see template_preprocess_input()
 */
#}
<button{{ attributes }}>
  <svg class="icon search-box__open">
    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="/themes/custom/mytheme/build/img/svg-sprite.svg#icon-search"></use>
  </svg>
</button>

Form still submits and functions as expected. Is this the general approach or at least acceptable? I will go with this unless there is a better way.


How to enable caching for ajax callbacks, especially for colorbox node?

This can be done. Will require 2 hooks hook_menu_alter() & hook_boot() and some non trivial code.

Top level overview of how to do this:
Use hook_menu_alter() to call a wrapper around colorbox_node_output() that will cache its output. Use hook_boot() to check the cache and deliver the cached content, routing the cached content though ajax_deliver().

An example of cache code flow can be seen in the 6.x-2.x ESI module. esi_get_page_cache() gets called from esi_boot. esi_set_page_cache() is what sets the cache; you can see it getting called at the bottom of these functions: esi__block_handler() & esi__panel_pane_handler(). Side note: A big reason the ESI module's cache code has a lot of complexity is it's compatible with D6 core and Pressflow; both have different code for the page cache.


The Vote Up/Down module, while it supports Views 2 integration, only allows for a Voting Up/Down widget. With no support in the module for retrieving the vote count, you'll need to do one of the following:

Wait for the maintainer to add a views handler that supports up & down votes data.
Create your own patch that adds support for that data.

Given the current state of the project (seeking maintainer, 7.x version not released), you're probably going to have to go with #2.


Update title field in hook_ENTITY_TYPE_insert()

Since nodes have no id on insert, you should just save the node twice.

node_save() initiates a database transaction, in which the changes are not yet written, but the id is already reserved (explaining your issues with not being able to save). You will have to await the database transaction before attempting to save the node again. Unfortunately there is no hook for this.

However, there is a workaround: drupal_register_shutdown_function(). This can be used to call an additional function at the end of the request.

You'll end up with a code like this:

function your_module_node_insert($node){
  if($node->type == 'your_node'){
    drupal_register_shutdown_function('_your_module_post_insert',$node);
  }
}

function _your_module_post_insert($node) {
  if ($node) {
      $node->save();
  }
}

Code comes originally from here: https://drupal.stackexchange.com/a/102185/9921


Routing for controller with multilingual enabled

The language is detected and the prefix removed before routing. So you have a static route without parameter and in the controller you can get the prefix from the language manager:

  $langcode = $this->languageManager()->getCurrentLanguage()->getId();


Is there a browser-side validation passed event I can listen for?

Drupal doesn't have a browser-side validation framework as it does with the back-end form validation handlers. The "Please fill..." message is the browser enforcing the required property.
If you'd like to hook into those validation events, you can bind event listeners on specific form elements for invalid events. If you want to take action on a submit click, the checkValidity() method can be executed on form field DOM objects.
See the MDN docs on the constraint validation API for more info.


You might want to have a look at the Paragraphs project. It basically allows you to create different building blocks (Image with text, Diagram with description, ...) and then you can piece them together in the edit form pretty easily.

Check out the demo module that's part of the project for a quick start. You'll still have to actually implement the design for each building block but once you have that, you can easily change how you've combined them and move parts around, add new ones.. create multiple pages that each uses those building blocks differently.


I suspect you have a setting or two wrong.  On admin/config/development/cdn make sure you are enabled, and not in testing mode:

Then goto admin/config/development/cdn/other, expand all of the sections and make sure you aren't excluding actual pages.


Is there a way to find out how many activated, registered users there are?

You can query the users table, counting the number of rows where status = 1, which will give you the number of active user accounts.


What is the replacement for menu_link_load()?

Drupal 8 menu links are now content entities. The equivalent to loading a D7 menu link object would be loading a MenuLinkContent entity. This can be done via the static Drupal\menu_link_content\Entity\MenuLinkContent::load() method.


For this you have to select text format to full html  check in admin/commerce/products/types/product/display or in admin/commerce/products/types/product/ your field name and check for format option.


You could achieve this with Comment Notify module.
We use it on few sites and it works great out of the box.

From module page:

  Features

  Mail registered and anonymous users about comment follow-ups

  Allow users to unsubscribe from notifications on a specific post with
  a single click

  Allow registered users to preset their follow-up setting in their
  profile

  Users can choose to get notifications about all comments on a node or
  just replies to their comment
  Registered authors can get notifications about comments on their nodes
  Note: Since it only notifies you about published comments, this is not a solution to notify admins when they need to moderate comments on their site


how would i go about creating variable menu links

You should try Context

  Context allows you to manage contextual conditions and reactions for
  different portions of your site. You can think of each context as
  representing a "section" of your site. For each context, you can
  choose the conditions that trigger this context to be active and
  choose different aspects of Drupal that should react to this active
  context.


I'm not sure what exactly you are looking for. The taxonomy terms for a node are normally nested inside $node->taxonomy. If you want all the terms "above" the terms inside the node, you should take a look at taxonomy_get_tree().
To the code above: I would urge you to seperate the tree-logic from the output; first create the array, then render the output.


Method of initiating a text trim at a matching string?

I'm answering my own question... To eliminate a text string in an imported node, I used the Feeds Tamper "find replace regex" plugin on the node's body.The regex to find was:

  /(?=FirstWord )(.*)(?<=LastWord[.])/s

Where FirstWord was the first word of the string to be eliminated, and LastWord[.] represented the last word of the string followed by a period. If you don't want to include punctuation, eliminate the [.] completely.

The trailing "s" indicates "single line mode," which makes the dot (before the asterisk) match all characters, including line breaks.

Of course, the replacement value was empty.


admin theme changes to default at editing page, Themekey module

I found the solution for this. I had to deselect the administration theme when editing or creating content, in admin/appearance.


I'm assuming you know how to filter the view to get the nodes based on the date and date + 6, but are having troubles grouping them together on output by date.

I see you are using D7, but to do this in D6, you would add the date field twice in the view and override one of these with a template to output just the day in question and group on that now simplified field.

A good article on that is http://drupal.org/node/388140 which shows you how to do it by month; to do it by day just change the date function to include it as well.

I would imagine D7 is very similar, and that this helps out.


How to override the ['search_distance'] in Location: Distance / Proximity Views in a custom module

I haven't had much experience with Location module. This feature is supported out of the box with Openlayers module. I would recommend checking out that module.

I have done a similar sort of thing for one of my clients. I had to hide the distance fields as they didn't want that. If you view source you can see those fields in HTML.

http://biopetonline.com.au/stores


How to send an email once a new member is invited using the Group module?

The Group module, out of the box, does not seem to send any eMail notifications to some user who got invited to join some group. Note however that a special Drupal message is shown right after an invited user performs a login to the site (too bad if the invited user never performs a login ...). Here is a sample of such message (which includes a link to relative path /user/uid/group/invite):

You have pending group invitations. Visit your profile to see them.

However, since Group is entirely entity based, it's a piece of cake to use Rules for creating such eMails. The clue to do so, is related to the creation of a new group membership, and which corresponds to Rules Event "After saving a new group membership*". This Rules Event is one of the events added by the Group module, located with 'Rules group' (don't get confused ...) "Group membership". However, a Group membership also has a status, which can be any of these:

Active
Requested
Blocked
Invited

With the above in mind, you can create a rather basic rule to do what you're asking for. Just use the Rules UI to import the rule below (in Rules export format) in your own site:
{ "rules_notification_about_new_group_invitation" : {
    "LABEL" : "Notification about new group invitation",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "group" ],
    "ON" : { "group_membership_insert" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "group-membership:status" ], "value" : "invited" } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "The user with name [group-membership:user] just got invited by [group-membership:invited-by:name] to join the group named [group-membership:group:title] (with group type [group-membership:group:group-type:label])." } },
      { "mail" : {
          "to" : [ "group-membership:user:mail" ],
          "subject" : "You\u0027re invited by [group-membership:invited-by:name] to join the group \u0022[group-membership:group:title]\u0022",
          "message" : "You\u0027re invited by [group-membership:invited-by:name] to join the group named [group-membership:group:title] (with group type [group-membership:group:group-type:label]).",
          "from" : [ "group-membership:invited-by:mail" ],
          "language" : [ "" ]
        }
      }
    ]
  }
}

Some more details about the Rules Actions in this rule:

show a Drupal message, each time a user is invited to join some group, similar to this sample message (which also shows various Group related tokens you can take advantage of, such as the name and type of the group):

The user with name Demo.User just got invited by Pierre.Vriens to join the group named Using the Answers module (with group type Class).

Create an appropriate eMail, using the various (relevant) tokens, e.g. the eMail Id of the user who performs the invite (= from), and the user that is invited (=to).

Note that for some user who is "added" to a group (instead of "invited") by an authorized user to do so, such message will not be shown. That's because of the Rules Condition included: the status for the selected group is not "Invited" in that case, instead the status will be "Active".
BTW, if you'd be willing (and able) to also use the Message module, you could add an extra Rules Action to create an appropriate Message entity (like a custom log record) also. And if you'd then use the Views module to create a custom view of such Messages, you'd have a perfect audit trail of who invited who for any of your groups ...


How do I disable the Update manager module?

You cannot disable a module as you do with Drupal 7 or previous versions, and this is valid also for the Update manager module. You could eventually avoid the module checks for new module versions, but the module itself doesn't have a setting for that in admin/reports/updates/settings.

What you could do is, using a custom module, avoiding Drupal invokes update_cron() which is the hook that periodically checks for updates.

function mymodule_implements_alter(&$implementations, $hook) {
  if ($hook == 'cron') {
    unset($implementations['update']);
  }
}

You could still manually check for updates from admin/reports/updates, but Drupal would not check for updates during cron tasks.

If then you also need to disable the route set by the Update manager module, you could also do it as shown in How do I alter the route defined by another module?
This is, I think, the closer you could get to disable the Update manager module.


D8, how to make node template aware of entity reference parent

well, this seems to be working.

function THEME_preprocess_node(&$variables) {
$nid  = $variables['node']->id();

if ($variables['elements']['#view_mode'] === 'VIEW_MODE') {
// Get the node ID.
    $variables['nid'] = $nid;
    $parent   = $variables['elements']['#node']->_referringItem->getEntity();
    $items = $parent->get('FIELD_NAME')->getValue();

    foreach ($items as $key => $item) {
        if ($item['target_id'] == $nid) {
            $variables['tree_position'] = $key;
        }
    }
  }
}

Not sure this is the best way. So any suggestions still welcome.


Drupal 6 stored it's content in one table per content type. CCK will adhere to that unless you share a field among several nodes, in which case the fields will be broken out to a separate table.

Drupal 7 creates a new table for every field, so you'll see a lot of tables named field_data_[name_of_field], and field_revision_[name_of_field], the former for the active data, and the latter for tracking any other revisions of the same data. You might be interested in this discussion How to disable the revision feature completely? if you don't need the revision functionality.

Use the entity_cache module to alleviate some of the performance hit from all the joins this causes on complex content types.

If you need an entity that is complex enough to make the D7 approach unusable, consider creating a custom entity where you make properties of your fields. That costs a bit of flexibility, but will make Drupal store the content like the title, which is a property, in the types table.


How to switch from using a theme function into using a template?

As described in the documentation for hook_theme(), the property that you need to provide in order to use a template file instead of calling the theme function is template.

  template: If specified, this theme implementation is a template, and this is the template file without an extension. Do not put .tpl.php on this file; that extension will be added automatically by the default rendering engine (which is PHPTemplate). If 'path', above, is specified, the template should also be in this path.

As you are altering the theme function implemented from another module, you are probably interested in setting also the path property.

  path: Override the path of the file to be used. Ordinarily the module or theme path will be used, but if the file will not be in the default path, include it here. This path should be relative to the Drupal root directory.


is autopostback available in jQuery or Ajax

<select id="autosubmit" name="autosubmit" class="autosubmit">
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
</select>

jQuery

$(document).ready(function () {
  $(".autosubmit").each(function (index) {
    $(this).change(function () {
      // write your custom trigger here.
    })
  });
});


Ajax call failing in Workbench email module

Thanks to Clive's suggestions, I logged the request and post data before the Drupal bootstrap kicked in, and found that it was not Drupal causing the issue.

The root cause was two different mod_security violations: PCRE limits exceeded and matching rule 300016 (Generic SQL injection protection).  Increasing the PCRE limit and adding an exception for the SQL Injection rule:

<LocationMatch "/system/ajax">
  SecRuleRemoveById 300016
</LocationMatch>

Just for the record, I got the idea that Drupal might strip out $_POST data from this comment: https://www.drupal.org/node/2209051#comment-8539311  I came across it trying to troubleshoot this issue earlier. Maybe I misunderstood or took it out of context. This was a hard one for me to figure out, and I was grasping for anything that sounded close to my issue. Thanks for the help, Clive!


Create a View that redirects to node content based on contextual filter?

One way I think of is to to this in a custom menu callback. So you could have an URL /mycallback/[OBJECT_ID] which would redirect to the first node that has the given [OBJECT_ID].

Something like this:

/**
 * Implements hook_menu().
 */
function MYMODULE_menu() {
  $items['mycallback/%'] = array(
    'page callback' => 'fieldvalue_redirect_callback',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Custom callback given a object id.
 */
function fieldvalue_redirect_callback($id) {
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
  ->fieldCondition('field_object_id', 'value', $id, '=')
  ->addMetaData('account', user_load(1));
  $result = $query->execute();

  if (isset($result['node'])) {
    drupal_goto(url('node/' . key($result['node'])));
  } else {
    drupal_set_message(t('Page not found'), 'error');
    drupal_goto('<front>');
  }
}

First comes the definition of the menu callback, MYMODULE_menu().

The argument after mycallback/ is being passed on the the page callback function by defining it here 'page arguments' => array(1),.

fieldvalue_redirect_callback() will get the id entered by the user after /mycallback as argument. In the function we use EntityFieldQuery to fetch the node that matches the given ID.

And last we redirect if we get a result, otherwise we show an error message and the front page.

Hope this can help you or someone else.


How to preserve form values for user who navigates out of form and back?

I'm not aware of a specifically Drupal way to do it.

As I say, I find that if I fill out a form, don't submit, click a link, and then click back, the form elements are still populated, unless perhaps there's some AJAX/JS funkiness going on with them (the actual form elements). However a little digging suggests that's browser-dependent and won't work in certain situations (eg. over HTTPS). I'd love to know more about this behaviour.

I think ideally you'd use JS to put the data in the URL. If you don't need to support older browsers then you can use the History API (not that I ever have...) which would allow you to separate arguments in a more Drupally way: eg. path/arg1/arg2/arg3. Otherwise the traditional window.location.hash can be used instead.

You can use the session variable like Views, which is more flexible and simpler to implement, but can cause anonymous users to bypass caching.


The price/amount is wrong. You do not have enough significant digits. Commerce works via a base price. Example:

A product that costs $20.00 (USD) is expressed as 2000 in Commerce. Basically all prices in Commerce should have the decimal point moved to the right by two or essentially multiplied by 100 and remove all significant digits to the right of the decimal point.

So in your case the price should be 2000 not 20.

Also I would like to point out a security issue in your code.  You are consuming a $_POST global variable directly into Drupal without first cleansing the $_POST.  This could open your site up to XSS attacks.  You should first past the $_POST global variable through filter_xss() before using the contents of that global variable.  Also note that Drupal Core offers ways to consume post variables if you use hook_menu for the page that this is running on.


How to install a module from an archive file with drush?

You can use drush make to unpack a module named your_module from an archive file, as follows:

Create a modulename.make file containing:

core = 7.x
api = 2
; Install from local module archive file.
projects[your_module][type] = "module"
projects[your_module][download][type] = "file"
projects[your_module][download][url] = "file:///dir/your_module.tar.gz"

While in the Drupal root directory of your site, execute the Makefile and enable your module:

drush make --no-core -y your_module.make && drush en -y your_module

Alternatively, you can script this into one set of commands, using a temporary file instead of a separate Makefile. Again, to be executed while in the Drupal root directory:

#!/bin/bash
module="your_module"
makefile=$(mktemp)
echo "Created temp file $makefile"
cat << end-of-makefile >$makefile
  core = 7.x
  api = 2
  projects[$module][type] = "module"
  projects[$module][download][type] = "file"
  projects[$module][download][url] = "file:///dir/file.tar.gz"
end-of-makefile
drush make --no-core -y --verbose $makefile
drush en -y $module

(Bash named pipes or bash process substitution via <(echo …) cannot be used here to avoid a temp file. They create streams, which are non-seekable files that drush make fails to read from.)


To alter how to insert content into the field, define your own field widget and then apply the new widget for the existing field in "manage form display" of the content type.

Field Widget

To alter how the field is displayed, define you own field formatter and apply it in "manage display" in the same way:

Field Formatter

When you start with a field widget or field formatter, the fastest way is to copy an existing one out of core and modify it or use drupal console to generate the scaffolding.

If you only want to modifiy an existing widget/formatter, then extend it, not write a complete new one. This is a good explanation, how to do this:

http://www.sitepoint.com/creating-custom-field-formatters-drupal-8/


Pressflow online users stats does not show correctly

I believe this is because of how Pressflow handles anonymous sessions.  It implements what are called "lazy sessions", which only creates sessions when actually needed.

This behavior can be changed by putting a drupal_start_session() in a custom hook_init.  If you do this, though, you will likely take a performance hit.

I have had to do this with a few projects to fix session problems when moving from Drupal 6 to Pressflow 6.

EDIT TO ADDRESS COMMENT:

You can simply put the hook in a custom module, such as

function mymodule_init ()
{
  drupal_start_session();
}

Note that you should really profile before and after to see what the performance impact is.


How do I set permission for a custom page to be based on node access?

Use entries/get/%node as path and node_access() as access callback. Also, you might want to consider setting page arguments. It's not a good idea for the page callback to fetch the node id from the URL or using the  arg() function.

$items['entries/get/%node'] = array(
  'title' => 'Dynamic Entries',
  'page callback' => 'dynamic_entries_get_entry',
  'page arguments' => array(2),
  'access callback' => 'node_access',
  'access arguments' => array('view', 2),
  'type' => MENU_CALLBACK,
);

BTW the function node_menu() is the hook_menu implementation of the node module. Looking up how the Drupal core modules implement certain hooks often helps.


Why do all my urls look like 'content/name-of-page'

Go to /admin/config/search/path/patterns to configure your content types appropriately. I believe the first one acts as a default if you do not define the other paths for content types.


I wouldn't increase the length of the field, but instead ask yourself why you are storing so much information in the title. There is a very good chance you simply need to split the information out into different fields or use a textarea to store ancillary information. You don't know how many assumptions commerce makes about the title field with regards to logic and formatting and the general Commerce wisdom is to not mess with the internals.


Display block based on main content type with view

In your case you don't need to provide any default value with PHP code.

Remove your contextual filter and add new one: Content: nid.

"WHEN THE FILTER VALUE IS NOT AVAILABLE"

Provide default value -> content ID from URL

"When the filter value IS available or a default is provided"

Specify validation criteria

Validator -> Content -> book


Unable to fetch paragraph's multi field values inside node twig

Off the top of my head...

For multiple value fields you either render out the paragraph field itself:

{{ content.field_paragraph_field_name }}

and let Drupal handle the multiple value rendering, or do your own loop:

{% for item in content.field_paragraph_field_name %}
  {{ item.your.array.keys.here.value }}
{% endfor %}

Try:

{% for item in content.field_paragraph_field_name %}
  {{ dump(item | keys) }}
{% endfor %}

to see what keys you need to follow to your value.

I do recommend doing this kind of theming in a paragraph--paragraph-name.html.twig file, and then just printing the field in node.html.twig.

For a paragraph template file, it would look something like:

{% for item in content.field_paragraph_field_name['#items'] %}
  <div>{{ item.value }}</div>
{% endfor %}

For the error, looks like you're cycling through the reference field, but you need to cycle through the values of a field inside the reference field. (I'm sure someone could explain this better, but entity holds the field values you want to loop)

Instead of:

{% for item in node.field_para %}
    {{ item.entity.field_cdsfasdf.value }}
{% endfor %}

try something more like:

{% for item in node.field_para.entity.field_cdsfasdf %}
    {{ item.value }}
{% endfor %}


Use CSS to change the div created by the field group.  Set margin, padding, border and font-size to 0.

Don't hide the div because that will hide the contents of the div.


How should I let some users to download from Private folder

What field type serve the link for the download ? Maybe the module behind this type already implement this hook ?
For example, File module or Image module already implement this hook_file_download.

In case of File module, it allow you to alter the permission to access to the file.

// Allow other modules to alter the returned grants/denies.
    drupal_alter('file_download_access', $grants, $field_item, $entity_type, $entity);

You just have to implement the hook_file_download_access_alter. By the way, there is this other hook (hook_file_download_acces) you can may be try to hook.

Finally, if no one of this hooks can help you, so may be you have to use this hook_file_download. But I don't really know what is expecting as headers, but you can look at the hook in the Image module.

There, it get headers from others modules (may be you can just use this trick) :

// Check the permissions of the original to grant access to this image.
  $headers = module_invoke_all('file_download', $original_uri);

And just after that, it make its own headers :

return array(

      // Send headers describing the image's size, and MIME-type...
      'Content-Type' => $info['mime_type'],
      'Content-Length' => $info['file_size'],
      // By not explicitly setting them here, this uses normal Drupal // Expires, Cache-Control and ETag headers to prevent proxy or // browser caching of private images.
    );

Hoping that help :)


Adding a delete button to node edit form

There is a "Delete" Link right to the "Save" Button. If you can't see it, you're missing the "delete content of type x" permission.
If you need the Link styled as button, use the matching css classes of your theme.


Is the Drupal philosophy to create some content/view and assign permissions to that for these top-level menus?

Obviously there is no hard and fast rule about this, but generally speaking your hunch is correct. Drupal menus expect every link (even a parent) to link to some content. As an example, the "add content" link goes to a page that lists the available content types even though the content types are usually listed under "add content" in the menu anyway.

I do not believe there is an example in core where a menu link is there only as a parent and does not link anywhere.


how to open a link field in new window in view

1) Click your image field at your views
2) Click Rewrite results. Check Output this field as a link. Key in your URL in the Link Path

) 3) At Target text field, key in this "_blank"


How to translate views infinite scroll Loading message

I'm using webpal pinteros theme, and it has its own js/views_infinite_scroll.js file, in-which the message could be translated. However, this solution is not suitable for multiple languages sites.


Opening user session programmatically using headers information

As the hook_init() doesn't works for the cached pages so the alternate option that seems to me is the hook_boot() (This hook is run at the beginning of the page request. It is typically used to set up global parameters that are needed later in the request),

However the discussion here on using the session during hook_boot make me feel that hook_boot() is invoked too early to use the session, as Drupal has not yet initialised the session.

  There is a trick to avoid the page is cached: Call drupal_page_is_cacheable(FALSE) in hook_init().

Check more here: using drupal sessions during hook_boot


How do I save a file with managed_file in a theme?

The way it was done in Drupal 7 was that you wrote a function for hook_form_submit where you would

// Get the File ID (fid).
$fid = $form_status['values']['managed_file_field'];

// Load the file.
$file = file_load($fid);

// Set the status to permanent.
$file->status = FILE_STATUS_PERMANENT;

// Finally save the file.
$file->save();

You can read more about this with a great Drupal 7 example here.
I'm sure there's something similar on Drupal 8. You'll just need to register a submit handler for the form. Take a look at the docs for managed_file if you want to go that route. here for it.


In your image, you are configuring the "Entity" parameter of the "Entity has field" condition. That parameter should be set to just "user" in the data selector - it would be wrong to specify a field here since it is calling for the entity that you want to check.

The SECOND parameter should be "Field", and it is there that you would want to enter "field_certified_tap" using direct input (not data selector).

Note that the "Entity has field" condition cannot be used to check the value of the field - that has to be done in a separate "Data comparison" condition.

But you are right that even when you properly configure the "Entity has field" condition, your custom field does not show up in the data selector for subsequent actions. I'm not sure why, but there's an open bug report for that in the Rules issue queue:  "Entity has field" doesn't actually give access to the field

Instead, use the "Entity is of bundle" condition to get access to the field. Here's an example using a boolean field called "field_certified_tap" which I added to the user entity. If you import this Rule and examine it in your UI you will see that after adding the "Entity is of bundle" condition to the rule, the data selector in the "Data comparison" condition and the "Show a system message" action DOES now give you an option of "user.field_certified_tap". You can then add a "Data comparison" condition to show the message only when field_certified_tap is true.

I'm using "Show a system message" here because it's much easier to use for debugging than "Send mail". You should use this action to test the tokens you plan to use for your email, then when you are sure you have the values you need you can add a "Send mail" action.

langcode: en
status: true
dependencies: {  }
id: access_certified_tap_field
label: 'Access user certified tap field'
events:
  -
    event_name: 'rules_entity_update:user'
description: ''
tags: {  }
config_version: '3'
expression:
  id: rules_rule
  uuid: 137a6a57-2d1a-467d-80e6-68091de5eb11
  conditions:
    id: rules_and
    uuid: 098bb2b1-3e95-4efa-9328-07b651591e63
    conditions:
      -
        id: rules_condition
        uuid: 3b23a038-ac0c-4461-b14b-6db518c3261a
        context_values:
          type: user
          bundle: user
        context_mapping:
          entity: user
        context_processors:
          type:
            rules_tokens: {  }
          bundle:
            rules_tokens: {  }
        provides_mapping: {  }
        condition_id: rules_entity_is_of_bundle
        negate: false
      -
        id: rules_condition
        uuid: fbcdef7b-9681-47a2-bcac-94d49c86d7fa
        context_values:
          data: '{{ user.field_certified_tap }}'
          operation: '=='
          value: '1'
        context_mapping: {  }
        context_processors:
          data:
            rules_tokens: {  }
          operation:
            rules_tokens: {  }
          value:
            rules_tokens: {  }
        provides_mapping: {  }
        condition_id: rules_data_comparison
        negate: false
  actions:
    id: rules_action_set
    uuid: d6d904a0-007a-4f7f-97be-ac7c1f64edd2
    actions:
      -
        id: rules_action
        uuid: c5d31406-7355-4d91-b623-2c55dc3d57cb
        context_values:
          message: 'User is certifiable!'
          type: warning
          repeat: false
        context_mapping: {  }
        context_processors:
          message:
            rules_tokens: {  }
          type:
            rules_tokens: {  }
          repeat:
            rules_tokens: {  }
        provides_mapping: {  }
        action_id: rules_system_message


Update hooks not being run when module enabled - chicken and egg problem

A module with an install file gets run at install, for an example if you install/enable a module with one hook_install and three hook_update_ only the hook_install will be ran.

The best way to do what you want to do is create a module like you want, with a empty hook_install then just keep adding hook_update_ functions as you need to do more stuff, then when you are done run update.php to run all the hooks.

It may also be a good idea to separate the types of stuff you want to do into groups (like create new items, and add them to the database, then another hook could be delete x and y, and another could be rename a and b) and add them as hook_update_ so for example if you need to run something more then once for an example or maybe down the road, you could just call update.php and run that specific hook_update_ function (if you for example wanted to run delete x and y more then once, you can).


You can use the Views module plus Slickgrid to do that.

The module:

  defines a slickgrid view style, so all data can be output as an editable grid.

And can also be used for data entry/manipulation directly within the grid itself.


Instead of using a preprocess function, you could accomplish the desired behavior using CSS.

Using the ::before and ::after selectors you can insert additional content. This content could be the textual " character (i.e., content: '"';) or you could display it as an (inline-)block, provide width, height, margin and padding and set a background image.

For example:

.field--name-body {
  padding-left: 1em;
  padding-right: 1em;
}

.field--name-body::before {
  content: '"';
  position: absolute;
  top: 0;
  left: 0;
}

.field--name-body::after {
  content: '"';
  position: absolute;
  right: 0;
  bottom: 0;
}

This creates some space around the body field and provides " characters at the top left and bottom right location.


Already the page-taxonomy-term-TERM_ID is present on the body tag.

To add more classes you can use hook_preprocess_html() and add the $vars['classes_array'] to add the css classes you want for the terms.


How to get the destination nid from an URL object

Looks like you're using the latest Devel, 4.0.1, which sadly currently doesn't show the available methods tab unless you patch it.
If you had the available methods tab, you would've seen that you can retrieve using the public method getRouteParameters
$nid = $url_object->getRouteParameters()['node'];


Show full content of related entity using Entity Reference in node view

You don't need a view for this. Instead, you can set the display settings for your entity reference field to Full display.
On Structure > Content types > My content type > Manage display, for the entity reference field choose Rendered entity as format. You can then have Full content as a view mode.


If you're looking for a module, try Splashify. Splashify is although not available for Drupal 6. Tinybox can help too but I haven't tried it myself.

You can also create this yourself, simplest way would be to change your front-page in configuration in toolbar, create that page, in drupal template, write something like this:

<?php
if (drupal_is_front_page()) {
    ?>
/*Your Splash Screen Code*/
<?php
    }
?>

Your Splash Screen Code can be a simple HTML Model, see this Simple Tutorial.


In defining a hook_block_info() is it possible to define the region per theme?

I can't say for sure but I would be surprised if that works.

You could try to define the region using the Context module and Context Conditional Theme module if you only want certain blocks to show up in certain regions for certain themes. Context module configuration is exportable so you could commit those settings to code.


What should be the optimum values for Minimum cache lifetime and Expiration of cached pages

The values of minimum cache lifetime and expiration of cached pages depends on how frequently the content on your site changes and for how long the external caches can show stale data from your site.

To get more info about these check https://drupal.stackexchange.com/a/83342/4876

However in your case I am not sure if these will matter. You should probably consider looking at Views Content Cache That might improve the performance in your case.


Get all content in all language using query

Following code should work:

$langcd = \Drupal::languageManager()->getLanguages();
$langcd = array_keys($langcd);
$query = \Drupal::entityQuery('node')
        ->condition('status', 1)
        ->condition('type', 'page');
$query->condition('langcode', $langcd, 'IN');
$nids = $query->execute();

Get list of active languages first, then change condition for langcode to IN.


The only real downside that I can think of is that the SQL that is generated can be really verbose, as it is not meant to be read by humans.

Very often, I will take a first pass at functionality for something using Views, grab the SQL, and then refine/optimize.  In fact, using Views to generate the initial SQL can be very handy for figuring out what you need to do your JOINs on.

One catch is that Views knows about internal structure.  If you do something that changes underlying table structure, Views will compensate automagically.  You would need to update your SQL manually.  One place this happens is with Drupal 6 and CCK, when you change fields from single value on a single content type to multiple value and/or add them to multiple content types.

All of that said, the new database abstraction layer and EntityFieldQuery does make life easier, and you may not need to use Views as an intermediate step.


If the content that you refer to is a node then you can use the twig path function as follows:

{{ 'Example text'|t }}


I assume you add Views for User listing:

add "User: uid" field;
exclude from showing;
move to the top of field list (rearrange);
Click on field, that you want to link with user profile.
Expand: Rewrite results
Check: Output this field as a link R
In the bottom, find "Replacement patterns", user uid  pattertn: [uid]
Place it on "Link path" next text: user/[uid]
Check that link appear.


How to set shorter caching time for a paragraph


How did the ransomware get in?

The website most likely got hacked.

  What is the most likely reason for a Drupal site to be infected with
  ransomware?

1) Well, doing exactly what that site owner did, putting off security updates which will leave you vulnerable.

2) Leaving the front door open: Allowing scripts, javascript/jQuery or PHP to be executed by regular users.

3) Not using Secure Login

  For sites that are available via both HTTP and HTTPS, Secure Login
  module ensures that the user login and other forms are submitted
  securely via HTTPS, thus preventing passwords and other private user
  data from being transmitted in the clear. Secure Login module locks
  down not just the user/login page but also any page containing the
  user login block, and any other forms that you configure to be
  secured.

Hacked!

  This module does not and will not prevent your site from being 'hacked'.

  This module scans the currently installed Drupal, contributed modules
  and themes, re-downloads them and determines if they have been
  changed. Changes are marked clearly and if the diff module is
  installed then Hacked! will allow you to see the exact lines that have
  changed.

Your Drupal site got hacked. Now what?


Darvanen, shs code didn't help, the module has always the correct tid, but I have to find it in a tree.

So I made my own function. (note I'm not a php pro)
TABLE
CAT1|CAT2|CAT3

function getcorrecttid() {

$nodes = db_query('SELECT cat1, cat2, cat3 FROM {TABLE});

// record loop
foreach($nodes as $node) {

// get TID with the last column
$query = new EntityFieldQuery;
$result = $query
  ->entityCondition('entity_type', 'taxonomy_term')
  ->propertyCondition('name', $node->cat3)
  ->propertyCondition('vid', 3)
  ->execute();

// check if has more than one
if (count($result['taxonomy_term']) > 1 ) {
  $tids = array();
  $tids = $result['taxonomy_term'];
  $i = 0;
  foreach ($tids as $t) {
    $Keys = array_keys($tids);

    $parent = taxonomy_get_parents($Keys[$i]);
    $pKeys = array_keys($parent);
    $c = 0;
    foreach ($pKeys as $b) {
      $pnum = array_keys($parent);
      if ($parent[$pnum[$c]]->name == $node->cat2) {
        $root = taxonomy_get_parents($pKeys[$c]);
        $rKeys = array_keys($root);
        $a = 0;
        foreach ($rKeys as $z) {
          // found a correct TID after a lot of loops, (caution this is a heavy, heavy search.....)
          $mytid = $Keys[$i];
          }
        $a++;
        }
      }
      $c++;
    }
    $i++;
  }
} else {
  $mytid = array_shift($result['taxonomy_term'])->tid;
  // Found no multi parents...
}
}
}