The has_js cookie is set, to indicate JavaScript is enabled, in drupal.js with the following code.

// 'js enabled' cookie.
document.cookie = 'has_js=1; path=/';

The HttpOnly flag makes the cookie not available from JavaScript.
For that reason, it's not possible to set the HttpOnly flag when creating a cookie from JavaScript. It may cause issues if there is code that checks for that cookie to determine if JavaScript or cookie support is enabled.

The Secure flag is used to make the cookie only available over HTTPS, which may cause issues with checking for JavaScript support on non HTTPS pages. Nevertheless, if your site is fully HTTPS, that should be fine.

With that being said, you could look into setting the HttpOnly flag on the has_js cookie server side, by checking for that cookie and updating it to use the HttpOnly flag via setcookie().


Is there a way to swap webform object between nodes?

Simply swapping Node IDs in {webform} table does not help, but switching them in {webform_component} is.

The way I did it was to swap nids in following tables:

{webform}
{webform_component}
{webform_emails}

I didn't touch submission tables because I was planning to purge them anyway, but for test purposes I needed to swap:

{webform_submissions}
{webform_submitted_data}

That did it. Don't know if it is really enough, but I see no errors after a long time of use.


you need to enable kint() to get the routs but you need to make sure the permissions for using kint() is correct.
and you can add your debugging into alterRouts()


How to override  ad_adapi() in custom module

As the Advertisement module invokes that hook using module_invoke_all('adapi', 'permissions'), and it doesn't use drupal_alter('adapi'), your module could override that implementation of hook_adapi() using code similar to the following one. (I assume the short name of your custom module is "custom_module"; change it to the short name you are using for your module.)

function custom_module_adapi($op, $node = NULL) {
  switch ($op) {
    case 'permissions':
      return array(
        'access statistics' => TRUE,
        'access click history' => TRUE,
        'access activity log' => TRUE,
        'set status as pending' => FALSE,
        'set status as denied' => FALSE,
        'set status from pending to approved' => FALSE,
        'set status from pending to denied' => FALSE,
        'set status from approved to active' => TRUE,
        'set status from approved to offline' => TRUE,
        'set status from active to offline' => TRUE,
        'set status from active to expired' => FALSE,
        'set status from offline to active' => TRUE,
        'set status from offline to expired' => FALSE,
        // Add your permissions.
      );
      break;
  }
}

function custom_module_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'adapi') {
    // Move custom_module_module_adapi() to the end of the list. module_implements()
    // iterates through $implementations with a foreach loop which PHP iterates
    // in the order that the items were added, so to move an item to the end of
    // the array, we remove it and then add it.
    $group = $implementations['custom_module'];
    unset($implementations['custom_module']);
    $implementations['custom_module'] = $group;
  }
}

custom_module_adapi() is completely overriding the values returned from ad_adapi(); for this reason, it cannot simply add the extra values it needs.
The code I wrote is a kind of hack; the correct way would be for the Advertisement module to use drupal_alter() to allow third-party modules to override the values set from other modules. The code I wrote works, but you need to keep update the code for custom_module_adapi() with the code used in ad_adapi(), in the case it is changes.
Only the branch 7.x-1 has ad_adapi(); the branch 7.x-2 doesn't have that function anymore. If you are planning to use that branch, the code for your custom module should be changed.


How to allow the user to change the language?

You can find a detailed answer in step 5 of this guide: 5 Steps to Build a Drupal 8 Multi-lingual Site.

Basically, this is what you need to do:

Go to Admin > Structure > Blocks
Click "Place blocks" on the desired region
Click "Place block" next to the "Language Switcher" block
Click "Save block"
Go to a translated node and the Language Switcher will be working

As a sidenote mentioned in the comments of that guide: "You also need to have the url method enabled in the detection and selection page."


How to add_js per content type in my module?

Here's how to add content type specific javascript to a node using hook_node_view and #attached

/**
 * Implements hook_node_view().
 */
function MYMODULE_node_view($node, $view_mode, $langcode) {

  // Add content type specific JS on full page node view
  if($view_mode == 'full'){
    switch($node->type){
      case 'article':
        $node->content['#attached']['js'][] = array('data' => drupal_get_path('theme', 'MYTHEME') .'/js/article.js');
      break;
      case 'page':
        $node->content['#attached']['js'][] = array('data' => drupal_get_path('theme', 'MYTHEME') .'/js/page.js');
      break;
    }
  }

}


Render a node as plain text for sending by mail

The render engine of Drupal cannot render Node as plain text (at least natively).

I think you have to choice between send the mail in HTML format with is very easy by changing the $message['header'] of your mail or installing Mail system with Swift Mailer (very easy too). Or you have to parse the field value yourself by escaping HTML markups (bad way IMO).

I strongly recommend you to send your mail in HTML format if you want to enjoy the benefits of the drupal render engine, which is made for generate HTML output.


Is it possible to run a View from code in a cron hook?

Problem sorted. It was all down to permissions, and loading user 1 as described in the blog linked to by my previous comment allowed the View to work as expected.


In webforms, how do I send the current user an email automatically?

As @huelfe recommended, the token [webform-authenticated-user:mail] actually works for this purpose in the custom to email address.


How to get node url of selected language?

You want to use toUrl() with the language option.

$node->toUrl('canonical', ['language' => $node->language()]);

Unfortunately, toUrl() currently doesn't automatically respect the active language.


How to use addField function when the field name is SQL keyword

I fixed it, using this code:

$query->addField('sco_groups', 'order', 'field_order');


Do something in hook_node_load only when displaying node

Yes, you'll need to examine the URL for this.

Loading a node is (correctly), completely de-coupled from displaying a node. node_load() doesn't know what you've loaded the node for; it doesn't care, its only responsibility is to prepare the node object.

So the context you're looking for doesn't conceptually exist when hook_node_load() is invoked, as that by definition has to happen before the object is passed to node_view(), and there's no way to signal your desired intent to node_load()


How to give anonymous user access in a menu hook?

You can definitely set 'access callback' => TRUE on the menu item and that will bypass any access checks, you don't need to implement a function that just returns TRUE (it would be redundant). Don't forget you need to clear the caches before changes in hook_menu will get picked up though.

Rather than just blindly returning TRUE though it's probably a better idea to assign a permission to the anonymous user role, or piggyback off of one that's already there (access content is the usual suspect for this if it fits in with your workflow). You can do that by using 'access arguments' => array('access content') instead of 'access callback' (don't use both).

Also you've missed out the title in your example, according to the docs that property is required. I doubt that's actually causing the problem though.

Just on another note, you mention that you're visiting '/search' to test this page - the path you've defined will be at '/site_search' instead.


Is it correct that a node and it's translations have the same node id?

Yes it's correct because Drupal 8 use Entity Translation (in core) for the translations.

You can more about this in Drupal 8 multilingual tidbits 17: content translation basics

  If you already built multilingual sites with Drupal 7 that had content
  translation, you may notice this model is a refined version of the
  Drupal 7 Entity translation module (without awkward modules required
  like Title) rather than the Drupal 7 core content translation module.
  The core module in Drupal 7 keeps different copies of nodes and
  relates them together in a translation set. In Drupal 8 this feature
  is not available, instead you can configure translatability on a field
  (and in some cases subfield) basis. However if you configure all
  fields to be fully translatable, you can essentially reproduce the
  Drupal 7 behavior. Compared to the Drupal 7 core solution with
  different entity identifiers then, Drupal 8 will have the same entity
  identifier but a different language variant.

  The biggest advantage of the Drupal 8 solution is you can configure to
  translate as much as needed and not more. With one unified solution to
  translate only some fields or all fields, (contributed) modules only
  need to deal with one system instead of two. With storing translations
  under one entity, modules that don't want or need to deal with
  multilingual scenarios can still consider the entity as one, no need
  for special translation set support. That is way more flexible than
  Drupal 7 and best of all it applies to all kinds of content, not just
  nodes. It is future proof for modules you enable like rules and
  commerce.


Facet filter in Views wrongly returns "No results"

I figured out what the problem was. I was using Indexed Node: Composer for the exposed filter instead of Search: Fulltext search (the field composer was indexed as a fulltext index).


(Newbie question) Something goes wrong here with db_add_field

First, make sure that Statistics module installed/enabled.

Second, replace your code with the following code:

function node_statistics_schema_alter(&$schema) {
  // Add field to existing schema.
  $schema['accesslog']['fields']['nid'] = array(
    'type' => 'int',
    'length' => '11',
    'default' => '0',
    'not null' => TRUE,
    'unsigned' => TRUE,
    'description' => 'Field added by node_statistics',
  );
}

function node_statistics_install() {
  $table = 'accesslog';

  $schema = drupal_get_schema($table);

  db_add_field($table, 'nid', $schema['fields']['nid']);
}

Note: make sure to uninstall and install your module after you apply the new code.


How do I exclude a single menu item from the home page?

Here is one method, and I must confess it may not be the absolute best. This method works for a menu that is not inside a block.

In your page.tpl.php use the following snippet:

if (drupal_is_front_page()) {
  foreach ($primary_links as $key => $value) {
    if (in_array('Home', $value)) {
      unset($primary_links[$key]);
    }
  }
}

The snippet will hide the element that contains the value 'Home' in the 'title' attribute.

Place that snippet before this chunk of code (so that $primary_links is modified before it is printed out):

<?php if (isset($primary_links)) : ?>
   <?php print theme('links', $primary_links, array('class' => 'links primary-links')) ?>
<?php endif; ?>


The discovery process is not the right place for dynamic behavior. A menu link defined statically in a yaml file can provide dynamic values only in a menu link plugin class.

In your case you would implement the method MenuLinkInterface::getTitle:

  public function getTitle() {
    return $title;
  }

See this answer https://drupal.stackexchange.com/a/249342/47547 for a complete example of a menu link class.

Although for translating the title this should not be necessary, titles of routes and menu links are covered by interface translation, see Translate routing and menu titles


Prompt registration based on number of free articles read

It seems you're looking for the Node Access module

  Nodeaccess is a Drupal access control module which provides view, edit and delete access to nodes. Users with the 'grant node permissions' permission will have a grant tab on node pages which allows them to grant access to that node by user or role. Administrators can set default access controls per content type, and also define which roles are available to grant permissions to on the node grants tab.

Image from module page


When I disable the poll module my add content page doesn't work. Why?

Cache can often be a source to weird problems, clearing it could help. The poll module won't effect if other content types are active or not, so the problem shouldn't be related to the poll module directly.


menu_tree_all_data() returns empty arrays for custom menus

Custom menu machine names always have a prefix of "menu-", e.g.:

$tree = menu_tree_all_data('menu-custom-menu');

Make sure you're using the right machine name. Edit the menu and look at the URL: The last part of it is the machine name for the menu.


CKEditor tabber shows tabs to the right on the screen when logged in as admin

In case anyone else has the same problem I will answer my own question. I found the answer to my problem in this issue for the same module: https://www.drupal.org/node/2774763
The problem was not exactly the same to begin with, but the solution was the same. The variable tabIndex needed to be placed within the function, not outside as a global. Problem solved.


Node and Webform - Open, Close, Scheduled and Limit per source entity

The Webform module includes the 'Webform Demo: Event Registration System' module which shows how to pass field related tokens from a Webform 'event' node to a webform submission.


How to implement a calendar based system for loaning of equipment?

Below is a summmary of the modules you may want to look at. These modules have a stable release for D7, and also for D6 (quotes are from their project pages):

Availability Calendars.

  ... allows you to add an availability calendar to entities. Example use cases are tourist accommodation, e.g. bed and breakfast, holiday homes or self catered apartments, and car or motor bike rental.

  An availability calendar shows your customers at what dates your accommodation is still available and at what dates it is already booked.

Simple Reservation.

  ... provides a simple and easy way to reserve items which can be created by the administrator. Examples for it's usage can be hotel rooms, boats, cars, airplanes, basically anything you can think of which can be reserved by one individual.

  The module provides the possibility to create reservations for other users (dependend on the permissions), and provides also restrictions in the maximum number of reservations a user can make and a maximum time a reservation can be made in advance.

  There is NO support for payment, booking and what ever one could imagine beyond the pure and simple reservation, and it is also NOT intended to create more than this simple functionality.

MERCI.

  ... can extend any content type into a list of unique reservable items (like studios) or buckets of interchangeable items (like DV cameras). We followed the approach used by Organic Groups, Feed API, and Scheduler and added MERCI's configuration to the Edit tab of those content types.

Resource Conflict.

  ... allows for users to book resources for use during events. For example, a student can book a microscope for use within their lab.

Booking Systems Comparison

Refer to Comparison of Booking System modules for a comparison of various modules related to bookings / reservations.

This comparison contains some other modules (not mentioned in my answer here) that might be worth considering also, e.g. in case of requirements that are slightly different (as compared to those in the question here).

How to pick the module that fits best

I've ordered my recommended shortlist above by number of reported installs. Though that is often a good first indicator, it should not be used as the only criterium to pick a module.

So do your homework to pick the right one for you. E.g. by using criteria such as those I often use for selecting module, as mentioned in the community documentation about Maintenance Scorecards.

Here is the intro about it (from that page):

  ... contains a list of 23 criteria (=28-5) that might help to evaluate
  the maintenance and support of contributed modules. Below is an
  attempt to apply those criteria to each of the native charting modules
  ...

Obvious, these scorecards are related to "charting modules", but the same criteria are applicable, IMHO, wheneven you need to decide between multiple modules.

Disclosure: I'm the author of that community documentation page (partially inspired by the 28 criteria in the issue linked near the beginning of the scorecards paragraph).


Privatemsg through a Multi Site configuration?

Multi-site is just a way to share code. Different sites are completely separated and know nothing of each other*.

There might be ways to theoretically do this using special recipient types, it would have to use services (or raw SQL queries) to another drupal installation, multi-site or not. And it wouldn't be easy to implement and likely also be very slow.

*With the exception of shared tables, but if you'd share your users, you wouldn't have different users in the first place.


determine which template file a contrib module is using?

I thing something like this could tell you what is going on :

$reg = theme_get_registry();
dpm($reg['commerce_order_ftp_export']);


How to set shipping price to 0 when a specific field of product is enabled or has specific value

How about this: In shipping calculation rule see if can get the following conditions.

Use execute php code, check in the php if can use $commerce_order
If can then loop through all product line items in the order load them check the field value.
On basis of condition return True so implement the action or false to not.


Why would !order-summary token be available/unavailable depending on payment method?

Of course I find the issue after posting the bounty :s

This Commerce Message issue explains that the problem is that some payment methods need to do a postback, which is executed as anonymous user. This apparently means that the view which returns the order summary (commerce_cart_summary) is also executed as anonymous and returns no results, so the token remains empty. The commerce_payment_example method does not have this problem because it doesn't rely on any external feedback.

The workaround to disable SQL rewriting in the commerce_cart_summary view works (I haven't tested the patch yet).


Sorting a new column on task list on open atrium

I figured it out.

Go to adminstration/structure/views/
Click Edit for Open Atrium Worktracker
In Filter Criteria click add, then select column of choice
Click the "Expose this filter to visitors, to allow them to change it"


How can I call javascript from another site?

You could add the JS in code.

e.g:

/**
 * Implements hook_init
 */
function mymodule_init(){
  if ($node = menu_get_object('node')) {
    if ($node->type == 'my_type') {
      $items = field_get_items('node', $node, 'field_my_nid_field');
      if (!empty($items[0]['value'])) {
        $nid = filter_xss($items[0]['value']);
        drupal_add_js('
        widgetContext = { "url": "http://theirsite.com/mysite/'.(int)$nid.'", "width": "600", "height": 200, "widgetid": "web_widget_iframe_hash" };
        ', array('type' => 'inline', 'scope' => 'header'));
      }
    }
  }
}

The other static script tag can be added in a custom Full HTML block / content pane or similar, where you want the content to display.


What is the reason of hidding comments and links in node.tpl.php?

You don't need to remove them from your node.tpl.php -- but that is always an option.

I recommend a better solution, however.

First, you can check out this resource to read more about how to deal with fields when they are being displayed on a node.

A really good solution (and one I always recommend) is using modules like Display Suite to customize the fields on your content type. You can customize the create/edit form as well as you can control which fields you want to be visible when visitors are looking at nodes.


It depends on how the developer did on the website. It could be very difficult if it is done by a developer who is not familiar with Drupal. For your situation, I can share some possible places of code for your reference.

Drupal developer may do it in:

Preprocess function in theme template.php
Field pre render function in custom module.

PHP developer may do it in:

PHP condition code in node.tpl.php

Frontend developer may do it in:

DOM manipulation in theme js file.


Filter View on Partial Term Name Across All Vocabs

sorted. Add relationship Taxonomy term: Name in a TERM view and viola


Adding taxonomies to node gallery and using views to display

I have made a plan. I have ignored the redirection for now. What I did was set up a view for each gallery-page/term that there should be. Each view was linked to a specific term that each gallery item is associated with.

The term association was made by adding a field to the gallery content type using the field type term reference. This allowed me to set the terms required for each gallery.

After setting up each of the fields I wanted to display including the path and additional settings, I got it to work displaying only the galleries in a specific taxonomy.

The solution is actually pretty straight forward. I would have liked to have used arguments, however I couldn't get that working. At least the problems described above have been resolved.


Generate Taxonomy Terms from Node Content Automatically

I haven't achieved such content based node tagging programatically on my own. But used a module named Open Calais which uses the Thomson Reuters web service to generate and classify taxonomy term from node body content. Though it was available with free key use the number of API calls were limited. This with More Like This might serve some purpose in case you are running on Drupal 6.

Another module that might be of interest is Autocategorise which appears to do the same by subjecting node content to regular expression rather than a web service API like calais. If you wish to code the logic yourself examining the module's code might give some ideas on implementation.


"Access Denied" to the Admin on Old and New Install

Are you login as an admin. I mean UID = 1 ?
Try to reset the super user password and loggin again.

DRUPAL 6 and below: UPDATE users SET pass = MD5('givememypasswordback') WHERE uid=1;
DRUPAL 7 - https://drupal.org/node/1023428

Also check error logs if you think its an internal permission issue.


Check out field_get_items(), or to go a bit more advanced (and more 'meta'), use EntityFieldQuery (see examples here).

But, if you're doing this outside of a loop or something, it's often easiest to do a full node_load(), as you can just grab more fields out of there when you need to (in the future) without having to add a bit more code.

My rule of thumb is this: if I only need to load one or two nodes for a particular operation, and the node doesn't contain more than 10-15 fields, I'll just do node_load(). Much more convenient when you don't need to worry about the extra 50ms or so... (for smaller node objects, of course. It's different if you have a node with 25 fields attached!).

[Edit: Just realized field_get_items() still requires the node object itself... which defeats the purpose.]


Multiple Content Types sharing a lot of common fields

If the content types share the majority of fields, it makes sense to keep them as a single content type.

I'd suggest adding a field for "Event type" or similar to record what sub-type of Event the content is and perhaps group the additional fields in fieldsets.

You can then show/hide the additional relevant fields with hook_field_attach_form (or equivalent) by setting '#access' => FALSE on the relevant field.

If you don't mind showing the fields to the user, you could also use a module like conditional_fields (D7 dev works ok)


Can a database serve two different installations on localhost?

There is no problem using a single database to serve multiple applications (including multiple Drupal instances).  However, they need to be completely separate instances. You cannot use a Drupal 6 database instance as part of a Drupal 7 instance.  You must set up a clean Drupal 7 instance, and then migrate the content from a Drupal 6 instance into it, using the standard procedures for upgrading from Drupal 6 to Drupal 7.

To do this, you use something known as "table prefix".  When you install Drupal (both 6 and 7) on the database setup page you get during installation, you can expand a tab to get to Advanced options.  This gives you access to some extra options, including "table prefix".

The "table prefix" allow for multiple instances sharing the database.  For instance, if your existing Drupal 6 site is set up without a table prefix, you can use the table prefix d7_ to set up a Drupal 7 configuration in the same database that will not interfere with your Drupal 6 configuration.


How to use a hyphen instead of an underscore when using the content type as a Views argument? (Hackable URLs)

If you have only six types, the quickest solution may be to create 6 page displays for your view, eg, one might be:

classifieds/for-rent/%/%

and then override the filter on this display and add node type for_rent.  Then create another page view, say:

classifieds/for-sale/%/%

and filter that page display on node of type for_sale, another:

classifieds/personals/%/%

etc for personals.

ADDITION:

You could create a menu item and do this yourself, eg:

function YOURMODULE_menu() {

  $items=array();

  // any other menu items here

  $items['classifieds/%/%/%'] = array(
    'title' => 'YOUR TITLE',
    'page callback' => 'YOURMODULE_classifieds',
    'page arguments' => array(1,2,3),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function YOURMODULE_classifieds($type, $tax, $title) {

  $type=str_replace('-', '_', $type);

  return views_embed_view(NAME_OF_YOUR_VIEW, NAME_OF_DISPLAY, $type, $tax, $title);

}

Now, this was just typed in off the top of my head so there may be subtle issues here, but the basic point is to create a menu item that responds to:

classifieds/SOMETHINGWITHADASHINIT/bar/baz

that gets the dash turned into an underscore for Drupal's internal name of the type.  So, you could "just" create a block display in your view and remove all of View's paths and call it manually like the above.  That, or ask that Views have a "transform underscores into dashes" checkbox like the "transform spaces to dashes" it has for taxonomy terms (which it might already have in D7 :)


Embedding a webform inside a node content

There are several ways to do this.  The method I normally use it to make a custom Panel page for my node.  The content area will contain the "node being viewed" as well as a custom block that renders out my form.

The easiest way, though, is to use the Webform module, and you can build your forms with the UI and easily attach them to a content type.


You can use as an example the taxonomy term view, which is in the D8 standard installation:

admin/structure/views/view/taxonomy_term

Two steps are necessary. First define the parameter in the path. For the taxonomy term this is:

Path

taxonomy/term/%

This view will be displayed by visiting this path on your site. You may use "%" in your URL to represent values that will be used for contextual filters: For example, "node/%/feed". If needed you can even specify named route parameters like taxonomy/term/%taxonomy_term

Then add a contextual filter in the advanced section, which will process this parameter:

CONTEXTUAL FILTERS
Add contextual filters
Content: Has taxonomy term ID

For the details see the example in your drupal installation. In your case you would use the referenced Pages node id.

If you want to use the view as a block, you cannot define the parameter in the path setting of the page. Then you have to switch in the contextual filter to "Provide default parameter" and configure the parameter from URL.


How to load a apache solr document and send it for reindex after editing is done in drupal 7

When using the apachesolr module, nodes are automatically marked for reindexing after an edit.  So there is nothing you need to do.

If for some reason you need to manually mark a node, the code is

apachesolr_mark_entity('node', $nid);


How to create a homepage exposed views search box drupal 7

Add filters for this fields to your view.
Mark this filters as exposed.
Go to blocks and make sure your exposed filter is visible.


Pictures are not responsive on Firefox & Internet Explorer, Using grid on views

I use the Adaptive Image module. It gives you an adaptive behavior you can select when on Admin>Configuration>Image Styles. In other words, you'll need to create an image style with the new adaptive behavior (it should appear in the pick list after you install the module), or alternately, add the adaptive behavior to existing image styles. Once you've done that, you just need to use the adaptive image style in the view, either by adjusting the image field settings, or by changing the settings on the display type fields if you're using content or rendered entities. For the most part, I found that doing the above steps gives me responsive images, but I sometimes have to tweak my CSS also.


If you are using the Varnish HTTP Accelerator Integration module, you can use the varnish_expire_cache() function, that accepts specifics paths like nodes or could be for other paths too.


hook_views_pre_execute() query not running (or being overwritten)

The reason nothing's changing is because you're just running db_query(), not actually assigning it to anything. If memory serves you need to assign your new query to $view->build_info['query'] (but that might be for Drupal 6).

Also you won't unfortunately be able to use a vanilla db_query for this (as far as I know), because Views is expecting a db_select() object.

You can test this pretty easily by running the following two statements:

// Breaks the view.
$view->build_info['query'] = db_query('SELECT nid FROM {node}');

// Does not break the query (but results are wrong obviously).
$view->build_info['query'] = db_select('node', '')->fields('n', array('nid'));

I would look at re-working your query into a dynamic db_select() and then assigning it as in the above example, you should get more joy.


Change menu link before rendered in mmenu module

You want to implement hook_translated_menu_link_alter() and hook_menu_link_alter(&$item). This hook is not called for all menu items.

According to the API documentation:

It is only invoked if $item['options']['alter'] has been set to a non-empty value (e.g., TRUE). This flag should be set using hook_menu_link_alter().
Here's an example:

function MODULE_menu_link_alter(&$link) {
  if ($link['link_title'] == 'foo') {
    $link['options']['alter'] = TRUE;
  }
}

function MODULE_translated_menu_link_alter(&$link) {
  if ($link['link_title'] == 'foo') {
    $link['href'] = 'node/5';
  }
}

Some notes

You may want to filter additionally by $link['menu_name']; MODULE_menu_link_alter() is invoked on cache clear for all menus items declared via hook_menu().
For menu items created via web it is only invoked on save, that is, for this code to take effect you need to edit-and-save menu links you want to alter.


How do I dump variables to the screen when running PHPUnit tests?

Recent versions of PHPUnit swallow output.  To get around this, you need to run with the --debug flag, eg

$ ../vendor/bin/phpunit --debug modules/migrate/tests/src/Unit/process/FormatDateTest.php

Then you can see printed output.

Also note that PHPUnit will skip tests with output in them with the default phpunit.xml file, because it will deem them risky.   To avoid this update the beStrictAboutOutputDuringTests="false" setting and your tests will run.

You can also use the $message parameter to output something when an assertion fails.


Need to disable Auto Preview in views for local development in settings.php

This should do it, make sure you clear cache:

$config['views.settings']['ui']['always_live_preview'] = 'false';


block_html_id for view comes with uuid drupal

The answer is in the following:
Views Block's machine name is being "hashed" (?)

It hashes block view name if the view name is larger than 32 chars


To update Drupal using Composer, you just need to move the "drupal/core": "~8.1" line from the replace section to the require section. At the end the content of the composer.json file is like the following one.

{
    "name": "drupal/drupal",
    "description": "Drupal is an open source content management platform powering millions of websites and applications.",
    "type": "project",
    "license": "GPL-2.0+",
    "require": {
        "composer/installers": "^1.0.21",
        "wikimedia/composer-merge-plugin": "~1.3",
        "drupal/core": "~8.1"
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "config": {
        "preferred-install": "dist",
        "autoloader-suffix": "Drupal8"
    },
    "extra": {
        "_readme": [
            "By default Drupal loads the autoloader from ./vendor/autoload.php.",
            "To change the autoloader you can edit ./autoload.php."
        ],
        "merge-plugin": {
            "include": [
                "core/composer.json"
            ],
            "recurse": false,
            "replace": false,
            "merge-extra": false
        }
    },
    "autoload": {
        "psr-4": {
            "Drupal\\Core\\Composer\\": "core/lib/Drupal/Core/Composer"
        }
    },
    "scripts": {
        "pre-autoload-dump": "Drupal\\Core\\Composer\\Composer::preAutoloadDump",
        "post-autoload-dump": "Drupal\\Core\\Composer\\Composer::ensureHtaccess",
        "post-package-install": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup",
        "post-package-update": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup"
    },
}

I was used to run drush upc to update Drupal, but that overriden my composer.json file, and the vendor directory. As consequence of this, I should run composer update all the times to update the content of the vendor directory.

Now, using Composer to update Drupal, I can also use it to download/update the modules I am using.

The composer.json file I am using is the following one.

{
    "name": "drupal/drupal",
    "description": "Drupal is an open source content management platform powering millions of websites and applications.",
    "type": "project",
    "license": "GPL-2.0+",
    "require": {
        "composer/installers": "^1.0.21",
        "wikimedia/composer-merge-plugin": "~1.3",
        "drupal/core": "~8.1",
        "drupal/imagick": "8.1.*@dev",
        "drupal/mollom": "^8.1",
        "drupal/honeypot": "^8.1"
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "config": {
        "preferred-install": "dist",
        "autoloader-suffix": "Drupal8"
    },
    "extra": {
        "_readme": [
            "By default Drupal loads the autoloader from ./vendor/autoload.php.",
            "To change the autoloader you can edit ./autoload.php."
        ],
        "merge-plugin": {
            "include": [
                "core/composer.json"
            ],
            "recurse": false,
            "replace": false,
            "merge-extra": false
        }
    },
    "autoload": {
        "psr-4": {
            "Drupal\\Core\\Composer\\": "core/lib/Drupal/Core/Composer"
        }
    },
    "scripts": {
        "pre-autoload-dump": "Drupal\\Core\\Composer\\Composer::preAutoloadDump",
        "post-autoload-dump": "Drupal\\Core\\Composer\\Composer::ensureHtaccess",
        "post-package-install": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup",
        "post-package-update": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup"
    },
    "repositories": {
        "drupal": {
            "type": "composer",
            "url": "https://packagist.drupal-composer.org"
        }
    }
}

Apart from moving that line as I said, I also executed the following commands.

composer config repositories.drupal composer https://packagist.drupal-composer.org
composer require drupal/honeypot
composer require drupal/mollom
composer require drupal/imagick 8.1.*@dev

The first allows me to require Drupal modules and update them.

The last time I tried, the Drupal official repository was still in alpha stage, and it gave me problems with modules that declared themselves as Composer packages, but not setting the package type (i.e. drupal-module). I hope they fixed the problem, now. For the Drupal Packager repository, the commands to use are the following.

composer config repositories.drupal composer https://packages.drupal.org/8
composer require drupal/honeypot
composer require drupal/mollom
composer require drupal/imagick 1.*@dev

If you were already using https://packagist.drupal-composer.org, and you want to replace with the official Packagist site, you need to replace the first command with composer config repositories.0 composer https://packages.drupal.org/8, which works if you don't have other repositories, basing on Using packages.drupal.org.

Notice also that packagist.drupal-composer.org is scheduled to be deprecated in January 2017 (or when the official Package Repository from Drupal.org is ready).


How to only allow alphabets and spaces in the middle in Profile2 field

I've found the Field validation module that works! I used this regex expression:
^[\x{00c0}-\x{01ff}a-zA-Z0-9]+([- '][\x{00c0}-\x{01ff}a-zA-Z0-9]+)*$

This way I can allow international names and only allow spaces, hyphens and apostrophes in the middle of the name.
It was based on combining

1 https://stackoverflow.com/questions/275160/regex-for-names , and
2 https://stackoverflow.com/questions/2525327/regex-for-a-za-z0-9-with-dashes-allowed-in-between-but-not-at-the-start-or-e


Loose compression for all images directly from Drupal

You're looking for this but in D8 - https://www.drupal.org/project/imageapi_optimize. You can still use the tools to do it manually.

PNG - Use https://pngquant.org/ first with these settings --speed=1 --quality=90-99 --force --ext .png and then https://github.com/subzey/zopfli-png
JPG - https://github.com/mozilla/mozjpeg and then https://stackoverflow.com/questions/5579183/jpegtran-optimize-without-changing-filename

EDIT: This new D8 project just appeared https://www.drupal.org/project/file_processor


How can I add extra text fields to the image field when adding/ editing nodes?

Image is a file entity and to make it fieldable you can use this module:

File Entity (fieldable files)

From the documentation:

  File Entity

  The File entity module extends the capabilities of the core File
  module.

  File Entity defines 5 File Types - Application, Audio, Image, Text,
  Video. The Media module adds an additional File Type - Other
  (currently these File Types are hard coded and cannot be changed).

  When files are uploaded they are automatically assigned the
  appropriate File Type based on the file suffix.

  The File Types as currently defined are:

  Images - .png, .gif, .jpg, .jpeg, .ico Videos - .mov, .mpg, .flv,
  .m4v, .mp4, ,ogg, .ovg, .wmv Sound files - .mp3 Text - .txt Document
  files - .doc, .xls, .pdf, .ppt, .pps, .odt, .ods, .odp Other - ??

  Each File Type can have fields. This allows for additional information to
  be stored along with a media file such as Title, Description, Taxonomy
  References, Node References, Location, Date created, License
  information etc.


Drupal recommended-project missing Drush

It is important to understand the distinction between the Drupal core project templates and the drupal-composer project template.

The Recommended and Legacy project templates are maintained by Drupal core. As a result, it only includes those components validated by the core maintainers to be very stable and needed by most Drupal users. The bar for this is very high, and the complexity of the component plays into the decision. For example, Drush is very stable and used by most Drupal users, but it is a fairly large and complex project, and therefore has not been added to a core project template. Use the Recommended project if you'd like your web root inside a "web" directory, or the Legacy project if you would like your web root at the project root.
The drupal-composer/drupal-project template is maintained by the community. It contains more components that are likely to be useful to a wide range of users. If a bug or configuration problem is found with this project, then it must be reported and fixed through the community repository on GitHub.

The latest version of drupal-composer/drupal-project uses the same core scaffold components as the drupal/recommended-project Composer template provided by Drupal core. It is safe to start with the drupal-composer/drupal/project template for your site.

If you add Drush to your site, either by starting with drupal-composer/drupal-project, or by adding it manually to the drupal/recommended-project, then the Drush binary will always be installed inside the vendor directory. This will be inside the web root for the Legacy project, or outside the webroot for the Recommended project, and for drupal-composer/drupal-project.

If you decide to start with the Recommended project and add Drush, you should also look at the composer.json for drupal-composer/drupal-project and see if there is any configuration in the "extra" section that you might want to copy over for your site.


How to add “Download file” link in Drupal 7 files attachment when chosen table formatter

use File Force Download module to add download functionality to your site. It has field formatter, views integration, good api and etc..

If you want to create a download link programmatically then you can generate download link such way:

l('Linktext', file_force_create_url($image['filepath']), array('query' => array('download' => '1'))).


How do i create a breadcrumb based on Main Navigation Menu in programatically?

Menu breadcrumb module create breadcrumb based on a menu. Maybe this could help.


How to Rename "Request new password" link?

The String Overrides module is a good suggestion if you have many strings, or need to constantly alter them, but you can also achieve this by editing the string overrides section of your settings.php file.

Simply uncomment the section so it looks like this:

$conf['locale_custom_strings_en'] = array(
  'Request new password' => 'MY CUSTOM TEXT FOR A NEW PASSWORD',
);


drupal module secure pages toggles between http and https on reload

The source of the problem could be in several places, depending on which webserver you're using, how it's configured, etc.

Are you using Apache with mod_ssl?  NOthing else 'in front', like nginx doing the SSL handshaking instead?

In any case, I'm guessing that your webserver's not consistenly serving up the required server var.  In 'securepages.module', there's a check for

return (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? TRUE : FALSE;

Not knowing your webserver config, find out what your webserver is doing.  add,

<?php
 phpinfo();
?>

to your pages and look to see what the values of

$_SERVER['HTTPS']
$_SERVER[SERVER_PORT]

are.  Or simply print them out directly ...  Check if/how those values toggle on page refresh.

I'm suspicious of caching, too.


You should conigure the max number of menu level in block structure


How to trim trailing spaces from labels of radio buttons/select list elements

Yeah, this is a known issue.  The form.inc file from /includes/form.inc which themes form labels outputs the following for labels:

$t('!title !required', array('!title' => $title, '!required' => $required))

The offending space is the space between '!title' and '!required', where !title will contain the actual label text and !required will contain a '*' for fields that are required to be filled in the form...

In any case, this is all in core, and there is an initiative to fix it for Drupal 8: https://drupal.org/node/1623574.  Definitely follow that or add your voice to the mix! Any fix will not be back-ported to Drupal 7, however, because lots of themes rely on that extra space and will be messed up if it is removed.

What you can do in your own case, though, is override the core hook_form_element_label theme function.

So, in your custom theme, just create the necessary function in your template.php file:

function YOURTHEMENAME_form_element_label($variables)
{
}

Now just copy the entire function from /includes/form.inc and just change the very last return statement to not include the space unless there is a required star ('*') to go after the label.  Your new and improved return should be:

return ' <label' . drupal_attributes($attributes) . '>' . $t('!title!required', array('!title' => $title, '!required' => $required ? ' ' . $required : '')) . "</label>\n";

That should do it!!  However, make sure you click around your site and check whether this messes anything else up before going in production.  You may see some labels mashed into other stuff without the space, again because some themes have relied on it!  And make sure to clear cache so the new function is picked up.

Let us know if it works...


How do you use tabledrag API in a multi-page environment?

I doubt anyone else will have a useful answer. But the DraggableViews module for Drupal 6 showed 3 items from the previous and next Page(s) in paged results. Allowing you to drag an item from the previous page into the previous or next page.

Now if you have hundreds of items I'm not sure how you would skip multiple pages at once -- but looking at how they did this could help you to extend the Drupal 7 Draggable Views module to achieve the functionality you want.

Unfortunately the Drupal 7 DraggableViews does not support this yet.

Proof of this is in this issue queue:
https://www.drupal.org/node/1458870


You need to edit your php.ini and add or uncomment the following line:

always_populate_raw_post_data = -1

If you've still that error after restarting Apache, you probably edited the wrong file. So as admin, go to Reports/Status/PHP (at /admin/reports/status/php) and double-check your value for always_populate_raw_post_data and your php.ini path.

Note that the above setting will only avoid the warning, see: Changes to PHP-5.6 and this SO post.


You should already have a template suggestions available like :

<!-- FILE NAME SUGGESTIONS:
   * node--2--teaser.html.twig
   * node--2.html.twig
   x node--BUNDLE--full.html.twig
   * node--BUNDLE.html.twig
   * node--teaser.html.twig
   * node.html.twig
-->

Make sure you have settings.yml set to twig.config: { debug: true ... and you will see the suggestions in the source.
You can set suggestions for any hook like:

function MODULE_theme_suggestions_node_alter(array &$suggestions, array $variables, $hook) {
 $node = $variables['elements']['#node'];
 $type = $node->bundle();
 $view_mode = $variables['elements']['#view_mode'];

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


Adding Search Block to Bootstrap 3 Navbar

I had the same feature request.
In mytheme/template.php I've added

/*
 *  Preprocess page.tpl.php to inject the $search_box variable.
 */
function mytheme_preprocess_page(&$variables){
  $search_form = drupal_get_form('search_form');
  $search_box = drupal_render($search_form);
  $variables['search_box'] = $search_box;
}

/*
 *  Form alter to add missing bootstrap classes and role to search form.
 */
function mytheme_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_form') {
    $form['#attributes']['class'][] = 'navbar-form';
    $form['#attributes']['role'][] = 'search';
  }
}

In mytheme/templates/page.tpl.php I've added

  <?php print $search_box; ?>

After the

 div.

There still was a problem with a float:left applied to secondary links menu (instead of the proper boostrap navbar-right.
So, for a quick workaround, in mytheme/css/style.css I've added:

@media(max-width:768px){
  ul.secondary{
    float:none!important;
  }
}


What you see in the log is malicious, so: Yes, somebody is rattling the doorknobs on your site to see if some door is not locked.

However, what you see is nothing unusual. I think you'll find similar entries in every watchdog log for a Drupal site that is "in the wild" (i.e. outside of a firewall).

Should you take more measures? IMHO, no. There is nothing in the messages you've posted that indicates that you're being targeted. These are random shots in the dark by script-kiddies - and they're all misses.

One of the reasons we use Drupal is because the core is pretty resistant to this sort of thing out-of-the-box.  Just make sure you keep your site updated. And don't install experimental or badly maintained contributed modules without checking them for security holes yourself.


I think the lock feature is to indicate that you are editing the manuscript. When you are ready editing, and have uploaded the next version, you can unlock it.


You should use d for the day of the month. Using t php displays the number of days for the given month. Reference: http://php.net/manual/en/function.date.php


How do I pass parameters to the form builder?

The parameter has to have the same name in routing.yml and build method. And when using parameters in forms you have to set a null value in the parameter list:

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


How to theme the taxonomy add/edit term form?

Use hook_theme() inside your theme's template.php file to set a custom template file (tpl.php) for the taxonomy add and edit forms. However, your theme needs to be set as the Administration Theme, even if Use the administration theme when editing or creating content is not checked.

The taxonomy module implements only one form template file for the taxonomy add and edit forms for all vocabularies. In other words, the taxonomy module does not provide, on its own, a way to have a different taxonomy form template file for a specific vocabulary. However, it is possible for you to add this capability by implementing hook_form_alter() within your theme's template.php file (explained below).

PSA: clear your site's cache after making changes to your templatate.php file.

This is what would be in the template.php file for the theme_name administration theme if you wanted to theme the taxonomy add and edit forms for all vocabularies:

/**
 * Implements hook_theme().
 */
function theme_name_theme($existing, $type, $theme, $path) {
  $items['taxonomy_form_term'] = array(
    'render element' => 'form',
    'template' => 'taxonomy-form-term',
    'path' => drupal_get_path('theme', 'theme_name') . '/templates',
  );
  return $items;
}

$items['taxonomy_form_term'] = array(...: The key taxonomy_form_term indicates the values inside the array are to theme the taxonomy add and edit forms. This key is defined by the taxonomy module.
'render element' => 'form':  $form will be the variable that holds the renerable form array. Note that the words "render path" are separated by a space, and not an underscore.
'template' => 'taxonomy-form-term': The name of the template file without the extension. When the extension is added, the name of the file will be taxonomy-form-term.tpl.php.
'path' => drupal_get_path('theme', 'theme_name') . '/templates': The template file will be in the templates sub-directories within the theme_name theme's path. You are not required to use this exact directory, and can omit path from the array if you place the template file directly inside the theme's default path.

When you implement a theme hook, you will also have a preprocess function that you can implement in your theme's template.php file for that theme hook:

function theme_name_preprocess_taxonomy_form_term(&$variables){}

Create a file named taxonomy-form-term.tpl.php in the templates sub-directory of your theme, e.g. sites/all/themes/theme_name/templates/taxonomy-form-term.tpl.php. Use the $form variable for rendering the form.

// Move the Relations fieldset to the top of the form.
print render($form['relations']);
print drupal_render_children($form);

You can use hook_form_alter() to define keys for hook_theme() to theme the forms for specific vocabularies, specific terms, and/or for just the add (or edit) form. You add the keys to the $form['#theme'] array. You can name them whatever you want, but the order that they appear in the array matters. Keys at the beginning of the array take precedence over others, so add them starting with the most specific keys first. taxonomy_form_term,and possibly other keys, will already be in $form['#theme'], so you will need to prepend your keys to the beginning of the array.

/**
 * Implements hook_form_alter().
 */
function theme_name_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'taxonomy_form_term') {
    $term = $form['#term'];
    $vocabulary = $term['vocabulary_machine_name'];
    $tid = $term['tid'];

    $theme_keys = array();
    if (!$tid) {
      // Key to theme the 'add' form for this vocabulary.
      $theme_keys[] = 'taxonomy_form_' . $vocabulary . '_term_add';
      // Key to theme the add form for any vocabulary.
      $theme_keys[] = 'taxonomy_form_term_add';
    }
    else {
      // Key to theme the 'edit' form for this term using its term id.
      $theme_keys[] = 'taxonomy_form_term_edit_' . $tid;
      // Key to theme the 'edit' form for this term for this vocabulary, using
      // the term's name (after replacing non-alphanumeric characters with "_").
      $term_name = preg_replace('/[^a-z0-9]+/', '_', strtolower($term['name']));
      $theme_keys[] = 'taxonomy_form_' . $vocabulary . '_term_edit_' . $term_name;
      // Key to theme the 'edit' form for this vocabulary.
      $theme_keys[] = 'taxonomy_form_' . $vocabulary . '_term_edit';
    }
    // Key to theme the add/edit form for this vocabulary.
    $theme_keys[] = 'taxonomy_form_' . $vocabulary . '_term';

    // Add the theme keys to the beginning of the #theme array so they have
    // precedence over any preexisting ones.
    $form['#theme'] = array_merge($theme_keys, $form['#theme']);
  }
}

Implement the new theme hooks in your hook_theme(). For example, if you wanted to theme the edit form for the my_vocabulary vocabulary:

$items['taxonomy_form_my_vocabulary_term_edit'] = array(
  'render element' => 'form',
  'template' => 'taxonomy-form-my-vocabulary-term-edit',
  'path' => drupal_get_path('theme', 'theme_name') . '/templates',
);

You will also have a new preprocess function that you can implement in your theme's template.php file:

function theme_name_preprocess_taxonomy_form_my_vocabulary_term_edit(&$variables){}

Create the taxonomy-form-my-vocabulary-term-edit.tpl.php file in the templates sub-directory of your theme, and use the $form variable to render the form.


What's the best way to implement a system to allow the end-user to download and buy documents?

There's a module in progress that provides that for Drupal Commerce, here:
http://drupal.org/sandbox/recrit/1118266

You could use it as a starting point, or just for inspiration.


Use views as radios (or check-box) options in drupal forms

You can do it using one of listed module :

Views attach

  This module provides two additional Views display plugins, "Profile"
  and "Node content". These displays do not display on a page but get
  "attached" to either a user page or nodes of specified types.

Entity Views Attachment

  "Eva" is short for "Entity Views Attachment;" it provides a Views
  display plugin that allows the output of a View to be attached to the
  content of any Drupal entity. The body of a node or comment, the
  profile of a user account, or the listing page for a Taxonomy term are
  all examples of entity content.

View field

  View field provides a field that holds a reference to a View and
  renders it whenever the entity containing the field is displayed.


Why do I get a redirect loop (302) when using path-auto patterns on taxonomy terms?

It seems to have been due to caching and the rebuilding of the alias table.

Once I left it for a while and cleared caches it was working as expected.


Disable language prefix for non-default languages

Path redirection from old paths to new may be a solution (workarround really). This is compatible with SEO https://drupal.org/project/redirect


Datepicker widget. How can I add some variable javascript code from my module to configure the date popup calendar?

You can add it with #datepicker_options, e.g.:

$form['date'] = [
  '#type' => 'date_popup',
  // ...
  '#datepicker_options' => [
    'minDate' => 0,
  ],
];


Is there any way to cancel Panels' overlay edit windows?

I did some research and looked into Panels 3 code so far I don't see any nojs fallbacks. You can also check if there are fallbacks when you try to disable Javascript in the browser.

This may not be the answer on how to disable Panels modals but you may increase PHP, MySQL and or Apache settings and increase memory to your local host.


Enable/ disable „Display author and date information“ per node?

You can override the variable display_submitted in a preprocess hook:

mytheme.theme:

function mytheme_preprocess_node(&$variables) {

  // check if this is the right content type where the field exists
  if ($variables['node']->getType() != 'article') {
    return;
  }

  // plain field
  if ($variables['node']->field_where_to_publish->value == 'public') {
    $variables['display_submitted'] = FALSE;
  }

  // taxonomy field
  $field = $variables['node']->field_where_to_publish;
  if (!$field->isEmpty() && $field->entity->label() == 'public') {
    $variables['display_submitted'] = FALSE;
  }

}


"File (Field) Paths" and "Media" modules: files not saved in the intended folder

No definitive answer so far, but I should note that I have been able to make this option work again simply by enabling the (very intimidating) option "Active updating" in the field's settings. (So in admin/structure/types/manage/[content-type]/fields/[field-name])

The "File (Field) Paths" developer warns that "This feature should only be used on developmental servers or with extreme caution", but since it's the only solution I've found so far, I'm going to keep this option enabled for now.

Hope this helps someone.


This looks more like a css issue than a drupal issue.
I am not sure if you are looking for some drupal hooks to solve this problem. But adding this css will solve the issue.

 .region-links-region{
      overflow: hidden;
  }

If this does not work, you can try overflow: hidden !important;


Weird redirect on taxonomy term edit page

Did you try to edit Taxonomy Term view /admin/structure/views/view/taxonomy_term I'm having issues with editing / deleting / translating taxonomy terms because I've edited taxonomy_term view. Disable taxonomy_term view and edit/delete should work.


How to invite multiple users when editing user account?

You question consists of actually 2 questions:

... have this field on my user/edit page.
... enter multiple e-mail addresses separated by , .

To answer the 2nd question (= ... enter multiple e-mail addresses separated by , ), have a look at the issue about Multiple emails support for Invite form. The patch contained in comment nr 5 of it can be used to
create a new invite entity for each email address. Attention: it seems that this patch still needs to be rerolled for the latest dev version (which is also what explains the "needs work" status of this issue).


How to get node content in an sql query?

Drupal 7

In Drupal 7 body content is saved in field_data_body and field_revision_body tables.

So example query to fetch title and body would be:

SELECT title, r.body_value, n.changed FROM node n LEFT JOIN field_data_body r ON n.nid = r.entity_id AND n.vid = r.revision_id

To query via drush, run drush sqlq following by above query.


You can't have multiple routes on the same path with different access checks, it just doesn't work like that.

If you want something like this, then you need to create your own route, check permission/role of the user there and then display the right view based on that.


View conditional logic based on dropdown value

No need to {{ fields.field_banner_type.content }} inside if statement use fields.field_banner_type.content like the following:

{% if fields.field_banner_type.content == "1" %}
  {# wrapping link #}
{% else %}
  {# no wrapping link #}
{% endif %}

For more info See Twig if Documentation


drupal 7.34 cannot rearrange form component and others

Very lucky....,
I found the answer to solve the problem (related to missing misc/jquery.cookie.js) from  this discussion https://www.drupal.org/node/1052372

To solve that: Configuration > Development, enable Aggregrate Javasript file

Now it just works perfectly as in the previous versions. Thanks Drupal developers.


I'm still using D6 but I did something similar with jQuery:

Make a mymodule.module file that goes like this:

<?php

function mymodule_form_alter(&$form, &$form_state, $form_id){
  if ($form_id == 'uc_cart_checkout_form'){

    drupal_add_js(drupal_get_path('module', 'mymodule') . '/mymodule.js');

  }
}

The format of your hook_form_alter may be different in 7, but there are tutorials all over the place for this. The point is that you use drupal_add_js (again, format may differ) to cram some javascript onto only the form with the ID you want - your checkout form.

Make a mymodule.info that goes like this:

name = Re-calculate Shipping
description = Use JavaScript to automatically click the Calculate Shipping button at checkout.
core = 6.x
dependencies[] = uc_quote
package = "Example.com custom modules"

(But you're core is 7.x - copy another module's info file.)
And make a mymodule.js file that goes something like this:

$(document).ready(function(){
      $("#edit-panes-quotes-quote-button").click();
      $("#edit-panes-delivery-copy-address").click();
});

$(document).ready(function(){
   $("#edit-panes-billing-billing-zone").change(function() {
      $("#edit-panes-quotes-quote-button").click();
   });
});

$(document).ready(function(){
   $("#edit-panes-delivery-delivery-zone").change(function() {
      $("#edit-panes-quotes-quote-button").click();
   });
});

Note that this just clicks the "calculate" button for the user, but I'm sure that you can work out how to use jQuery to click more things.

Imagine you have a drop-down select with the attribute id="cram".
In your js file you would use $("#cram") to select anything with the ID "cram":

$("#cram").change(function() {

Sticking .change() on the end triggers anything between the brackets after .change when the #cram element changes, such as when a different fruit / rodent is selected. we're triggering a function here, and it is defined in-situ.

Sticking .click() on the end of a selector clicks the selected element.

Enjoy :)


you might try running "composer install" from inside your drush directory.


Note: This does not answer the question of "trying to get the full SQL of the final query that's creating the anonymous pages", but answers the underlying issue.

tl;dr Checking the Advanced Settings > Query > Disable SQL Rewriting option will allow views to return consistent results.

Explanation

The views module (contrib and core) configures views with restrictive entity access enabled by default. This sends the query object through hook_db_rewrite_sql (6), hook_query_TAG_alter (7, 8). Nodes for instance will add in joins to the node_access table, which can be prohibitively expensive on queries.

This is important for sites that use complex entity access where one node may be hidden from view based on node grants/access rights.

However query results will be different when querying entities (such as nodes) depending on if you are logged in. This can be frustrating when building a view as a site builder - what you see is not what you get.

It may not necessary to use SQL rewriting because a view has other access restrictions. Checking the Advanced Settings > Query > Disable SQL Rewriting option will allow views to return consistent results.

This is usually the first thing I do when creating a view unless I specifically need the extra access checks because

It improves performance significantly.
I create selective and filtered views that naturally restrict data using filters, contextual filters and view access restrictions.

Update 2019.06

Note that the views module changed the label for this setting from "Disable SQL Rewriting" to "Disable Access Checks".


Views exposed filter by season from date field (date range group as month only?)

You can create the season date ranges and name them by using the Grouping Exposed filter option.
You can find it in the regular Date filter, select Grouped filters instead of Single filter for the Filter type to expose option.
Set the operators to Is between and enter the dates for your seasons (you can see spring and summer in this screnshot):

Drupal will assume midnight if you ommit the time and only include the date. You can look up the exact astronomical times for the seasons if you like :)
Be careful not to exclude some results if you use the same date in separate grouped options but not the same time.


https://drupal.org/project/advagg/ should solve this issue. Odds are the cached page is older than 30 days (limit of CSS/JS aggregates in D7 Core).


Found a solution @ https://www.drupal.org/node/2085879

Where you can use the patch by agileadam @ https://www.drupal.org/files/issues/timefield_feeds_support-2085879-6_7.x-1.0-alpha2.patch

On top of which you can also apply a patch from pontus.froding found @ https://www.drupal.org/files/issues/0001-adds-weekly-repeat-to-times.patch which also as an added bonus adds the weekday repeating to the import

The patch is still to this date not imlemented into any release and the issue of time field not showing up in feeds was that Feeds doesn't know the field type and the Timefield module didn't have any feeds hooks in it, to make feeds module aware of it.

Implementing this patch manually (for now) seems to be the only solution.


This is commonly a result of loading theme javascript before it's dependencies.

If your theme lists multiple external js dependencies, or just has multiple custo. Javascript files, you may need to assign weights to establish a load order. Refer to
https://www.drupal.org/docs/8/theming/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme

Likewise, if your theme depends on other javascript provided by other modules, be sure to list those dependencies in your theme.info.yml file.

After making any of the above changes, clear Drupal caches with aggregation turned on and retest.


How can I insert one bespoke item first and one last in a views grid?

Go to admin/structure/views/view/YOUR-VIEWS-NAME/edit/page, click on Theme:Information and you will see bunch of lines. Choose appropriate one depending what exactly you want to override. It can be the whole views display output, or style output, or specific field output.

Each line will have an active hyperlink, clicking which you can copy the content of the new file. Also each line will have file name suggestions.
When you identified the right output, you can choose pick any of the suggested file names on that line: the further to the right, the more specific output.

Create a new template file in your themes template directory, paste the copied content and start modifying the output per your desire.

For example, you could execute your checks just after foreach loop starts:

<?php foreach ($rows as $row_number => $columns):
  if ($row_number != 0) {
    // Here goes your custom modifications.
  }
<?php endforeach; ?>


The Services module will definitely help you with that

  A standardized solution of integrating external applications with Drupal. Service callbacks may be used with multiple interfaces like REST, XMLRPC, JSON, JSON-RPC, SOAP, AMF, etc. This allows a Drupal site to provide web services via multiple interfaces while using the same callback code.

It has CRUD operations for nodes, files, users and plenty more. There's a video presentation available that introduces it properly, and there are loads of code samples on the web to get you started.


This is a display which can be embedded via views_embed_view() or drupal_view() of Twig Tweak.

You can embed other display types, too, for example Page or Block, but the first one generates a route and the second one a block derivate you see when adding blocks to the block layout. So Embed is basically a display type which does nothing until you embed it in code.

The only explanation you can find in Views UI is in the general settings, where there is this checkbox:

  [x] Allow embedded displays

  Embedded displays can be used in code via views_embed_view().

Which by the way is without function and there is an open issue to remove it.


How to do the live streaming of music channels on my site?

You can do this by using Live Streaming module.

How to use?


How to insert HTML that includes an ampersand>

t function is for texts, not for HTML, so it is perfectly allowed to fail. Also, you should not use dynamic strings in t's first argument at all, it is meant to be static.

Whenever possible, you should use renderable arrays. In your specific case this seems a bit difficult, so first thing to, if you are willing to settle for quick and dirty, do would be just forget t and output tag directly.


So it appears that the machine names for my custom content types can not be longer than 24 characters.  As soon I shortened the names they inserted into the view as normal.

It's odd that I have never had that kind of problem before.  But so it is...

Thank you for your efforts!!  It is REALLY appreciated!


$items['admin/structure/types'] = array(
    'title' => 'Content types',
    'description' => 'Manage content types, including default status, front page promotion, comment settings, etc.',
    'page callback' => 'node_overview_types',
    'access arguments' => array('administer content types'),
    'file' => 'content_types.inc',
  );
  $items['admin/structure/types/list'] = array(
    'title' => 'List',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
  $items['admin/structure/types/add'] = array(
    'title' => 'Add content type',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('node_type_form'),
    'access arguments' => array('administer content types'),
    'type' => MENU_LOCAL_ACTION,
    'file' => 'content_types.inc',
  );

This is what exist on node.module, modify to set the type to MENU_LOCAL_ACTION

Hope that help.


No, the database does not update your dump-file afterwards. You should prepare your new site with a database dump.

Then when you are ready to move the site finally you should put your original site in maintenance mode, and dump and import your database with the latest content. In this way you ensure that you will get the most recent content from your old live site.


Is it possible in Views to get parent term of parent term all the way up a tree

use Client-side hierarchical select" module.

1)Force selection of deepest level (If checked the user will be forced to select terms from the deepest level.)

2)Parent (Allows to select a parent term to use only a subtree of a vocabulary for this field.)

3)Labels per hierarchy-level


chmod() and touch() operations not permitted

I fixed this problem by updating owner of files, groups only not enough. Before i has owner as vagrant and group as www-data and now www-data for both.

But it's still strange for my. If i refresh page sometimes file generated and created anyway and warnings went one.


You provide very little information ... Which version of Drupal? (It's Drupal 7 based on the paths.) Which theme have you just enabled causing this problem? It worked before you switched theme, right?

My best guess: You have installed a theme that is a subtheme of Bootstrap without installing the Bootstrap theme itself.


Drupal commerce: there is a way to apply discount to products with some taxonomies elements?

The biggest issue here is that in your taxonomy term comparisons, Rules is going to be looking for taxonomy term IDs. In core Rules, there is no way to show a select list or something similar in the Rules UI for selecting a taxonomy term. There may be a contributed module that adds this functionality; I didn't look.

If you know a term ID, you can use a different condition based on whether the term reference field is single or multi value:

Single value: Data comparison
Multi value: List contains item

Since you're going for usefulness to non-developers / site builders, I'll assume you need something better than that. It appears you might be using Commerce Discount, but I don't know if that's why you've added the tag or not. It offers a simplified interface for building product pricing rules and depends on the http://drupal.org/project/inline_conditions module, which includes a simplified taxonomy term check for product entities.


Lightbox/colorbox slideshow and trigger thumbnails

I found my way of doing this. It's a litle bit tricky, but I hope it helps.

1) Get a View where you grab all node's fields, one of them is the "image" (multi-value).

2) To create a Custom Formatter with the Field API, put this code in a custom module (e.g. mymodule):

/**
* Implements hook_field_formatter_info().
*/
function mymodule_field_formatter_info() {
  return array(
    'mymodule_formatter' => array( //Machine name of the formatter
      'label' => t('Links to images'),
      'field types' => array('image'), //This will only be available to text fields
    ),
  );
}

/**
* Implements hook_field_formatter_view().
*/
function mymodule_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array(); // Initialize the var
  $settings = $display['settings']; // get the settings

  //get first image
  $firstimg = $items[0];
  $uri = file_create_url(file_load($firstimg['fid'])->uri);
  $html = '<img src="'. $uri. '" id="galeria1-button" class="btnSlideshow" href="#" />'. PHP_EOL;

  //get all images and put them as links but without being seen
  $options = array(
    'html' => TRUE, // This tells Drupal that we're sending HTML, not plain text, otherwise it would encode it
    'attributes' => array(
      'class' => 'galeria1',
    ),
  );
  foreach ($items as $delta => $item) {
    $uri = file_create_url(file_load($item['fid'])->uri);
    $html.= l('&nbsp;', $uri, $options);
  }

  //js will make that when you click on first image its as if you were clicking on first gallery image
  drupal_add_js('jQuery(document).ready(function(){jQuery("#galeria1-button").click(function(){jQuery(".galeria1").filter(":first").click();}); jQuery(".galeria1").colorbox({rel:\'galeria1\'});});', 'inline');

  $elements[0] = array('#markup' => $html);

  return $elements;
}


I am just going to answer your first two questions (about file_managed).  Please ask a separate questions for the second set (about file_usage) and about the relation between the tables.

  What is public:// mean here? Does it translate to some root URL like http://example.com/files or similar?

Navigate to Administration » Configuration » Media » File system. Take a look at the value for "Public file system path" (default is sites/default/files).  this is the path to public:// from your site root.

  When there is a directory in the uri, what do they represent?

The path below the public file system root.

So, given the that the public path is the default, public://foobar/image.jpg, this expands to the path sites/default/files/foobar/image.jpg, or the URL  http://example.com/sites/default/files/foobar/image.jpg


How to get the list of all entity reference fields and their params?

Here is my custom function that gets id's of all files referenced entities and their parents. Also get's all field names, entity types and bundles of entityreference fields.

function _my_module_get_entityreferences_settings() {
  $child_ids = $field_names = $settings = array();

  // Get all entityreference field names
  $query = db_select('field_config', 'f');
  $query->fields('f', array('field_name'));
  $query->condition('f.type', 'entityreference');
  $query->distinct();
  $rows = $query->execute();

  foreach ($rows as $row) {
    $field_name = $row->field_name;
    $field_names[] = $field_name;
  }

  // Loop all entityreference fields. Get all child and parent Ids
  foreach ($field_names as $field_name) {
    $table = 'field_data_' . $field_name;
    $target_id = $field_name . '_target_id';

    $query = db_select($table, 'f');
    $query->fields('f', array('entity_id', $target_id, 'entity_type', 'bundle'));
    $query->distinct();
    $rows = $query->execute();

    foreach ($rows as $row) {
      $settings[$row->entity_type][$row->bundle][$field_name] = $field_name;
      $child_ids[$row->{$target_id}] = array(
        'id' => $row->{$target_id},
        'parent' => $row->entity_id,
      );
    }
  }

  return array(
    'childs' => $child_ids,
    'settings' => $settings,
  );
}

Maybe you don't need all this stuff. When you get $field_names array you can use

$field = field_info_field($field_name);

to get settings of current field. You can find here referenced bundles, field type, handler_settings etc.


Keep line breaks when printing custom plain text textarea field

I worked it out. I just needed to use the following code:

print nl2br($taxonomy_term->field_address['und'][0]['value']);

This uses the print nl2br function to convert line breaks to <br> tags.


Show exposed filter value when returning results

a bit tricky, but works:

Add a field (term) Taxonomy term: Name (Name)
in settings check: exclude from display
Add header:  Global: Unfiltered text
check: Use replacement tokens from the first row
set the text area with the available token: e.g "Showing results for [name]"

Screenshot:


You should definitely NOT put HTML into render arrays (I'm not saying you cannot (you can with #prefix and #suffix), you just shouldn't - that's D7 thinking). You should define a theme hook/template for that so that you can use your own template. But if you have to use inline template:

$page['noscript'] = [
  '#type' => 'inline_template',
  '#template' => '
{{ message }}
',
  '#context' => [
    'message' => $noscript_message,
  ],
];


How to set a rule that sets a term reference field value and text area value in a commerce order entity

Here's a strategy that I think will work:

Create a field on the product like field_bulk_order_limit
Create a field on the order called "field_held_bulk_order" or something. This can be a boolean or some similar thing.
Create a rule that looks at the product's field_bulk_order limit whenever a line item is created or updated and its product has that field. It could output to the screen (system: site message) at the user if the number is above the bulk order limit.
Create a checkout rule (a rule triggered by "when completing the checkout process") that loops through the line items and checks their products' field_bulk_order_limit. If it finds line items with a quantity higher than the field_bulk_order_limit, set the order's field_held_bulk_order to TRUE. Optionally also show them another message.
Fiddle with your administrative order views to have a view that explicitly shows held orders,etc.
Nice to have: create a custom pane that lets them enter the reason that they need so many. This requires a tiny module. It could imitate the commerce_order.module's pane (see commerce_order.checkout_pane.inc and commerce_order_commerce_checkout_pane_info()


Redirect User to their Profile Page After Saving

As @Aboodred, if you already have the Rules module installed, adding a simple rule can do the job.

Create a rule with the React on event type After updating an existing user account.
Add a Page redirect action. Set the 'Data selector' field to account:url (either manually or using the dropdown).


Drupal view shows multiple results to a single row

Option 1: Set the format of the view to "grid" and columns to 2.
Option 2: Set the format of the view to "HTML list" and then with css set the width of the li and float it left.


How to render Views anchors with `title` attribute?

You can do this:

In your Content: Title expand Rewrite Results and check Rewrite the output of this field

In the Text field enter: [title]
This will create your anchor jump point.

Next you can add a block and repeat the same process replacing Text field with [title]


How to edit a web form value so that the column name can be as required in a table in UI

I was able to edit it using theme_preprocess_table method below is the method which I used.

   function theme_preprocess_table(&$variables)
   {
       $variables['header']['completed']['content'] = 'your requirement';
   }


How to put multiple conditions on a field, using Views 3?

Consider module Views Contextual Filters OR (which only has a dev version today). Excerpt from its project page:

  ... provides a views plugin which modify query to support OR conditions for contextual filters.

A few issues on Drupal.org that may be of some help:

Using OR in filters breaks contextual filters.
Views AND/OR Contextual filters two ways.

There is also this comment in the support forum.


Content Type vs Webform vs Form API vs Custom Form vs?

I'm using Drupal for exactly the same purpose. Basically, what I'm doing is using the Field Group module to wrap particular items together in DIV tags so that I can use CSS styles to properly layout my forms.

Drupal provides a very structured set of container elements with appropriately named classes. Accordingly, leveraging the power of CSS to your advantage should be the first thought that goes through your mind when it comes to manipulating layouts.

I mucked with the Webform module, and although it is quite capable, I've found that just sticking with Drupal's standard content type system for collecting information has suited me best.  Utilizing Views and the Rules module, I'm able to generate reporting pages that show me the critical information I want with less modular bloat to my Drupal installation.

So definitely read up on Views, Field Group, and the Rules module to see if the functionality as described will fit your bill.


Having each child record inherit (display) data elements from a parent record

There are several modules to use in conjunction.

Firstly, you need Entity Reference and its dependency, Entity API
https://www.drupal.org/project/entity
https://www.drupal.org/project/entityreference

Install those two modules the normal way.

Others have written add on modules for entity reference such as Entity Reference Prepopulate:
http://drupal.org/project/entityreference_prepopulate
That module can be helpful for prepopulating values for the entity reference fields you create.

So after you've installed the modules you can go to the Manage Fields page for you Program content type, and add a new Entity Reference field.

Might call this field "Company"

Click Save

On the field settings page, Select the Target type (entity type) as "Node"
For the Target bundles (content types in the case of node) select your Program content type
Optionally you can chose to sort the options for the entity reference field by a property of the node such as title.

Click Save

On the next screen you can set the default Company for the Reference field, or you can configure add modules such as Entity Reference Prepopulate to configure defaults based on context.

Click Save

Now you can edit or create Program nodes and reference a company node from them.

For this example I had created a Company node called "A Company"


You can achieve this using Rules by following steps given below:

  Event: After udpdating an already existing line item

  Conditions: 1/ data comparison: commerce-line-item:type = product 2/
  data comparison: commerce-line-item:commerce-product:type = Your given
  product type 3/ data comparison: commerce-line-item:quantity is
  greater than 1

  Action:
  - set data value: commerce-line-item:quantity 1
  - display custom message

Reference: https://drupalcommerce.org/questions/8066/how-limit-maximum-quantity-1-one-given-product-type


You can not include search box generated by custom search module into views, but you can add exposed filter into views to implement search functionality in the views.

To implement search functionality in the views

Add "field" in the filter and choose "Contains" from the operator list
Exposed field in the filer

It will display a search box for that field in the views and work nicely for searching. Moreover, you can enhance its display by using views tpl and control where to display this views block.


Alter existing 'Log In' route so URL includes request_uri as query string

I think you'll need to have a look to PathProcessors, you might do something like that:
mymodule/mymodule.services.yml
mymodule.path_processor:
  class: Drupal\mymodule\PathProcessor\MymodulePathProcessor
  tags:
    - { name: path_processor_inbound, priority: 250 }

mymodule/src/PathProcessor/MymodulePathProcessor
<?php

namespace Drupal\mymodule\PathProcessor;

use Drupal\Core\PathProcessor\InboundPathProcessorInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class MymodulePathProcessor.
 *
 * @package Drupal\mymodule\PathProcessor
 */
class MymodulePathProcessor implements InboundPathProcessorInterface {

  /**
   * {@inheritdoc}
   */
  public function processInbound($path, Request $request) {
    if ($path == '/user/login') {
      $request_uri = $request->server->get('REQUEST_URI');
      return "/login?destination={$request_uri}";
    }
  }
}

Don't forget to clear the cache before to try it.
You might need the processOutbound function too in which case you'll need one more line in your service
mymodule/mymodule.services.yml
mymodule.path_processor:
  class: Drupal\mymodule\PathProcessor\MymodulePathProcessor
  tags:
    - { name: path_processor_inbound, priority: 250 }
    - { name: path_processor_outbound, priority: 250 }


What's the purpose of $item in taxonomy_field_is_empty($item, $field)?

With the help of @Clive

I think that's not the way, taxonomy_field_is_empty is an implementation of hook_field_is_empty(), which is used to

  Define what constitutes an empty item for a field type.

$item is:

  An item that may or may not be empty.

An item is the data for a specific field entry, so what you'd find in, for example, $node->field_tags['und'][0] in your code example.

If you have access to the $node variable and your field is named field_tagsyou can do this:

//Recover all the items
$items = field_get_items('node', $node, 'field_tags');
//If there is not a tag, then do something
if (count($items) == 0) {
  echo "field empty";
}

Or

//If there is not a tag, then do something
if(count($node->field_tags[LANGUAGE_NONE]) == 0) {
  echo "field empty";
}


Styling first results from a View differently from the rest

You can do this in views with the pager offset option. Based on your example above, create a view like normal as a page or block then under the Pager set "Display a specified number of items" and set to 4 and then under the pager's options set offset to 1. This will skip the first item. Then add an attachment display to the view and attach it to your page or block before and set pager to "Display a specified number of items" and 1. Next add another attachment display and attach after and set "Display a specified number of items" to 6 and then under the pager's options set offset to 5. Now you override each display and output only the fields you need for each one.


to do this you could use the Rules module. I tried to do a similar thing before, it works but is a little awkward. You only need an event and action, a condition isn't really needed here:

Event: "Name of flag" has been flagged,
Action: Unflag "Name of second flag"

For the second flag you would obviously do the opposite:

Event: "Name of second flag" has been flagged,
Action: Unflag "Name of flag"

Now if someone flags a node with "Like" the "Dislike" flag is almost automatically unflagged, and vice versa (I think you get the concept here). "Almost" is because while flagging works dynamically the unflagging via rules only works after page reload, in my experience at least. So to a user it will look like you can both "Like" and "Dislike" things, but after reload only the last flag will stay.


How to make calendar block show site events?

I think that you probably want to use the views module to create a custom block that contain the calendar items.  Here is an example...

http://drupal.org/node/1250714


How to set the parent of menu items creating using hook_menu()?

Since the Events menu item links to a node, for which events is a path alias, what you are trying to achieve should work if you define the menu items using the following code (I use "11" as node ID).

function MYMODULE_menu() {
  $years = array(2011, 2010, 2009);

  foreach ($years as $year) {
    $items['node/11/' . $year] = array(
      'title' => $year . ' Events Archive',
      'page callback' => 'page_archive',
      'page arguments' => array(1),
      'access callback' => TRUE,
      'type' => MENU_NORMAL_ITEM,
      'menu_name' => 'main-menu',
    );
  }

  return $items;
}

This is necessary because, if events is a path alias for node/11, Drupal doesn't expand events/2011 to node/11/2011. In the same way, it will not expand events/edit to node/11/edit, even thought the Node module defines nodes/%node/edit as one of its menu items.


How to properly delete fields, programmatically?

field_purge_field() is described as follows:

  This function assumes all data for the field has already been purged and should only be called by field_purge_batch().

On Drupal, fields are effectively removed during cron tasks; in fact, field_purge_batch() is called from field_cron(), the implementation of hook_cron() done from the Field module. There is no need for you to call neither field_purge_field() nor field_purge_batch().

If you want to write code to purge fields for a node bundle, that code would be similar to the following one. (See the notes after the code, thought.)

  $properties = array(
    'entity_type' => 'node',
    'bundle' => 'Your bundle (a.k.a. content type)',
    'include_deleted' => TRUE,
  );

  $entity_manager = \Drupal::entityTypeManager();

  $fields = $entity_manager->getStorage('field_config')->loadByProperties($properties);

  $info = $entity_manager->getDefinitions();
  foreach ($fields as $field) {
    $entity_type = $field->getTargetEntityTypeId();

    // Proceed only if the module implementing the entity has not been uninstalled already.
    if (isset($info[$entity_type])) {
      $entity_manager->getStorage($entity_type)->purgeFieldData($field, 100);
      field_purge_field($field);
    }
  }

Notes

Purging the fields is thought to be ran during cron tasks; that is why Drupal::entityManager()->getStorage()->purgeFieldData() requires the batch size as argument. I used a value of 100, which would possibly allow the code to purge all the fields for that content type, but it could also cause a PHP timeout error. It would be better to run the code from PHP CLI, in order to avoid any execution time out.
You should not need to use this code; in most of the cases, you should execute the cron tasks (which is when Drupal purges the fields of a deleted bundle), or use Drush to purge the fields, either running hook_cron() with it, or executing a specific Drush command (if it exists).

As for truncating the tables, that is the wrong way to proceed. It would not allow Drupal and third-party modules to delete the data they have for the fields; even if you know which tables Drupal uses, you could forget a table used by third-party modules.


As discussed in the linked topic use database values to check for booleans in a condition. In a View template you'll find for each row the entity the row is based on in row._entity, from which you can get the raw field values:

{% if row._entity.field_new.value %}
  <div class="info--details__new">
    {{ fields.field_new.content }}
  </div>
{% endif %}

Even if it works with debugging turned off, you still depend on how you've configured the rendered output and this is not good practice, if a small change in UI can break the code.


You have to use the global variable $custom_theme.
The implementation of your hook_init() is good.


Count entitys dependent om field value and as entity reference

In general Views Aggregator Plus and Views Calc can both generate tally reports like these.

Unfortuntaley by making rooms a text list you've basically made it (nearly) impossible for you to easily generate these types of reports. You're question isn't really a Views question, but 1 of how to write a tally report in SQL.

Since rooms is a simple string, its hard(er) to SUM the values to make your report. If the room was a reference to a room ID in another table then SQL, and Views and aggregation functions could more easily generate these reports.

  Is this possible to do with Views, and then HOW to do it?

TLDR; Yes, it's possible. It's easier if you make your data into non-string values for aggregation. It's a futile effort to show you how because it's simply too messy in code to work with the data structures you've created.

EDIT

If these were numerical numbers for the number of rooms, or room IDs, you could easily use SUM aggregation to find the total. Then you would simply use a Views rewrite substition to show the output as something like the string [node-room-sum] x [node-room-size] room(s) aparament and use tokens derived from your View.


To solve the problem I used the code below to force Drupal to create the image styles for my nodes:

if ($entity->hasField('field_image') && $entity->get('field_image')->getValue() != null) {
  $image = \Drupal::service('image.factory')->get($entity->get('field_image')->entity->getFileUri());
  if ($image->isValid()) {
    $styles = \Drupal::entityTypeManager()->getStorage('image_style')->loadMultiple();
    $image_uri = $entity->get('field_image')->entity->getFileUri();
    foreach ($styles as $style) {
      $destination = $style->buildUri($image_uri);
      $style->createDerivative($image_uri, $destination);
    }
  }
}

Here is the description, for each node ($entity variable) , first it checks if the node type has a field with machine name "field_image" and if this field has a value, then it checks if fileUri is a valid image, then if all conditions met, the code iterates on all image styles available and build that style for given image manually.

This code can be used as a cron job function, so on every cron job image styles of given nodes are created.


If you use standard CCK imagefield, you can set the number of images that can be uploaded within one field. For example, you could allow just one image, or up to 10 images, or an unlimited number of images.

Providing you don't have hundreds of images per node, CCK imagefield is fine for having a gallery of images on each node, and we've implemented galleries quite successfully in this way.


How to translate $value in the output code of a view?

return $dtF->diff($dtT)->format('%a ' . t('days') . ', %h ' . t('hours') . ', %i ' . t('minutes'));


When entering taxonomy terms are new ones added with different pk even if term is already in the dictionary

Drupal allows you to enter multiple terms with the same name. If you want to have unique term names, use the Taxonomy dupecheck module.

  Taxonomy dupecheck module prevents Drupal administrators from adding
  duplicate taxonomy vocabularies and/or terms.


Variables injected or set in a Twig file are undefined after the first position of an entity reference field

Based on the comments to the question, I extended the EntityReferenceEntityFormatter class and modified one part in the viewElements method (the rest is the same):

  $view_builder = $this->entityTypeManager->getViewBuilder($entity->getEntityTypeId());
  $elements[$delta] = $view_builder->view($entity, $view_mode, $entity->language()->getId());

  try {
    $parent = $items->getParent();
    $parent_entity = $parent->getValue();
    $elements[$delta]['#cache']['keys'][] = $parent_entity->id();
    $elements[$delta]['#cache']['keys'][] = $parent_entity->bundle();
    $elements[$delta]['#cache']['keys'][] = $parent_entity->getEntityTypeId();
    $elements[$delta]['#cache']['keys'][] = 'context_aware';

    // Add special information for different paragraph types.
    if ($parent_entity->getEntityTypeId() == 'paragraph') {
      if ($parent_entity->bundle() == 'homepage_feature') {
        $elements[$delta]['#style_flags']['top_image'] = FALSE;
        $elements[$delta]['#style_flags']['right_image'] = FALSE;

        if ($parent_entity->get('field_items')->count() === 1) {
          $elements[$delta]['#style_flags']['top_image'] = TRUE;
        }
      }
    }
  } catch (\Exception $e) {
    // Add logging
  }

Later on, down in preprocess_node:

// ONLY for the homepage handling of featured content.
      if ($referringEntityType == 'homepage_feature') {
        $variables['top_image'] = $variables['elements']['#style_flags']['top_image'];
        $variables['right_image'] = $variables['elements']['#style_flags']['right_image'];
      }

I was able to then add the same node in the same paragraph type multiple times with the correct information. The correct classes are now applied.

Edit:

Just to add to this too, be sure to set your cacheable dependencies so any change to what holds references will not require a cache clear:

$parent = $items->getParent();
$entity->addCacheableDependency($parent);

Edit 2:

Thanks to extra guidance from 4k4, I injected the renderer service and reduced down to:

    $parent = $items->getParent();
    $parent_entity = $parent->getValue();
    $elements[$delta]['#cache']['keys'][] = $parent_entity->id();
    $elements[$delta]['#cache']['keys'][] = $parent_entity->bundle();
    $elements[$delta]['#cache']['keys'][] = $parent_entity->getEntityTypeId();
    $elements[$delta]['#cache']['keys'][] = 'context_aware';

    if ($this->paragraphDisplaySettings->isApplicable($parent_entity)) {
      $elements[$delta]['#style_flags'] = $this->paragraphDisplaySettings->getSettings($parent_entity);
    }

    $this->renderer->addCacheableDependency($elements[$delta], $parent);

paragraphDisplaySettings is a custom service object that aids in evaluating different flags to pass through from the original code just to keep it cleaner and leaner. It's working great.