How to use search_excerpt() function from core search module?

Try this code.I have just added a space after the string and this will surely work

$string = 'this is a test';
$test = (search_excerpt('test', $string.' '));
print $test;

In the search_excerpt() if the search text is the last one, then preg_replace omits the search text.In order to overcome this I just added a empty space to the string.

// Highlight keywords. Must be done at once to prevent conflicts ('strong' and '<strong>').
  $text = preg_replace('/' . $boundary . '(' . implode('|', $keys) . ')' . $boundary . '/iu', '<strong>\0</strong>', $text);


How to add custom attributes to description meta tag?

function [your-theme]_page_attachments_alter(array &$attachments) {
  $attachments = SwiftypeMetaDescription::add($attachments);
}

 class SwiftypeMetaDescription{
      /**
       * @param array $attachments
       * @return array
       */
      public static function add(array $attachments): array
      {
        // check if $attachments contain html_head
        if (empty($attachments['#attached']['html_head'])) {
          return $attachments;
        }

        // loop through HTML head
        foreach ($attachments['#attached']['html_head'] as $key => $attachment) {
          // check if element name is defined
          if (empty($attachment[1])) {
            // if it's not, skip element
            continue;
          }
          // if the element name equals 'description'
          if ($attachment[1] == 'description') {
            // add 'class' attribute
            $attachments['#attached']['html_head'][$key][0]['#attributes']['class'] = 'swiftype';
            // add 'data-type' attribute
            $attachments['#attached']['html_head'][$key][0]['#attributes']['data-type'] = 'string';
          }
        }

        return $attachments;
      }

    }


why my custom jquery code stopped working on a multipage webform after upgrade to WF x6

Following the tips in this post, I changed the code as follows and it worked:
(function ($, Drupal) {
 Drupal.behaviors.myBehavior = {
  attach: function (context, settings) {
    $('input.countme').change(function(){
        var a =  $("input.countme:checked").length // count all checked checkboxes with the css class "countme"
        $(".cm_score").val(a)  //update the value of the textfield that has the class ".cm_score"
    });
 }
};
})(jQuery, Drupal);


Drupal + Solr, boost result based on custom node weight

To provide the score as a sort option add it in the prepare_query hook:

function mymodule_apachesolr_prepare_query(&$query, &$params, $caller) {
  $query->set_available_sort('field_score', array('title' => t('Score'), 'default' => 'desc'));
}

To boost by it you'll need to either:

Go to Site settings -> Apachesolr -> Search fields and if the score field appears there give it a value bigger than all the other fields to make it the most relevant.
If the field doesn't appear (due to the type it might not appear) or you want more control (like calculate the boost value on every query) you can add the boost in the modify_query hook with something like this: $params['qf'][] = 'field_score^10';.


How do I use Panels to replace a default node page?

I found using Views, panels and Ctools a complex and steep learning curve.  Two resources have been very helpful. 1. The video series from Nodeone.se has two video series that can help, "Taming the Beast' (views) and 'Learning Pagemaker'which includes panels. 2. The new book "Drupal's Building Blocks" by Earl and Lynette Miles (Merlinofchaos at drupal.org).


What to do when a module is uninstalled but leaves some features enabled?

If the feature is creating some items that you no longer wish to have on your site (content type, maybe) you can always uninstall that feature. Remember features are basically modules, so you uninstall them the same way (go to mysite/admin/modules/uninstall). That may start to remove some of the items the feature was responsible for (depending on the feature's uninstall script)

Also, as features are basically mini modules, they won't fully go away (or stop showing up on your features page) without removing them first. They should be located in your site/all/modules folder. Remove the feature from the file system.


Is the "access" table removed during upgrade?

The access rules function has been largely removed from core. From the CHANGELOG:

  Refactored the "access rules" component of user module: The user module now provides a simple interface for blocking single IP addresses. The previous functionality in the user module for restricting certain e-mail addresses and usernames is now available as a contributed module. Further, IP address range blocking is no longer supported and should be implemented at the operating system level.

The upgrade path do not remove the {access} table. It migrates the entries it can to the new {blocked_ips} table, but otherwise keep the content of the {access} table in place. See system_update_7002() and system_update_7003().

Parent issue: http://drupal.org/node/228594.
Possible replacement for Drupal 7: http://drupal.org/project/user_restrictions.


The Commerce Price Components module allows you to change what elements of a price are included when displaying it, including whether tax is included in the amount.  With that module, you can get the result you are looking for by editing the view behind your Checkout screen (from your screenshot).

Go to the Checkout screen so it looks like your screenshot.  In other words, be sure you have a VAT tax set up, and a product in your shopping cart, and go to Checkout.  The screen will look as you show above, ie the line item price will INCLUDE VAT.
There is a gear icon in the upper right of the screen (above the word TOTAL).  Hover over this and click EDIT VIEW.
You will be in the Commerce Cart Summary View.  In the FIELDS list, click on the Commerce Line Item Unit Price.
Change the Formatter to Price By Components, and be sure only Base Price is ticked.
Click APPLY
Do the same for the Commerce Line Item Total.
Click SAVE to save the View


I see two problems. First your routing file has the path set to:

path: '/{user}/settoken'

To do what you're describing I would expect to see:

path: '/u/{user}/settoken'

Second, are you opposed to using a second parameter in the URL instead of the Get Method variable? If not opposed you can add a second parameter that will handle the 'token' variable.

In your routing file you can set up the pareters like this:

path: '/u/{user}/settoken/{token}'

The url would then be (cleaner I think):

/u/john-smith-36/settoken/123456

Lastly, to access the parmeters in your controller you shouldn't need to access the Globals. The parameters get passed to your function directly. Use this as the function declaration to pick up the variables:

public function SavePushToken($user, $token)


Trying to display a views list with order based upon current node being viewed

In your View, under Block Display, go to:

Advanced-> Contextual filters (Add)->Content: NID

In the "When the filter value is NOT available" option select:

Provide default value-> PHP Code

and add the following code:

if (arg(0) == 'node' && is_numeric(arg(1))) {
  $nodeid = arg(1);
  $result = strval($nodeid-2) . "+" . strval($nodeid-1) . "+" . strval($nodeid) . "+" . strval($nodeid+1) . "+" . strval($nodeid+2);
  return $result;
}

Last but not least, under "More", select the option: "Allow multiple values"


Redirect the title field of a content type to some external url in a view

To change content link... You can try using Views Conditional Module...

Project page says

  Views Conditional is a simple module that allows you to define
  conditionals (if xxx then yyy) with fields in views. Conditions
  include:

  Equal To

  Not Equal To

  Greater Than

  Less Than

  Empty

  Not Empty

  Views conditional allows you to output text based on the result of the
  condition.

If it doesn't work then you can solve it using views php module..


8 - Is there a drush command to reset a module's config back to install defaults?

I guess it doesn't provide drush integration yet, but have a look at https://www.drupal.org/project/config_update

It provides a UI to compare and revert configuration with the defaults provided by a module.


How to remove white space from a field using Search API module

I would use Computed Fields. Store and display user input with spaces, but index and search computed field too.

  These computed fields are populated with values that you define via PHP code.

So you can simply remove white spaces, or re-format phone number in any way you please, and store a standardised copy of user's phone number. That way both representations will be searchable.

As a small bonus, other modules (like Views, various exporters and connectors or phone integration) would be able to benefit from this too. Bad thing is a slight overhead on reads and saves.


$result = db_query_range("SELECT title FROM {node} WHERE type = '%s'", $content_type, 0, 20);
$titles = array();
while ($row = db_fetch_object($result)) {
  $titles[] = $row->title;
}

http://api.drupal.org/api/drupal/includes--database.inc/group/database/6


How do I make an external URL open on a new tab?

If you can target your menu tag with jquery using its ID you can put something like this in an JS file that you'll add in your theme via your_theme.info

Drupal.behaviors.externalMenu = function(context, settings) {
    $('#menu_id').attr('target', '_blank');
};

Or you can use the Menu attributes module.


All you would need to do is create a block in views with an exposed search function. A walk through on how to do something like this is available at http://summapro.com/drupal-tutorials/learning-exposed-filter-views-search-and-filter


The content access permissions need to be rebuilt. Rebuild permissions?

I cannot give you a full answer. Your answer is specific to your website.

  "The content access permissions need to be rebuilt. Rebuild permissions"
  what is this means?

From some Drupal 6 documentation:

  Rebuild Permissions If the site is experiencing problems with permissions to content, you may have to rebuild the permissions cache.
  Possible causes for permission problems are disabling modules or
  configuration changes to permissions. Rebuilding will remove all
  privileges to posts, and replace them with permissions based on the
  current modules and settings.

  Rebuilding may take some time if there is a lot of content or complex
  permission settings. After rebuilding has completed, posts will
  automatically use the new permissions.

You then asked:

  Can I go for Reubuild Permission?

Sure. This process can take a long time though for a site with many nodes and content.

  Will it cause any problem for current modules?

Depending on your situation and the new modules you've installed that are changing how content permission is being assigned rebuilding permissions may or not affect your users. You must first verify what modules are affecting the content permissions and be sure you've assigned appropriate permissions to specific roles that may be using them. It is your responsibility as site owner to be aware of module dependencies.


Access list of view modes available for nodes

View modes are config entities, so an entity query would do the trick:

$view_modes = Drupal::entityQuery('entity_view_mode')
  ->condition('targetEntityType', 'node')
  ->execute();


Display Suite provides this functionality.  Just install DS, then, in your view, choose "Display Suite" under the option for "Show":

In the settings for that option you can choose a different view mode for the first item in your list:


I needed to add the following to my code:

  $items['admin/settings/cvminterviews/interviewers/interviewers'] = array(
    'title' => 'Interviewers',
    'description' => 'Interviewers',
    'file' => 'cvminterviews_admin_interviewers.inc.php',
    'page callback' => 'cvminterviews_interviewers_overview_page',
    'access arguments' => array('administer cvminterviews'),
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );

The important part is to make this the exact same callbacks as the 'admin/settings/cvminterviews/interviewers' menu item, but with one more level, and assign the MENU_DEFAULT_LOCAL_TASK type.


How to do result biasing in Apache Solr by node rating?

I think the Apache Solr Voting API module is just what you're looking for. It seems to have grown out of this issue. In limited testing I found that enabling it does add a bias setting for vote rankings:


How to modify HTML layout inside a View template

views-view-fields--[view-name]--machine name.tpl.php

Ex: views-view-fields--hello-world--block-1.tpl.php

  <?php print $fields["field_image"]->content; ?>

     <?php print $fields["title"]->content; ?>

     <?php print $fields["body-summary"]->content; // if you r using a body summary ?>
     <?php // if you are using an actual field then use:  print $fields["field_name"]->content; ?>

CSS

.picture { float: left; }


You can do it from hook_menu_link. You want to access the $vars['element']['#localized_options']['attributes']['class']

Something like this

$element = $vars['element'];
$element['#localized_options']['attributes']['class'][] = 'your-class';
$output = l($link_text, $element['#href'], $element['#localized_options']);

Then return the $output in the <li>. Be sure to account for $vars['element']['#below'] if you have a sub-menu.


Navigate to

admin/config/development/jquery_update

and set the Default jQuery Version to 1.8 or higher

and the Alternate jQuery version for administrative pages to 1.7 (1.5 and lower has issues with views and other modules)

Then clear your Drupal and browser cache if need be.

If you don't see these settings in jquery update ui then install the latest dev version of jquery update.


Alternative to FieldCollection and FieldCollection Table

Oh, good question.

combined with some fancy view work, you could use pretty much any fieldable entity in Drupal to do this.

You could use another content type with entity relationships to link the two. You can render it with an Entity Reference Views Widget and use a views table to format that output.

If you don't want to use a content type, you can also explore custom entities.

Reading:

https://www.sitepoint.com/build-custom-drupal-entities/
https://www.phase2technology.com/blog/developing-a-custom-drupal-entity/
http://www.trellon.com/content/blog/creating-own-entities-entity-api

Now, if you don't want to have to try and do this in code, there is also a great module called ECK (Entity Construction Kit) which allows you to build fieldable entities and use them just like any other all from within the Drupal admin UI.

Hope this helps.


Does a sub-theme needs the main theme enable?

No, it is not necessary. You need to have your base theme installed, but you don't need to enable it: https://www.drupal.org/node/225125#comment-7716513

EDIT: Note that if you want to access the settings for your base theme, you will need to enable it, as noted by @MPD in a comment below.


Drag & drop upload plugin, how to make it multiple

It suggests you need this module; from the README file and project page;

  Multi-upload support will be enabled if Multiupload Filefield Widget
  module exists.


How do you override the add or edit node for a particular content type

Depending on where exactly you want to indicate that "away" status, I think you should rather alter the entity reference field widget for that specific field to add this "away" status rather than trying to achieve this via templates.

Sounds like you want to try implementing this hook:

function hook_field_widget_multivalue_WIDGET_TYPE_form_alter(array &$elements, \Drupal\Core\Form\FormStateInterface $form_state, array $context) {
  // Add a css class to widget form elements for all fields of type mytype.
  $field_definition = $context['items']->getFieldDefinition();
  if ($field_definition->getType() == 'mytype') {
    // Be sure not to overwrite existing attributes.
    $elements['#attributes']['class'][] = 'myclass';
  }
}


I don't know what you try to do with the config directories.

This doesn't make sense at all, setting a value and deleting it:

$config_directories['staging'] = 'sites/default/config/staging';
$config_directories = array();

The config directory staging does not exists anymore, it must be from an old drupal 8 version. You only need sync. This can be any directory. The hash is only for security reasons and is not needed outside the public files directory.

And I don't see anything in your workflow that would need a special configuration of the config directory, because you transfer the config in the database.


It is because path aliases are for a single path, so the path alias user/[user:name] is only for user/82.
If you want path aliases for all those other pages, they have to be added separately.

And because they are not pages that are covered by the pathauto module, you cannot use it for those pages.

You can manually add aliases at admin/config/search/path/add but because you can't use tokens there you would have to add aliases manually for each user (which is ridiculous).

The only module I know that can help you out is http://drupal.org/project/subpathauto

The equivalent module for drupal 6 is http://drupal.org/project/subpath_alias

Those modules aim to allow you to do what you desire.

It seems there is currently a bug in the subpathauto module though that is breaking user aliases. See http://drupal.org/node/1851102

I just tested 7.x-1.2 and it is working correctly.

You can get 1.2 from here - http://drupal.org/node/1416736


How do I reset URL for Product Display when replacing the main product? (instead of having an increment added to the URL)

I am not sure why this happens in Commerce Kickstart, while it does not happen with regular Drupal. Almost as if the product's path are cached or something, but clearing all caches after deleting a product did not change the outcome. But I did find an easy solution.

You can fix that by deleting your Aliases, go to /admin/config/search/path/delete_bulk

And then regenerating them


To programatically user from code, you need to replicate what user_login_submit and user_login_finalize are doing:

function user_login_submit($form, &$form_state) {
  global $user;
  $user = user_load($form_state['uid']);
  $form_state['redirect'] = 'user/' . $user->uid;

  user_login_finalize($form_state);
}

function user_login_finalize(&$edit = array()) {
  global $user;
  watchdog('user', 'Session opened for %name.', array('%name' => $user->name));
  // Update the user table timestamp noting user has logged in.
  // This is also used to invalidate one-time login links.
  $user->login = REQUEST_TIME;
  db_update('users')->fields(array('login' => $user->login))->condition('uid', $user->uid)->execute();

  // Regenerate the session ID to prevent against session fixation attacks.
  // This is called before hook_user in case one of those functions fails
  // or incorrectly does a redirect which would leave the old session in place.
  drupal_session_regenerate();

  user_module_invoke('login', $edit, $user);
}

Just replace $form_state['uid'] with UID you generated in earlier step, and maybe use other way to redirect.


You can achieve that using the jCarousel module. I've used this module and works fine for me.

  This module allows developers and themers to make use of the jCarousel jQuery plugin. It includes a developer API that other modules can use, as well as Views integration in the 2.0 version so that you can turn any list of content or images into a carousel.

Image from module page.

There is another module called  Owl Carousel

  This module integrates the wonderful Owl Carousel slider built by OwlFonk. The primary module is comprised of three sub modules providing a views style, field formatter & administration UI. The administration form leverages the variable module providing multilingual support out of the box.


In Drupal, the submitHandler() method of your form definition will always be called UNLESS you have a custom handler attached to the submit button that is clicked. In the case of #ajax buttons, you add your own custom handler, then rebuild the form in that handler.

'#type' => 'submit',
'#ajax' => [
  'callback' => '::ajax_function',
  'wrapper' => 'my-button-wrapper',
],
'#submit' => ['::ajaxButtonSubmit'],

Then:

public function ajaxButtonSubmit(array &$form, FormStateInterface $form_state) {
  $form_state->setRebuild(TRUE);
}

By doing this, the default submit handler is not called, and your ajax submit handler is called instead, which then ensures the form is rebuilt instead of reloaded.


Using Views for a custom table with multi-value fields

You'll probably need 2 MySQL tables (to overcome the many-to-many relationship): one to link the nids to data-ids and one to link the data-ids to the actual data. One with three columns and the other with two: (primary key, nid, data-id) and (data-id, data).

    +------------+-----+--------+     +---------+--------+
    |nid-data-id | nid | data-id|     | data-id | data   |
    +------------+-----+--------+     +---------+--------+
    |1           | 1   | 1      |     | 1       | value  |
    |2           | 1   | 2      |     | 2       | value  |
    |3           | 2   | 1      |     +---------+--------+
    +------------+-----+--------+

This way  you can use either multi-select or new values every time. Linking these tables can be done in the same manner as the article you provided (linking two can be found at Views - join tables or the views table API ) but I do not have any experience with that.


Translation of months and days in Calendar Views Module

You need to translate the strings. Go to Administration » Configuration » Regional and language » Translate interface, in the menu.

Then search for !month-name and !day-abbreviation and translate the strings to your language.

You can also download translations for the whole module on https://localize.drupal.org/translate/languages/fr

You can also use the Localization update module. From the UI of the module you can download and keep track of new translations for your downloaded modules.


How to create a pager to display next article in particular taxonomy?

You can accomplish this with the contrib module Flippy. It will allow you to add pagers for specific content types. Hope it helps.

  Flippy is an ultra-simple module that generates previous/next pagers
  for content types. On the Node type administration screen, you can
  turn Flippy on or off for each content type. It'll generate a unique
  pager for each content type, so you can page through Articles or page
  through Blog posts, but you can't page through all nodes on the site.


How to build and organize menus with rich taxonomies and complex view-based menus

Typically, we put all of the site sections in the main menu.

Each site section will get its own Drupal menu.  How items get into menus varies widely project-to-project, but we will rely on path-alias define section organization as much as possible.

Each section will have its own Panels pages, where the site section gets used as the context / selection rule (typically by path matching), and the menu is placed in a content area.

Occasionally, we will have a site section taxonomy, which gets used inside a custom block to display the proper menu.


How do I get the menu ID based on the menu title?

Tricky question. In short, you can't. You can query the menu_links table all you want, be my guest, but realize please that the title you see on the page and the title in the database is the same only in one case: you are running an English-only website and the title_callback is t. (And if you are on D7, you are not overridden in settings.php or in D6 with string overrides and...) Otherwise the title is generated dynamically and it's literally impossible to figure out from the DB alone.


User Registration Disable Email Verification

You need to do a lot more than just unsetting the field if you want to change the way registration works. Out of the box, Drupal expects a valid email unique address for every user. This is why there are contributed modules for this purpose: it needs a fair amount of code to achieve.

Take a look at https://www.drupal.org/project/optional_mail for example.


How can create a template for user login form?

Use page--user--login.html.twig for targeting user/login  page.

You can also enable Twig debugging to see naming suggestions for different page components.

  The markup of each Twig template is surrounded by HTML comments that
  contain theming information, such as template file name suggestions.


Set a datetime field configured as date-only

Assuming field_profile_geburtsdatum is configured as a singular date-only datetime field, the following are all equivalent in the Field API (in order of my preferred usage):

$user->field_profile_geburtsdatum = '1999-12-31';
$user->field_profile_geburtsdatum->value = '1999-12-31';
$user->field_profile_geburtsdatum->set(0, '1999-12-31');
$user->set('field_profile_geburtsdatum', ['1999-12-31']);

The value you set should be a string in the DATETIME_DATE_STORAGE_FORMAT, which is 'Y-m-d', and not a DrupalDateTime object.  That is used internally by the field type.


Showing only one of the Field Collection fields through Views

Did you try to ad a new view with "Show: Field Collection Item" and then, you need different relationships and contextual filters. My Field collection Item is called Gallery and Caption

I've got the following relationships (right column of the views):

"Field collection item: entity with the Gallery and Caption" (this
one connects the field collection item with my contenttype gallery)
"(Field_gallery_and_caption) File Usage: File"  "Field collection
item: Gallery Image:fid"

And following Contextual Filters (also right column of the views):

(field_gallery_and_caption) Content: Nid
Field collection item: Gallery Image:fid

I'm not sure about the order of adjustment, you have to try a little bit. But through relationships and contextual filters, you can get new fields for the views. And while configuring the fields (left column of views), there appears a dropdown called "Relationship", try different settings here, it changes the result.

Not the most detailed help but try to change the settings and you gonna get a result...


views contextual filter based on NID that is selected from a list

You can use Nodequeue module for this. Quote from its project page:

The Nodequeue module allows users to collect nodes in an arbitrarily ordered list. The order in the list can be used for a any purpose, such as:

A block listing teasers for the five top news stories on a site
A user’s favorite music albums
A group of favorite from which one is randomly displayed

Nodequeue provides a simple drag-and-drop interface to manually order any queue. Additionally, it allows nodes to be added and removed from queues without needing edit permissions to the node. Nodes can be added to queues either from a queue management tab or by links on the node teaser.


How to move an article to another place.

Promoted to home page content is ordered by created data.. So, Change authored date accordingly..
Make them sticky by editing content and checking sticky at top of lists checkbox to place them on top of list in home page..
If you are using views module you can set sort criteria..


How do I plot a graph or chart on the confirmation message?

Since there doesn't seem to be a solution for this, I would define a webform handler that would preprocess the confirmation page with the chart that you generate.
There are plenty of D8 module for charting, and in the handler you have access to the webform submission values. You could even use a different method and save the chart image into a hidden image field on the submission. Handlers are sweet like that.
Check out WebformHandlerBase class/interface for the full method list. Checkout this other answer involving webform handlers to get you started. Once you have your handler, check out these examples for your methods.
Acting on presave()
/**
 * The example below demonstrates:
 * - retrieving a submission value
 * - processing it
 * - setting a field value to that result
 *
 * @param WebformSubmissionInterface $webform_submission
 *   A webform submission.
 */
public function preSave(WebformSubmissionInterface $webform_submission)
{
  $age = $webform_submission->getElementData('age');
  $ageChart = $this->someInjectedFooChartingService($age);
  $webform_submission->setElementData('age_chart', $ageChart->BarExportPng());
}

Acting on preprocessConfirmation()
/**
 * The example below demonstrates:
 * - retrieving a submission value
 * - processing it
 * - passing data to the confirmation template
 *
 * @param array $variables
 * @throws Exception
 */
public function preprocessConfirmation(array &$variables)
{
  /** @var WebformSubmissionInterface $webform_submission */
  $webform_submission = $variables['webform_submission'];
  $age = $webform_submission->getElementData('age');
  $ageChart = $this->someInjectedChartingService($age);
  // Add data to the confirmation template
  $variables['agechart'] = $ageChart;
}


The solution for this, is a quite similar response for this question: Manually disable a module take a look. Hope that helps.


A module for displaying the author and the title

Like Andy said your best bet is to use Views. I'm afraid with any thing in Drupal there comes a learning curve.

From what I can gather you either want:

a) The username and title of the content your viewing displayed in a tabular view

or

b) A tabular view of all authors and their titles on a single page.

Views will do both of these with some configuration. I can't give you the exact configuration because there isn't enough information but this should get you going.


Form posting before ajax can update content

function THEME_form_alter(&$form, &$form_state, $form_id) {
    $form['#validate'][] = 'webform_validate';
}

function webform_validate($form, &$form_state) {
  //Appending comments field with campaignString
  $campaingString = $form_state['values']['submitted']['campaignstring'];
  $comments = $form_state['values']['submitted']['Comments'];
  $comments = "[".$campaingString."]  " . $comments;
  $form_state['values']['submitted']['Comments'] = $comments;
}


How to avoid url conflict when defining menu items, and make sure path without wildcards will be used in favor of path with %?

Assuming you are using Drupal 7:

Order matters only a bit - menu_router_build() saves all path into the {menu_router} table just the way they are set. But there are no guarantees database will return elements in that order. Logic to decide which menu item should be executed is in menu_get_item().

Actual query is:

$router_item = db_query_range('SELECT * FROM {menu_router} WHERE path IN (:ancestors) ORDER BY fit DESC', 0, 1, array(':ancestors' => $ancestors))->fetchAssoc();

As you can see, fitting elements are ordered by fit column, most specific first.

As you can see in actual _menu_router_build(), $fit gets initially set to 0 for each menu item:

foreach ($callbacks as $path => $item) {
  $load_functions = array();
  $to_arg_functions = array();
  $fit = 0;

It means it shouldn't be possible for the order of menu elements in hook_menu() to affect order of routing. Actual code is a bit complicated to understand, but elements specific should have higher fit than elements with '%' in them. As the comment in code says: // If there is no %, it fits maximally.


I would suggest perhaps using a Nodequeue - http://drupal.org/project/nodequeue.

This way you can order the images in whichever order you like.

Alternatively, if it is just one node that you want to appear first and then sort by something else you could perhaps utilise the 'sticky' feature?

OR do you want the order to start from ID 5 and continue 6, 7, 8 etc?


Automatically add a new node to a drop-down menu

I achieved this effect by using https://drupal.org/project/nice_menus, and building a view that contains all of the nodes I want displayed in the drop-down. Then https://drupal.org/project/menu_views can display that view as menu items within the menu that Nice Menus has built.


A view with exposed sort: can i turn off 'grouping field' for different sort criteria?

Ok, i think i've managed it with a Views hook. Took an hour's worth of tinkering. I plopped this into my template.php...

/** Find out what the sort criterion is.
    @return The sort criterion fieldname. IMPORTANT: this isn't sanitised!
*/
function MYTHEME_get_sort_by() {
    if (isset($_GET['sort_by']))
        return $_GET['sort_by'];
}

/** Turn off Views grouping-field when sorting by title.
*/
function MYTHEME_views_pre_build(&$view) {
    if ($view->name=='event_programme') {
        if (MYTHEME_get_sort_by()=='title')
            $view->display_handler->options['style_options']['grouping']='';
    }
}


Drupal Commerce - add fields to product or product display?

I add all fields that will never change depending on the variations to the product display. For the fields that will change based on variation, those fields go on the product itself.

Example:

A tee-shirt from "Rockstar Threads," a brand, and a tee-shirt from "Basic Clothes," another brand. Each shirt has two colors each, red and black.

The red Rockstar shirt is the same brand as the black Rockstar shirt.
The red Basic shirt is the same brand as the black Basic shirt.

So the "brand" field gets attached to the product display. The "color" field gets attached to the product. Now, when I create a new product, for each variation I can add a color, but I only choose a brand once since it's attached to the display. All in all, anything that will remain constant across all variations is attached to the display. Anything that will change, attach to the product.


Add condition to specific content type in apache solr

Check apachesolr.api >> hook_apachesolr_query_alter

function hook_apachesolr_query_alter(DrupalSolrQueryInterface $query) {
  // I only want to see articles by the admin.
  //
  // NOTE: this "is_uid" filter does NOT refer to the English word "is"
  // It is a combination of flags representing Integer-Single, which is
  // abbreviated with the letters i and s.
  //
  // @see the <dynamicField> definitions in schema.xml or schema-solr3.xml
  $query->addFilter("is_uid", 1);

  // Only search titles.
  $query->replaceParam('qf', 'label');
}

More details about solr query DrupalSolrQueryInterface


Error : No eligible views were found. Create a view with an Entity Reference display, or add such a display to an existing view

I solved it by chosing content as a reference. After that the options are the same but then it is displaying the view and it works.


How to use views to display a list of views pages?

What you're asking is not possible. De data that the views stores is not provided back to the views module. As you've noticed, you're not able to create a list of views using a view.

I can think of two options to make this possible:

Create a (complete) custom module that selects and outputs the values you desire
or, provide the views module with the data you need to create the list you want

Both options require custom code to make it possible. At this moment, both views and metatags don't allow you to do what you want.


What specific modules are included in Drupal Commerce Kickstart?

Here's the actual makefile that builds the latest version of Commerce Kickstart.

http://cgit.drupalcode.org/commerce_kickstart/tree/drupal-org.make

Within it, you can find every module that is built in. It includes the machine name of the project and the version number used.

For example, the entry "projects[ctools][version] = 1.9" shows you the machine name ctools, which is the Chaos Tools module, and the version is 1.9. You can look up the modules on drupal.org by substituting the machine name into the following URL: http://drupal.org/project/MACHINENAME.


Adding a variable to a menu twig template

You could use directly the derivative id (which will be unique) of the menu item in twig, with:
item.original_link.getDerivativeId()

otherwise you need to add a custom unique id in preprocess function to each item, like:
function yourtheme_menu_link_alter(&$item) {
  if($item['menu_name'] == 'custom-menu')
  {
    $item['uuid'] = \Drupal\Component\Utility\Html::getUniqueId($item['menu_name']);
  }
}

which you then access in twig with:
item.uuid


Getting the node object in hook_form_FORM_ID_alter

PhpStorm doesn't know as the type of form object is dynamic but it's fine.

If you want to make it happy, wrap it in a condition like:

if ($form_state->getFormObject() instanceof EntityForm) {
  ...
}

Either way, it should definitely work if you implement the correct form alter. If you don't, you should end up with a fatal error not just without a node object.

You need to share your exact code if you want a more specific answer, that's all I can tell you.


How do I echo the node vocabulary in preprocess_page or in page.tpl.php so that I can test against it in Drupal 7?

If you want to output something on in the page structure (ie. somewhere in page.tpl.php), you need to output it as a block, Drupal's primary structural element.

In a module, define a hook_block_info() (or hook_block() in Drupal 6 and below), and implement it in this way:

/**
 * Implements hook_block_info().
 */
function mymodule_block_info() {
  return array(
    'node_taxonomy' => t('Taxonomy terms of the node')
  );
}

/**
 * Implements hook_block_view().
 */
function mymodule_block_view($delta = '') {
  if ($delta != 'node_taxonomy') {
    return;
  }

  // Get a node object form the URL (node/123).
  $node = menu_get_object();
  if (!$node) {
    return;
  }

  // Render the 'field_tags' field from the node object using the 'page' display.
  $rendered_field = field_view_field('node', $node, 'field_tags', 'page');
  if ($rendered_field) {
    return array(
      'subject' => t('Tags'),
      'content' => $rendered_field,
    );
  }
}

Or use Panels, which is precisely designed to build composite pages, and allows you to render the different elements of the node in different places.

Other approaches, especially those involving hacking the theming layer are breaking the principle of separation of structure and presentation.


Search text box for Search API + Database + Search Views + Facets API + Facets Bonus

You should enable title and other fields for search in your search index.
Select type as "Fulltext". Reindex content.
After that add new exposed filter in your search view. It's fulltext search filter. In settings of this filter you can select your fields from index.


How to set the path to images in ckeditor?

You might want to try Pathologic module to see if that works for you.

  Pathologic is an input filter which can correct paths in links and images in your Drupal content in situations which would otherwise cause them to “break;” for example, if the URL of the site changes, or the content was moved to a different server. Pathologic can also solve the problem of missing images and broken links in your site’s RSS feeds.


Pods created after the first try to load the private files using the same path as the first one

Posting my comment as an answer.

sites/default/files needs to be on a shared file system so that Drupal can work correctly. This contains uploaded and generated files (e.g. CSS/JS).

If you do this, you probably want to move twig to a local temporary folder, see Can I change the location of the cached Twig templates?. Note that you then need to take care of emptying that folder on all servers when you do a deployment (Unless you do something really special, this cache only needs to be updated when you change your template files).


Permission to control revisions without giving full content access in D6

You should try using the Workbench module.

  Workbench provides overall improvements for managing content that
  Drupal does not provide out of the box. Workbench gives us three
  important solutions:


entity translation access permission alter

This is how its working for me, with args() we can get path ie english or any other language node is there :

  Example Paths in my case:

  node/[nid]/edit/add/sv/en

  node/[nid]/edit/add/en/sv

  node/[nid]/edit/sv

  node/[nid]/edit/en

define('ROLE_EDITOR',4); // role ID 4
define('ROLE_EDITOR_ENGLISH',10); // role ID 10

function my_module_node_access($node,$op,$account) {
  global $user;

  if (in_array(ROLE_EDITOR, array_keys($user->roles)) && !in_array(ROLE_EDITOR_ENGLISH, array_keys($user->roles))) {
    if(arg(3)== "en"){
      return NODE_ACCESS_DENY;
    }
    if(arg(3) == "add" && arg(4) == "sv"){
      return NODE_ACCESS_DENY;
    }
  }

  if (!in_array(ROLE_EDITOR, array_keys($user->roles)) && in_array(ROLE_EDITOR_ENGLISH, array_keys($user->roles))) {
    if(arg(3)== "sv" || arg(3)== NULL){  // Null is need to add as edit and edit/sv is same in my case because sv is defult language
      return NODE_ACCESS_DENY;
    }
    if(arg(3) == "add" && arg(4) == "en"){
      return NODE_ACCESS_DENY;
    }
  }

}


There are two modules, I didn't try them myself and I'm not sure what is your use case:
Drupal to Slack and Slack. Are these provide the functionality you want?

Update
Ok, there are other modules for adding share buttons like Simple Addthis or the dev version of the original Addthis Module


How to I get an extra field for a user profile when using EntityFieldQuery()

The result that comes from EntityFieldQuery::execute contains an array of entity types, and within each of those is an array of the entities found in the query.

The caveat is that the entity ID is actually the array key of said array, so to use user_load_multiple() you would use syntax like this:

$users = user_load_multiple(array_keys($result['user']));


Using hook_form_alter to change exposed filter from a textfield to a checkbox

Just entered this as a bug: https://www.drupal.org/node/2651102. The underlying issue is that Views checks for an empty array (among other things) to see if a filter has a value set. Unchecked checkboxes results in an array of zeros.


Adding a custom URL to the top of a view based on status of another field

Your question is actually several questions. I'd suggest that you break you problem down into smaller, more manageable questions otherwise the number of responses might be low.

For starters, a break down:

"I need to dynamically create a link that uses the title" ->
Pathauto module.
"I'd like a link to appear of this form": The
format that the URLs appear in can be set in the Pathauto
configuration settings for the node type.
"BUT ONLY if that node has a field_type_status of "closed" -> Hmmm,
this might require some custom code. It's kind of a weird spec as
it's considered good SEO to use Pathauto on all site content. Good
luck with this one, perhaps someone else will help you with this one.


How do I add a css class to body from a page callback function?

Well, I think your confusion comes from the D7/D6 fact that a "page" has little clue whats going on around it. As you've said the page callback function tells drupal "what goes in the $content" but not what adornments happen on the page HTML DOM around $content.

To my knowledge unless your using Panels, Context or something else to share "page state" through components of your site -- this is simply how D7 simply works.

Without using context, panels, etc. I usually end up looking for url paths or NIDs or custom content array attributes #project-add-body-classes in hook functions to fire off my logic.

For what you describe I would use hook_html_alter() and look for a page path to alter the body_classes array as needed.


Personal contact form button if available

This was the solution I came up with:

/**
 * Implements hook_preprocess_user().
 */
function MYTHEME_preprocess_user(&$variables)
{
    $account = $variables['elements']['#user'];
    if ($account->getEmail() != '') {
        $contactUrl = Url::fromRoute('entity.user.contact_form', ['user' => $account->id()]);
        if ($contactUrl->access()) {
            $contactLink = Link::fromTextAndUrl('Contact', $contactUrl);
            $variables['contact_btn'] = $contactLink->toRenderable();
            $variables['contact_btn']['#attributes'] = array('class' => array('btn', 'btn-primary', 'btn-contact-user'));
        }
    }
}


Saving date field programmatically on node, but not on profile

This might or might not fix your problem but since you're using entity metadata wrappers, you should use them fully:

$profile = profile2_create(...);
$profile_wrapper = entity_metadata_wrapper('profile2', $profile);
$profile_wrapper->field_date = array(...);
$profile_wrapper->save();

The above snippet can also be used with nodes, just replacing the creation & wrapper instantiation.

Also, if you're using a single timezone, you can safely omit it and just specify the actual timestamp value.  You should probably omit the 'date_type' key too, that's inferred by the field config and could be causing issues.

In fact, you should just do: $profile_wrapper->field_date = 123456; // (timestamp)

Tested locally and it works!

You shouldn't use LANGUAGE_NONE or [0] indices because not only might it break i18n if you're translating fields but it's also not very robust.


Drupal site shows frontpage instead of added content

You might have all of the tables, but you might not have all of the rows, perhaps. Two tables to look at: node and node_revision. See of there are rows there.


What is the best way to import new changes from dev to live site using feature module

Do not use a huge feature with all your changes because Drupal may have problems managing it. I recommend to split your configuration in several Features.

If your project is absolutely custom and you are not going to reuse your custom configuration you can create a Feature for every Drupal domain obejct. For example, create a Features for each Content Type, a Feature for the base Fields, a Feature with all your Views, another Feature with the roles, anohter Feature witj all permissions, and so on. If any of those Features becomes too big (for example, you have hundreds of Views) you can just split it into smaller Features.

If your configuration may be reusable in other projects use Features that more or less pacakge a single site feature.

There's no way to know what you have changed from your dev site compared to live site easily. I suggest to just create your Features and deploy them in a clone of your pro site and check everything works ok. If not, trace the missing configuration.


View only displays nodes that has comments when adding comment count field

I think it is you. Unable to re-produce. Here is a example view listing content nodes, two fields and the comments count.

I also exported the example view example view that you can import and test out for yourself.


Try this:

{% set varname = app.session.get('varname') %}

This is the session value {{varname}}


Creating a Rule condition that evaluates a field an entity that is referenced by a created node

Okay, I think I figured out a way to pull this off, and even if it's not the best practice for what I'm attempting to do, it is working.

So like I said, I was trying to create a condition that relies on information contained in a node that is being referenced as an entity. One of the discussion posts indicated I may need to create a component.

So I went to components and created a new component. Data type I set for Any Entity then named it story page (story_page).

I set conditions that the entity is content, and then a condition where content is of type story page.

Now that we have the content type identified and set we create a condition for list contains item and search for the item in the specific taxonomy I'm looking for.

TO understand this component understand that there are some folk who post more mature content on my page that I DON'T want exposed to the general public. So I require that that kind of content be marked by a specific setting in two fields.

This checks one of those fields and makes the determination. The information however on a chapter for that to be determined is stored in a referenced node which is set in field_story. You have to be able to get the information from that node, and that information is stored in field_genre. So the Componenet is built like this.

{ "rules_check_for_erotica" : {
"LABEL" : "Check for Erotica",
"PLUGIN" : "and",
"OWNER" : "rules",
"TAGS" : [ "Entity Reference", "Node", "Twitter" ],
"REQUIRES" : [ "rules" ],
"USES VARIABLES" : { "story_page" : { "label" : "Story\u00a0Front Page", "type" : "entity" } },
"AND" : [
  { "entity_is_of_type" : { "entity" : [ "story-page" ], "type" : "node" } },
  { "node_is_of_type" : {
      "node" : [ "story-page" ],
      "type" : { "value" : { "story_front_page" : "story_front_page" } }
    }
  },
  { "list_contains" : { "list" : [ "story-page:field-genre" ], "item" : "161" } }
]

}
}

Now, we have a component that can test and figure out if the attached story field has that entry. We can then use it for rules related to story pages to test for it, and make a determination on what to do based on it.

I then created another rule similar to this but it was checking a different field to determine if the story in question is an original story  or if it's part of an original series on this page. I then created a new rule to check the chapter page.

{ "rules_publish_new_chapter_darkscribes_" : {
"LABEL" : "Publish New Chapter (Darkscribes)",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"TAGS" : [ "Facebook", "Social", "Twitter" ],
"REQUIRES" : [ "rules", "twitter_actions", "fb_autopost_entity" ],
"ON" : { "node_insert--chapter_page" : { "bundle" : "chapter_page" } },
"IF" : [
  { "component_rules_check_for_original" : { "story_page" : [ "node:field-story" ] } },
  { "NOT component_rules_check_for_erotica" : { "story_page" : [ "node:field-story" ] } }
],
"DO" : [
  { "rules_core_twitter_actions_set_status_action" : {
      "message" : "[node:author] just posted a new chapter for [node:field_story] | Chapter [node:field-chapter-no-]: [node:title] | [node:url]",
      "sender" : "Darkscribes"
    }
  },
  { "entity_create" : {
      "USING" : {
        "type" : "facebook_publication",
        "param_type" : "post",
        "param_user" : [ "site:current-user" ]
      },
      "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
    }
  },
  { "data_set" : {
      "data" : [ "entity-created:field-facebook-link" ],
      "value" : [ "node:url" ]
    }
  },
  { "data_set" : {
      "data" : [ "entity-created:field-facebook-message" ],
      "value" : [ "node:body:summary" ]
    }
  },
  { "publish_to_facebook" : {
      "USING" : { "publication" : [ "entity-created" ], "pages" : "215544991848808" },
      "PROVIDE" : { "facebook_publication_id" : { "facebook_publication_id" : "Facebook publication returned ID" } }
    }
  },
  { "data_set" : {
      "data" : [ "facebook-publication-id" ],
      "value" : [ "facebook-publication-id" ]
    }
  },
  { "entity_save" : { "data" : [ "entity-created" ] } }
]

}
}

I tested it to see if it would post a message to one of the two twitter accounts in question, and it SEEMS to have done just right.

I may need to revisit this answer later and add an image or screenshot to it at some point. Or find a way to consolidate my content checking rules.


How to add the VAT on the selected products in Commerce Kickstart?

There is a module Commerce VAT for this purpose

  Commerce VAT module is an improved module for supporting VAT than the
  Commerce Tax module included in Commerce. If you are using Commerce
  VAT is is recommended you disable Commerce Tax.


Why is #attached library load not working, but drupal_add_library works?

Because the render array has already been rendered before the preprocess functions, '#attached' is not supported in preprocess functions until Drupal 8.

The issue where it was added is https://www.drupal.org/node/2346369

The related Drupal 8 change record is https://www.drupal.org/node/2352319 - this also shows the supported way of doing it in Drupal 7.

Using drupal_add_library() will work, but it will not be cached, so you will take a performance hit. You are better off adding it to the #attached array at a different step in the process.


How to place two Fivestar widgets on the node for voting?

you can use a PHP code like this

$node=node_load($nid);
print fivestar_widget_form($node);

the forms will have different ids so the javascript will work

you have to create a custom php/tpl file for this node-CONENENTTYPENAME.tpl.php by copying the contents of your node.tpl.php  and include there the custom code...


There's no need to use any sort of API or query. If you're goal is to validate email, it's built into Drupal's core account settings (Configuration > People > Account settings). Just make sure the Require e-mail verification... checkbox is ticked on the form page.


How to put google map field in my form of my custom module?

use this
it works for me
https://www.drupal.org/project/google_map_field
.
.
.
.
.
.


I actually disagree with the comment from @Kevin, using or not using nodes can make a huge performance difference, for multiple reasons.

Yes, node is a pretty standard content entity, but..

It is revisionable
It is translatable
It has a bunch of standard base fields like promote, sticky that are likely not relevant for your use case
Any data that actually is relevant needs to be stored in configurable fields, which results in additional tables.

So if you need 20 additional fields to store stuff, you end up with 4 base tables and 40 additional tables, so 44 tables in total.

If you don't need revisions and translations and assuming you only have single-value fields, you can do that with a single table instead with a custom entity type and base fields. If you need revisions then it's 2. And each multi-value field does require 2 additional tables but usually there are not that many of those.

With millions of records, it's definitely worth thinking about if creating a custom entity type is worth it and sounds like for that case, the answer is probably yes.

It's worth pointing out that there's still a decent amount of modules (even in core), that currently only work with nodes, e.g. book or diff. So make sure that you don't need any of that or be prepared to re-implement that functionality.


How can users buy nodes they can create?

There's already a Commerce subproject called Commerce Node Checkout that does node publish purchasing with the option for expiration.

  Integrate with Commerce in order to allow you to charge users to
  create nodes. It is possible to have multiple different product
  offerings for each node type, so the user can pick the product they
  want to purchase when creating the node. An example use-case would be
  a classifieds site that charges people to post listings.

It's purchase process is on demand, rather than purchasing a credit quota, so you might have to look at something different to base your project on depending on how important the quota functionality is.

An alternative role-based approach would be the Commerce License Roles submodule and something like the Node Limit module to setup your quota-per-role requirement. You'd also have to find a node expiration solution (e.g. Node Expire) as well.


How to perform a Database API Inner query

You Can refer to this link

However you can try like below

$query->condition('<condition>', $subquery);


When using hook_FORMID_form_alter(), how does one use validation to prevent form submission?

Use form_error($form['delivery_postal_code'], $message) instead of calling drupal_set_message().

OR try

form_set_error('delivery_postal_code', $message);


Why are some of my teasers only show up inside the view preview and not on the page?

For each content type, go to "manage display" and then "Teaser". Make sure all the fields in there are set the same way as the content type that is working.


Just configure your "Default 403 (access denied) page" to "user/login". It's under "configuration / system / site information"


enable secure site only on certain pages

I have two options, but there could be more (quotes included are from their project pages):

Secure Pages:

  A small process which will redirect the required pages to a SSL version of the page.

Context SSL:

  Allow site administrators to make sure certain sections of their sites are always accessed through SSL.

  This module adds a reaction plugin to the Context module and thus benefits from all the flexibility that the Context module provides.


How do I override a module template (.tpl.php) from my custom subtheme?

Copy file from your module folder: /var/www/openatrium/profiles/openatrium/modules/apps/oa_home/oa-home-default.tpl.php
and paste this to your subtheme in following path : /var/www/openatrium/sites/all/themes/my_radix/templates/oa-home-default.tpl.php

open this file and write something like this somewhere under php tags

 drupal_set_message('in new file');

go to admin/config/development/performance/ and clear all cache. Now when you visit to the page where the template is getting rendered, you'll see the message.


I guess the Chosen library version 1.8.3 (released Jan on 22 2018) is a little bit too far ahead of the Chosen module version 7.x-2.1 (released on Mar 23 2017).

Replace the library by an older release (preferably version 1.1.0) and it should work.

From the Chosen module's README.txt:

-- INSTALLATION --

  1. Download the Chosen jQuery plugin
  (http://harvesthq.github.io/chosen/ version 1.1.0 is recommended)
  and extract the file under sites/all/libraries.
  2. ...


Does Commerce Override Username Or Is Username Linked To A Node?

Commerce Kickstart 2 includes the following function, which uses hook_username_alter() to alter the display of the username to be the billing name, which is what it sounds like you're seeing here.

The easiest way around this would be to just delete this function, which is located in "/profiles/commerce_kickstart/modules/commerce_kickstart/commerce_kickstart_user/commerce_kickstart_user.module" from you're Drupal site's root directory.

/**
 * Implements hook_username_alter().
 */
function commerce_kickstart_user_username_alter(&$name, $account) {
  if (!empty($account->uid) && module_exists('commerce_addressbook')) {
    if ($billing_profile_id = commerce_addressbook_get_default_profile_id($account->uid, 'billing')) {
      $billing_profile = commerce_customer_profile_load($billing_profile_id);
      if (!empty($billing_profile->commerce_customer_address[LANGUAGE_NONE][0]['name_line'])) {
        $name = $billing_profile->commerce_customer_address[LANGUAGE_NONE][0]['name_line'];
      }
    }
  }
}


Tools to create registration site with calendar and jQuery/ajax

Creating the form should be as easy as simply  as creating a content type and populate it with your needed fields. This content type will have the date,  the stations, etc etc.

Then, using views will be as easy as list your nodes. If you need to display them in a calendar you can customize your view using third modules, calendars or customizing your own view.

Good luck :-)


You could add news fields to your vocabulary for the link text ('Enquire now') and for the href ('Enquiry')

You'll add these new fields to your view, and then you will be able to format your link like nandhana said.
And the reference will do the rest ...

But be sure that the 'nid' is the lower field among all others, so that you can access to all others fields


How do I implement hook_views_post_execute

My guess is you did not include the use statement at the top of your file that tells the application how to locate the class ViewExecutable. This is a PHP construct and not Drupal specific, which is why it is not always mentioned explicitly in the documentation.

At the top of your file, add:

use Drupal\views\ViewExecutable;

The incoming argument to the hook is of type ViewExecutable, but PHP does not know how to find that class, so it errors out unless you either use the use statement, or change the function signature to:

function idm_views_post_execute(Drupal\views\ViewExecutable $view)

Clear cache and reload. If the error persists, you'll need to provide log(s) to indicate what the actual error that occurred was.

If you copied and pasted the code here for hook_entity_view that would explain why that worked for you:

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook_entity_view/8.6.x

The example here has the full path in the argument list.

hook_entity_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode)


Default to 'this display' when editing views

Not that Im aware of, Im afraid this is the default behaviour. I often catch myself out by not selecting "This block override". :-(

But actually - Breaking the default behaviour for the very first display when you create a new view would mean that every new display you add would have its own settings for filters etc. You would just have to remember to do this everytime you add a view


how to redirect page for anonymous users after number of times?

I don't think there are any contrib modules which can provide this functionality. This is not an ideal way but you can do it like this, I think:

Create a table (id, host_name, hash_code, visit_count)
Whenever you opens your site you will check for host_name, hash_code, and visit_count (if user is anonym)...

Example:

/**
 * 1 - I named the function as 'test' but this function must be called
 * at page load, that's why you need find where to call it. may be
 * TEMPLATE_preprocess_page() or HOOK_init()...
 * 2 - I can't say that here is everything is correct. Correct it if
 * something is wrong.. because I didn't test it...
 */
function test() {

  if(user_is_anonymous()) {
    $host_name = ip_address();
    $hash_code = genCode(35);
    $query = db_select('MY_tABLE', 'mt')
      ->fields('mt')
      ->condition('host_name', $host_name, '=')
      ->range(0,1)
      ->orderBy('id', 'DESC')
      ->execute()
      ->fetchAssoc();

    if(empty($query)/* This user is the first time came to your site */) {
      $record = array(
        'host_name' => $host_name,
        'hash_code' => $hash_code,
        'visit_count' => 1,
      );
      drupal_write_record('MY_TABLE', $record);
    }
    /* This means that the user is anonymous but not a new user */
    else {
      if(isset($_COOKIE['anonym_code']) && $_COOKIE['anonym_code'] == $query['hash_code']) {
        if($query['visit_count'] > 4) {
          drupal_goto('user/register');
        }
      }
      else {
        setrawcookie('anonym_code', rawurlencode($hash_code), 0, '/');
        $visit_count = $query['visit_count'];
        $new_record = array(
          'host_name' => $host_name,
          'hash_code' => $hash_code,
          'visit_count' => $visit_count + 1,
        );
        drupal_write_record('MY_TABLE', $new_record);
      }
    }
  }
}

// Helper function
function genCode($length) {
  $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
  $string = '';
  for ($i = 0; $i < $length; $i++) {
    $string .= $characters[mt_rand(0, strlen($characters) - 1)];
  }
  return $string;
}

I am sure that there are tons of bugs in that function;) I didn't test it... Also You need to implement hook_user_login() to delete a record from MY_TABLE right after the user registers and logs in.

P/S: Use this approach if you don't care about performance...


How to add flag on each field in a node in Drupal?

I am gonna say something different than @Volker, hopefully correct.

Important: You need to install the File Entity module to allow flags on your image field's multiple values.

Just tried this and it works for me, using:

A multivalued Image field; setting its display "Format" to "Rendered file" and the "View mode" to "Teaser", here is a screenshot of my configuration:

A new Flag for File entities; selecting the respective "Display in entity links" view modes. Selecting is optional, it should work out of the box.

And there is what I get:

Hope this helps!


I don't really understand your use case correctly, but probably you need to implement a language negotiation manager. See an example at /core/modules/language/src/Plugin/LanguageNegotiation/LanguageNegotiationBrowser.php.

If you also need to change the url for adding language, or changing how the links in language switcher work, you may need to override some more methods. See an example at /core/modules/language/src/Plugin/LanguageNegotiation/LanguageNegotiationUrl.php.


Make link translatable in Admin from a PHP string in a tpl-file

You can use path aliases for this. Go to /admin/config/search/path/add and create a new alias with the following settings:

Language: Dutch (or whatever it is called in your site)
Existing system path: 'doctor/register'
Path alias: 'dokter/registreer' (or whatever suits your fancy)

Repeat for the French site. Drupal core and contrib modules should automatically pick up the language-dependent aliases. If you're creating a link in a template yourself, make sure you use the l() function to build the entire <a> tag. To get the result in your question, you need something like this:

<div class="well">
  <?php
    $link_options['attributes']['class'] = array('btn', 'btn-large',' btn-primary');
    print l(t('Create an Account'), 'doctor/register', $link_options);
  ?>
</div>


What version of jQuery does Drupal 8 use?

If you want to save some time, you can go to the Javascript console and type jQuery.fn.jquery which works on any site using jQuery, not only Drupal sites.

At the moment Drupal 8 core uses jQuery 2.1.4, but it looks like jQuery 3 has been implemented in Drupal 8.4.x.

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


How do I find the max length of a field (e.g. title field)

The Drupal schema API has a function named drupal_get_schema (D7) or drupal_get_module_schema (D8) that lets you inspect a schema programatically and retrieve field constraints.

For instance, to get the maxlength of the title field in the {node} table, you can use the following in D7:

$schema = drupal_get_schema('node');
$maxlength = $schema['fields']['title']['length'];

You can also inspect the max length of any field used by Drupal simply by looking at the database schema that defines that field.  This will also tell you the names you need to use in the above PHP to get the right value in cases where you're unfamiliar with the schema.

For instance, if you are talking about the title field in the {node} table, you can see when looking at a scheme in a database inspection tool such phpMyAdmin that it is a varchar with a maximum length of 255 characters.


How to format Computed Field as WKT (geofield CCK) with display code

Geofield calculates various values with the geofield_compute_values() functions (see README), so calculating a WKT will not replace it properly. Geocoder supports computed field, so I guess you can use that to populate a geofield.


Views- Show a table of users with each column indicating whether or not a user has a role

Here's a solution using a simple module and a custom field template.

Overview

The view (obviously of the User Table) should only contain one field: User: Name. All of the other Role columns are generated by implementing HOOK_views_pre_view() with a loop for each defined role. The module also defines a custom function that compares the original output (comma-separated list of roles) and returns true if the list contains the current column's role.

The custom views field template simply calls the custom function for each column that corresponds to a role.

This solution will automatically scale if you add/delete roles and adjust if you rename/reorder roles etc.

Module File

You'll obviously need an info file too. I chose to name the module views_urt (User Role Table) - but you can name it whatever you want or include these functions in an existing custom module if you choose.

<?php
/**
 * Implements HOOK_views_pre_view().
 *
 * Adds a field to the User Roles view for each role defined.
 */
function views_urt_views_pre_view(&$view) {
  if ($view->name == 'user_roles') {
    $roles = views_urt_roles();
    $count = count($roles);
    for($i=0;$i<$count;$i++) {
      $view->display['default']->handler->options['fields']['rid_' . $i]['id'] = 'rid_' . $i;
      $view->display['default']->handler->options['fields']['rid_' . $i]['table'] = 'users_roles';
      $view->display['default']->handler->options['fields']['rid_' . $i]['field'] = 'rid';
      $view->display['default']->handler->options['fields']['rid_' . $i]['label'] = $roles[$i];

    }
  }
}

/**
 * Determines if a comma-seperated list of roles contains the role of the
 * current column.
 *
 * @param $pos integer
 *   The column corresponding to the $field->position value in the view.
 * @param $user_roles string
 *   Comma seperated list of Roles (haystack)
 * @return bool
 */
function views_urt_has_role($pos, $user_roles) {
  $pos = ($pos -1);
  $user_roles = explode(',', $user_roles);
  $defined_roles = views_urt_roles();
  foreach ($user_roles as $user_role) {
    if (trim($user_role) == $defined_roles[$pos]) {
      return TRUE;
    }
  }
  return FALSE;
}

/**
 * Helper function that returns an array of roles exluding "Anonymous" and
 * "Authenticated" user.
 *
 * @return array
 *   An array of roles.
 */
function views_urt_roles() {
  $roles = user_roles();
  array_shift($roles);
  array_shift($roles);
  return $roles;
}

Views Field Template File

This template should be picked up by all of the fields in this view for all of the displays. So, since my view is named user_roles, this template is named views-view-field--user-roles.tpl.php.

<?php
if ($field->field_alias == 'users_name') {
  print $output;
}
else {
  // We're assuming that this view only has one field (User: Name). All other
  // fields are generated by the HOOK_views_pre_view() function in the
  // `views_urt.module` and those should be passed through the
  // `views_urt_has_role` function which determines if the $output
  // (comma-seperated roles per user) contains the column role.
  print views_urt_has_role($field->position, $output);
}
?>

Sample Output


How to change the default logo size in the OpenChurch theme?

In your Admin toolbar, click on appearance, then click on settings.

Scroll down to LOGO IMAGE SETTINGS and uncheck Use the default logo supplied by the theme and upload your own logo.


You can edit/add CKEditor settings by implementing hook_wysiwyg_editor_settings_alter(), see Allow configuration of advanced editor settings - comment #52 and later comments for examples.

If you want your own script to run after CKEditor has loaded, maybe How to attach Javascript to a form so that it loads AFTER CKEditor can help you.


Displaying Taxonomy Terms which are used by a Content Type

You should use Views. Here are the steps to do to achieve what you would like to do:

Create vocab. "Category":

Create content type "Suppliers" with a "Term reference" field to "Category" vocabulary:

Create three "Suppliers" contents in "Agriculture", "Business" and "Blabla" categories - so these 3 should be listed in your block.
Add a new view at admin/structure/views/add with these settings:

Add a new field "Content: Category":

(here are the settings)
Remove "Content: Title" field (1 , 2)
Set some descriptive names (like machine name, block name, display name, etc.), AND set Sort Criteria to "Content: Category (asc)":

Save
Go to admin/structure/block, set "Supplier Categories block" to be displayed in the "First sidebar" (or "Sidebar first" in Bartik) or any other, then hit "Save blocks":

You are ready.


How do I programmatically render a view that has exposed filters?

You can use this code in custom block can also set permission.

 use Drupal\Core\Form\FormState;
 use Drupal\views\Views;
   $form = [];
   $view_id = 'blog_landing_page';
   $display_id = 'page_1';
   $view = Views::getView($view_id);
   if ($view) {
   $view->setDisplay($display_id);
   $view->initHandlers();
 $form_state = (new FormState())
  ->setStorage([
   'view' => $view,
   'display' => &$view->display_handler->display,
   'rerender' => TRUE,
   ])
   ->setMethod('get')
   ->setAlwaysProcess()
   ->disableRedirect();
   $form_state->set('rerender', NULL);
 $form = \Drupal::formBuilder()->buildForm('\Drupal\views\Form\ViewsExposedForm', $form_state);
    }


Can drupal be installed on a subdomain and used on the main domain?

Yes, you can have Drupal run in subdomain and have a completely different web site coded on the domain root.

Just make sure that the subdomain is directed at the Drupal root. To be clear, the Drupal root directory is the one that contains the following files:

authorize.php
CHANGELOG.txt
COPYRIGHT.txt
cron.php
.gitignore
.htaccess
includes
index.php
INSTALL.mysql.txt
INSTALL.pgsql.txt
install.php
INSTALL.sqlite.txt
INSTALL.txt
LICENSE.txt
MAINTAINERS.txt
misc
modules
profiles
README.txt
robots.txt
scripts
sites
themes
update.php
UPGRADE.txt
web.config
xmlrpc.php


How can I translate the particular field or content in english to german language?

It's very easy, you need to install the Internationalization module where you find  some sub-module to do that .
Youn need to install the Localization Update module it's very helpful .


Make custom form submit data to view filters

Views exposed filters are using information supplied by the relevant GET parameters so this use case is actually very simple. You only need to build the correct url in your custom form submit handler from the received data and then redirect the user. A basic example to illustrate this:

function mymodule_custom_search_form($form, &$form_state) {
  $form['key1'] = array(
    '#title' => t('Key1'),
    '#type' => 'textfield',
  );
  $form['key2'] = array(
    '#title' => t('Key2'),
    '#type' => 'textfield',
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Search'),
  );

  return $form;
}

function mymodule_custom_search_form_submit($form, &$form_state) {
  $options = array('absolute' => TRUE);
  $key1 = trim($form_state['values']['key1']);
  if ($key1) {
    $options['query']['key1'] = $key1;
  }
  $key2 = trim($form_state['values']['key2']);
  if ($key2) {
    $options['query']['key2'] = $key2;
  }
  $form_state['redirect'] = url('customsearch', $options);
}

If the user submits the form with "key1" value "one" and "key2" value "two" then they will be redirected to "customsearch?key1=one&key2=two". What you need to note is that the GET parameters "key1" and "key2" must match with what you've set in the relevant view: click on your filter criteria -> "MORE" link at the bottom and then check/modify "Filter identifier".


Try this at the top of your code:

global $node;
if (empty($node->nid)) {
  node_save($node);
}

Worked for me in D5 and D6.


Allow users to manage their own mailing list?

Start with adding a multi-value field to store eMail addresses. Say with a machine name like field_email_addresses. Assume the content type you're using for this is "Article" (pick whatever fits).

With the above in place, uou could use the Rules module to achieve your goal. Similar to what is shown in my answer to "How to check with Rules if a new element has been added to a list in a node?". By using the rule included in that answer, you can discover scenarios such as these:

Value user3@example.com was removed from the multi value field.
Value user2@example.com was added to the multi value field.

Here is a simplified version of the rule that only shows the inserted values:

{ "rules_verify_updates_to_selected_email_ids" : {
    "LABEL" : "Verify updates to selected eMail IDs",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules_conditional", "rules" ],
    "ON" : { "node_update--article" : { "bundle" : "article" } },
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-email-addresses" ] },
          "ITEM" : { "current_email_id" : "Current eMail ID" },
          "DO" : [
            { "CONDITIONAL" : [
                {
                  "IF" : { "NOT list_contains" : {
                      "list" : [ "node-unchanged:field-email-addresses" ],
                      "item" : [ "current-email-id" ]
                    }
                  },
                  "DO" : [
                    { "drupal_message" : { "message" : "Value [current-email-id:value] was added to the multi value field." } }
                  ]
                }
              ]
            }
          ]
        }
      }
    ]
  }
}

If you just add a field with machine name "field_email_addresses" to your articles content type you should be able to import this rule in your own site and experiment with this rule in your own site to see it at work (for nodes of content type "Article", adapt this type to fit your needs).

All that's left to do is to transform the message that is displayed by sending an appropriate eMail (which is like a Rules-getting-started exercise). That will allow you to eMail relevant parts of the node whenever some eMail Id is added to that field already.

Some suggestions to further improve this solution:

Send it to all (not just updated) eMail ids mentioned in the field_email_addresses field, by creating another rule that is triggered with Rules Event "After saving a new node of content type Article".
Also use the Flag module so that if the node is flagged by the node author (and only then), send it to all eMail ids mentioned in the field_email_addresses field (something that is straight forward to do with another rule).
Variation of the previous item (which does not require the Flag module): add an extra (boolean) field to Articles, to indicate something like "Send this node as an eMail now".
Replace that field_email_addresses field (related to the Article content type) by a similar profile field with similar purpose. So that by combining it with the Views Rules module, you create a Rules loop to eMail all those users when such article is created, flagged, etc.

The above are just some basic solutions to implement what you're looking for. To further improve it (eg: combine it with importing a CSV list) should really be a different question.


Randomly display questions in Webform - to use as an exam

You can use form alter to access $form array and display/hide specific elements, more details: https://www.drupal.org/docs/8/modules/webform/webform-cookbook/how-to-programmatically-hide-and-show-webform-elements.

function CUSTOM_MODULE_form_webform_submission_WEBFORM_NAME_add_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  $elements = &Drupal\webform\Utility\WebformFormHelper::flattenElements($form['elements']);

  $elements['question_one']['#access'] = FALSE;
  $elements['question_two']['#access'] = FALSE;
}


How to define custom content entity one to many relationship?

Sounds like you need to add setCardinality(-1) to your B reference field definition in your A entity. This will change the B reference field to support an unlimited number of references instead of 1, the default cardinality.


Implementing a search and results page in the admin interface

Drupal only has only pager implementations for DB queries, but you can use the pager system manually for data in external sources. There are a couple of examples on the pager_default_initialize() docs that should get you started.
Anything other than q as the param name should work - Drupal uses q as the path param in its rewrites, so it's probably trying to find a route of foobar in your example.


To rename the file, you'll need to use PHP's rename() function. To do so, you'll want to get the file's full local path using drupal_realpath() like so:

// Fetch the local absolute path of our image
$local_path = drupal_realpath($file->uri);

Once you've renamed the file, you'll need to modify the file URI (and potentially other attributes-- use print_r($file) to check).

The wording in the docs is a little weird to me, it says "when a file has been added to the database" which means to me the file metadata has already been saved to the database. However, the example shown in the docs seems to edit this info (but without using &$file ...?) without having to return the file object. Strange.

Anyway, your code might look something like this:

function mymodule_file_presave($file) {
  if ($file->type != 'image') {
    return;
  }
  if (!empty($file->filename)) {

    // Will likely be 'public://'
    $scheme = file_uri_scheme($file->uri);

    // Get full path of image location
    $local_path = drupal_realpath($file->uri);

    // Create new name using drupal scheme format
    $new_uri = $scheme.'new_name_here.jpg';

    // Actual OS rename of file
    rename($local_path, drupal_realpath($new_uri);

    // Update $file object with new uri
    $file->uri = $new_uri;

    // Not sure if this is still needed...
    $file->destination = $file->uri;
  }
}


Character counter for textarea in webform

For webforms use the Webform Countdown module instead of maxlength. Here is a quote about it (from the module's project page):

  Provides a textarea component for Drupal webforms with a configurable, twitter-style dynamic word or character count.


That page seems to be a Views page, but there is no way of telling from the screenshot if you're using a special module to build those page or simply Views.
If it's Views then you can Edit the particular View, it has the Title option for the Page, that's where you change it.
You can find list of all Views under Structure on the top menu.


One could modify the auto increment field of the users table in the database. Similar to https://stackoverflow.com/questions/970597/change-auto-increment-starting-number.

ALTER TABLE users AUTO_INCREMENT = 5000;


You can use field_info_instances() which:

  Retrieves information about field instances.

In the case of taxonomy terms the code would look like this:

$instances = field_info_instances('taxonomy_term', $vocab_machine_name);

The $instances array will contain (amongst other things) the machine names of all the fields attached to the term, if you want further information about any or all of those fields you can run the names through field_info_field().

I think the file that function lives in is included by default but if not just add this before you call it:

module_load_include('inc', 'field', 'field.info');


I wrote a block in Drupal 8 to render a menu based on the http headers
  of the request, which contains the users' information from the idp.

If you want to build a new page for every request then there is no point in using the page cache, so I would uninstall the core module Internal Page Cache.

Edit: Just read in drupal planet, BigPipe will be available in Drupal 8.1, then you have a perfect solution for this. But in the meantime running a site without page cache for anonymous users is fine, you still have the dynamic cache and can use the cache tags.


Anonymous users skip comment approval but they shouldn't

On my side, the problem was the use of the cleantalk module.

In this module, in the configuration page: admin/config/content/cleantalk/settings

You must uncheck "Enable automoderation" if you do not want to override the "Skip comment approval" permission


Is there an efficient easy way to test Drupal code while developing it?

As you're comfortable with Grunt, I've got a Gruntfile that I wrote that I use as a stub for most projects. You can find it here github.com/Chapabu/grunt-drupal-standards/. Just clone it to your project root and follow the installation instructions.

There are Drupal specific tasks there for doing to following:

PHP linting of any custom code
JS linting
CSS linting
Automatic clearing of theme registry when new templates are found
PHP_CodeSniffer tasks to ensure your code mets the Drupal Coding Standards

I need to make a few updates (i.e. remove Casper stuff, remove Compass tasks as I now use Libsass etc) but the tasks that are there should be enough to get you started.

There are also Grunt tasks for running PHPUnit tests or PHP Mess Detector (to name a couple of helpful suites) so it's pretty easy to add tasks to watches.


A lot of those classes are added by the classy base theme templates. You'll be able to get rid of them with a theme based on stable instead.


How to shift/change timestamp in a scheduled rule?

Yes, the timestamp of when the task is to be scheduled is stored in rules_scheduler db table, in date field. You can run a query like:

db_update('rules_scheduler')
  ->expression('date', 'date + 86400') // 86400 = 24 * 60 * 60
  ->condition('tid', $your_task_id)
  ->execute();


The Drupal way of doing this is to pull out the content from your HTML file; you don't need to paste the entire contents into the node body, that will break your site's theme.

Once you've created the node with the content you've pulled out of the HTML file, you can use the Content Access module to restrict viewing of the node to only authenticated users.


how to hide the adminblog link in the teaser

Try to use something like the below code to hide admin's blog from teaser's view in your theme's template.php, hope it will work for you:

function THEME_preprocess_node(&$variables) {
      if ($variables['view_mode'] == 'teaser') {
        if ($variables['type'] == 'blog' && (arg(0) != 'blog' || arg(1) != $variables['uid'])) {
          unset($variables['content']['links']['blog']['#links']['blog_usernames_blog']);
          unset($variables['content']['links']['node']['#links']['node-readmore']);
        }
      }
    }


Sometimes things compress too well; ie empty string. Sometimes things don't compress at all; ie already compressed. In both cases I opt to use the original file since minification of already minified js can sometimes cause js errors. You can variable set it if you want to adjust the min/max cutoff.


Import a big website using Feeds XPath Parser

Feeds is a very powerful module, and it is much more than a basic RSS aggregator.  Many people are beginning to leverage Feeds as a migration tool, and Feeds XPath Parser is emerging as a popular way to import static HTML documents.  I set up a quick parser to import this page, so hopefully the example will assist you with what you are trying to do.

First, it is important to enable the debugging options when using Feeds XPath Parser.  This will show you what text was matched by your various queries.

Second, the image below shows the Context and XPath queries I used to import this page.  The result is that it pulls the HTML title tag along with the content under an element containing the "question-page" class.

If you are looking to pull the header elements, I think you will have to explicitly use "h1", "h2", etc. in your XPath query, but I am not sure about this.  The downside of this approach is that you will have to have a source node for every page you are importing, or you will have to find a way to batch submit the import form either programmatically or through some automated tool such as Selenium, JMeter, Firefox Macro, etc.


\Drupal::database() ->insert - Error: Call to undefined method Using ->condition()?

As described in Insert Queries, the object returned from \Drupal::database()->insert() doesn't have an condition() method. If the purpose of the code is creating a new database row if it doesn't exist, or update it if it already exists,
the code should use the object returned from \Drupal::database()->merge(). See Merge Queries.

For example, the following code will create a new row if none of the existing rows contains the value $name for the name database column; otherwise, it will update the existing matching row. ($connection is the object returned from \Drupal::database() or a Connection object obtained via dependency injection.)

$connection->merge('example')
  ->key(['name' => $name])
  ->fields([
      'field1' => $value1,
      'field2' => $value2,
  ])
  ->execute();

It is also possible to use a set of values when the row is created, and another set when the row is updated.

$connection->merge('example')
  ->insertFields([
      'field1' => $value1,
      'field2' => $value2,
  ])
  ->updateFields([
    'field1' => $alternate1,
  ])
  ->key(['name' => $name])
  ->execute();

What that documentation page doesn't show is how to use multiple keys, as the following code does, using Merge::keys() instead of Merge::key().

$connection->merge('example')
  ->insertFields([
      'field1' => $value1,
      'field2' => $value2,
  ])
  ->updateFields([
    'field1' => $alternate1,
  ])
  ->keys(['name' => $name, 'nickname' => $nickname])
  ->execute();

The only limitation is that the values passed to keys() are all used to match a single database row. In other words, the last snippet I shown doesn't look for a row containing $name in the name database column or a row containing $nickname in the nickname column.

In cases more complex, where the Merge class doesn't help, you need to first check what the database table contains and take the necessary action basing on the table content (which involves writing more PHP code to check the database content).


The PHP filter module was removed from core, because of the inherent security problems it presents.

It now exists as a separate contrib module, but beware that even the module description itself warns against using it:

  Warning

  Enabling this module can cause security and performance issues as it allows users to execute PHP code on your site. There are better alternatives out there that do not expose such vulnerabilities on your site.


Not sure if this is the correct approach, but it worked - I used a menu_alter hook to move the menu items to a different menu.

function mymodule_menu_alter(&$items) {
    $items['user']['menu_name'] = 'unused-menu';
    $items['user/logout']['menu_name'] = 'unused-menu';
}


How do I avoid the maintenance screen on database errors?

If you have a serious / fatal database error, you're probably not seeing the 'maintenance page' but the db_offline page which usually displays errors direct to screen. What kinds of database errors are you experiencing?

Assuming your site is not in maintenance mode, few things you can check and set:

Check the settings under admin/config/development/logging and make sure you have it set to display 'all messages'
Make sure you have php set to display errors -- you can add the following in your settings.php file to increase your error_reporting level:

error_reporting(-1);
$conf['error_level'] = 2;
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);


How do I programmatically find the core version?

I found this example in MetatagNodeTranslationTest.

To find the drupal version in your code,

\Drupal::VERSION

will return it.

If you need to compare

if (floatval(\Drupal::VERSION) <= 8.3) {
  // do some stuff.
}


You add a filter criteria that checks the image's file id (fid):

Content: Image (field_image:fid)

Operator: Is not empty (NOT NULL)


Disclamer

I am using a hook in a way that is different from the usage that is documented on Drupal.org API. See the notes at the end of the question.

You could achieve what you want by implementing two hooks:

hook_module_implements_alter()

function mymodule_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'node_load') {
    unset($implementations['user']);

    // Put mymodule_node_load() to the beginning of the list.
    $group = $implementations['mymodule'];
    unset($implementations['mymodule']);
    $implementations = array('mymodule' => $group) + $implementations;
  }
}

hook_node_load()

function mymodule_node_load($nodes, $types) {
  if (path_is_admin($_GET['q'])) {
    $uids = array();
    foreach ($nodes as $nid => $node) {
      $uids[$nid] = $node->uid;
    }

    $user_fields = db_query("SELECT uid, name, picture, data FROM {users} WHERE uid IN (:uids)", array(':uids' => $uids))->fetchAllAssoc('uid');

    // Add these values back into the node objects.
    foreach ($uids as $nid => $uid) {
      $nodes[$nid]->name = $user_fields[$uid]->name;
      $nodes[$nid]->picture = $user_fields[$uid]->picture;
      $nodes[$nid]->data = $user_fields[$uid]->data;
    }
  }
}

The code I used for hook_module_implements_alter() is different from the example code shown in the documentation, which just alters the order in which different implementations of the same hook are invoked.

function hook_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'rdf_mapping') {
    // Move my_module_rdf_mapping() 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['my_module'];
    unset($implementations['my_module']);
    $implementations['my_module'] = $group;
  }
}

In general, it is not a good idea to avoid a hook implemented from another module is invoked. Modules that change their behavior because a hook implemented from another module is invoked normally use module_exists(), rather than module_implements(), which means those modules normally make the assumption that the module being enabled is sufficient for that specific hook to be invoked.
Generally speaking, there could be modules that depend from the data injected from the hook you are trying to block. It is not said that avoiding user_node_load() executes its SQL queries would avoid another module executes its own SQL queries with a decrement of performance even worse.

If you are sure that none of conditions I described are verified, you could implement the code I shown, at your own risk. Be prepared to verify there aren't any unwanted consequences, and check what the code used by the modules you use in the site is doing.


What can I use to layout the content type form input when creating content?

Display Suite is capable of formating form layout, as well.

  Modules included:

Display Suite: The main module to rearrange your fields.
Search: extend the search results for Drupal core or Apache Solr.
Extras: extra functionality like semantic fields, region to block, hide page title etc.
Forms: style the layout of forms.
Format: provides a PHP filter with entity context (only 7.x-2.x and higher)
UI: Manage custom fields, classes and view modes through UI (only 7.x-2.x and higher)

You should enable the Display Suite Forms module, which is shipped with DS.

Under the 'manage fields' tab of your content type

admin/structure/types/manage/your_content_type/fields

At the bottom, you have an option to select a layout for the form.


Service is being instantiated during installation with unknown entity type call

While it will require an additional call when you require it, you could just store a reference to the entity type manager only.

Especially for entity query, you must not do it like this anyway. A query object is not re-usable. You can't execute multiple queries from a single instance.

Additionally, you can simplify your dependencies if you call $storage->getQuery() instead of using the entity query for that (which does the same internally).


How do I setup the date picker popup for date fields in a view?

This is usually because the ui.datepicker wasn't added as a dependency in your theme as this isn't usually enabled by default in themes.

I use the seven theme for administration, so I had to add the line:

  - core/jquery.ui.datepicker

Looks like this in my seven.libraries.yml file:


Attach user created content (in this case a gallery view) to a Profile 2, per user

I am going to answer the first part of my own question:

If you need a gallery per user and you need to attach it to a profile2 type. Follow the tutorial linked to in above question, to create each gallery.

Clone the gallery view (EVA Field), and change in Entity Content Settings.
For Entity Type use Profile.
For Bundles, the profile types you want the view to be attached to.
For Arguments, choose token, and select profile2:user:uid.
Go to Advanced and add a Content: Author relationship and Contextual Filters: (author) User: Uid. In the settings of the Contextual filter choose author for Relationship (that's what appear between brackets) and also for WHEN THE FILTER IS NOT AVAILABLE select Provide Default Value -> User ID from URL. And below, Specify Validation Criteria > Choose "User" as the Validator from the pull down, and "Allow both numeric UID's and string username (I don't know if that's strictly necessary but broadens the possibilities).
You may want to (I did) restrict the selected roles to those that have that kind of profile2 type. Done.

Now I need to figure out how to restrict the "Add more images" link. If anyone can answer that, I appreciate.

I have created a URL alias pattern for the images content type that includes the USER ID in the URL when an image is uploaded.


If you have access to the database check the table config for all entries starting with views.view.*
One of these entries might be empty or with a corrupt uuid. If so, take a backup of your database and try to manually delete this entry and see what happens.

Update
According to coments below I suggest taking a database backup and then delete views one by one from the database until the error is gone


How to display all nodes by user on his profile page

1.Create a view for content of type all 2.Inside the view display node title and all other fields as per your requirement. 3.Add a contextual filter content : author uid 4.While adding that you will have a option for provide a default value 5. select that option and inside that use filter by 'currently logged in user'. 6. Save it by this you will be able to see all the nodes of current logged in user. 7. Inside the path you can enter just any path like '/my-nodes'. and you are done.
8.If you want you can avoid providing default value and switch to manual input
by placing the path as '/my-nodes/%' and then just add contextual filter as 'content : author:uid' without default value(depends as per the requirement).
9.For user name you can add a relationship content author:uid then
 in the contextual filter use User name with relationship author:uid