How to add a page redirect in Drupal htaccess file or otherwise?

I'd suggest you consider the Rules module as that "other module" you are looking for. Using an approach as described in my answer to the question "How to use the Rules module to implement a custom redirect for an outdated URL?" ...

Using that technique, you can also solve your requirement about it being "temporary" (that's just a matter of some appropriate rules Condition to be added in your case).


Using Drupal 7 & Omega 3.x - Page Titles + Edit Tabs are not showing up on node content types!

it seems that it is a bug in omega. https://www.drupal.org/node/1906744 -- this took quite awhile to figure it out! The culprit was actually the "main content" block not being enabled on the blocks page. This was because I was primarily using context in positioning my blocks and left the default blocks page empty by not assigning anything. It seems that the theme has to detect the "main content" block in order to show the tabs. So the fix is just assigning the "main content" block back into the content region.


Since you are querying some tables to get the value of an entity field, I would rather use the EntityFieldQuery class.

To answer your question, what you want to achieve can be obtained by concatenating strings to the the query string.

$query = "The first part of the query";
$args = array();

if (isset($form_state['storage']['etat_livre'])) {
  $query .= "WHERE field_etat_du_livre_value = :field_etat_du_livre_value";
  $args[':field_etat_du_livre_value'] = $form_state['storage']['etat_livre'];
}

$query .= "ORDER BY field_etat_du_livre_value ASC, created DESC";

$result = db_query($query, $args);

As side note:

The query should not use back-ticks
The reserved words should be written in upper case


How do I override views-view-summary-unformatted.tpl.php inside my own theme?

I know this is old but today I struggled with this and thought I should provide a solution.

First, you have to rename your copy of 'views-view-summary-unformatted.tpl.php' so views can discover it. It should be named 'views-view-summary-unformatted--my-view.tpl.php'.

You then need to click the 'rescan template files' button under the theme information in the view.


The master page is always present in a defined View, although it may not be visible.  To toggle its visibility on and off go to the views list page and select the 'Settings' Tab.  Check or uncheck the "Always show Master Display" checkbox.

When you begin a new view and generate the a page or block, the hidden master is also being completed.  It serves as the template for any new pages or blocks you create without cloning.  I keep the master display visible and will use it as the template for views with many alternate displays.


Is Filter Contains all words working well?

Change your Operator to Starts with and Apply.

If you need use a specific filter you can alter your view query with this hook:

function YOUR_MODULE_views_query_alter(&$view, &$query)
{
    if($view->name == 'NAME') {

    //here modify your query

    }

}


How to pass along current $form_state for an #upload_validators callback?

It appears we can use this code to get the $form_state, however, there are no $form_state['values'].

$form_state = form_state_defaults();
// $form_state is passed by reference and will be updated automatically.
form_get_cache($_REQUEST['form_build_id'], $form_state);

I was able to find the value in
$form_state['field']['field_NAME']['und']['entity'][0]->field_NAME['und'][0];

However, this will not pass along the value you set in another field without first setting an #ajax callback on that field, the callback can just return NULL, it is just to update the form.

In our case we disable the file upload field until the other field has first been set.

Hopefully this will help someone or most likely myself in a year from now.

sources: https://twitter.com/eojthebrave/status/743544054030336000 && How do I load the $form_state for a form loaded with drupal_get_form?


DS Views Block Field page visibility settings

Go to /admin/structure/block under the disabled region, click on Place block button and try searching for it on the search box, if you find it, place it and then Configure.


Node Migrations with programmatic url aliases

If I understand correctly, based on your example, you'll need to switch the to and from URLs. If you want the new node to display the redirects in the node edit form, the node ID should be as follows:

$redirect->redirect = 'node/' . $node->nid;

FYI - programmatic redirect creation here.


Views slideshow displaying multiple items

You need to add views slidehshow cycle module as well


Indeed, all you can do is specify the other CKEditor plugins your CKEditor plugin depends on. It is guaranteed that those are loaded first. But beyond that, there are no guarantees. Nor should there be.

So, just specify the CKEditor plugins your plugin depends on in getDependencies(). This ensures Drupal informs CKEditor about where those plugins live.

Then, it is up to the CKEditor plugin itself (i.e. the JavaScript code) to specify the necessary dependencies, CKEditor then ensures the depended plugins are loaded first.


Is there a way to figure out the block machine name?

You can query the blocks by the plugin id. This is the id of a block plugin or for derivatives like a view block (which you probably are looking for as you've mentioned a view machine name) with additional parameters:

$plugin_id = 'views_block:' . $view_id . '-' . $display_id;

Where $view_id is the view machine name which you find in the Views UI and $display_id is the display machine name, usually block_1 for the first block of the view.

Then get all blocks placed for this plugin id and print the block machine names or use the loaded blocks in your code:

$blocks = \Drupal::entityTypeManager()->getStorage('block')
  ->loadByProperties(['plugin' => $plugin_id]);
foreach ($blocks as $block) {
  echo $block->id();
}

Add a theme or region to loadByProperties() if needed:

['theme' => 'bartik', 'region' => 'header']


Use simplenews module

Simplenews

  Simplenews publishes and sends newsletters to lists of subscribers.
  Both anonymous and authenticated users can opt-in to different mailing
  lists. HTML email can be sent by adding Mime Mail module.

  Simplenews 7.x-1.0 has finally been released which includes a number
  of other important bugfixes, especially in the upgrade path.

  Features Sending nodes as newsletters to subscribers Multiple
  newsletter categories with separate settings Per category and
  multi-signup Blocks and Pages Subscriber management including
  mass-subscription and export Optional E-mail confirmations for
  anonymous users Customizable newsletter templates Support for HTML
  (including text alternative) newsletter when used in combination with
  a supported mail system module Views and Rules integration Support for
  multi-language newsletters


This issue is solved. The issue was a malformed URI that was imported from the Drupal 6 website. The search indexing failed when it encountered this content (comment).

It turns out that it was old spam comments from the D6 site. I was able to delete those and indexing is working now.


How do I stop a module from installing optional configuration, or make sure it's installed by the time I want to remove it myself?

Hmm, have you tried in the .profile file an hook_install_tasks?

Or maybe with the hook_install_tasks_alter.

/**
 * Implements hook_install_tasks_alter().
 */
function MODULE_install_tasks_alter(array &$tasks, array $install_state) {
  $tasks['install_finished']['function'] = 'CALLBACK_post_install';
}

And deactivate the view in the callback.


Drush - /usr/bin/drush: line 129: /usr/bin/php: Success

just run

  $ /usr/bin/drush

if it runs it means that your symlink to the drush command is wrong


Altering the text after a checkbox using the Drupal Form Api

You can give the $options as an array of value and label. And the label can then be given as a link using l().

'#options'       => array(
  'facebook'     => l(t('Facebook'), 'http://www.facebook.com'),
  'twitter'      => l(t('Twitter'), 'http://www.twitter.com'),
),


How to rebuild route cache programmatically

If you would like to clear route cache programmatically in drupal 8, use the following:

\Drupal::service('router.builder')->rebuild();


Looking for a Module to allow presentation of data like a Microsoft Access Table

Take a look at Node Table module.

Generates sticky headers automatically
Supports flexible column sorting on none, one, or multiple columns
Supports a default sort column with asc / desc option
Supports add, delete, edit of rows and columns
Supports drag and drop reordering of rows and columns (row reordering works only when no column sorts are enabled)

  NodeTable module is a versatile module for handling HTML tables on
  Drupal sites. The module provides functionality for creating,
  uploading, editing, and presenting HTML tables within nodes or as
  nodes.


You need to call the current theme URL and concatenate it with your alternative logo

    <img src="<?php print drupal_get_path('theme', 'THEME_NAME'); ?>/images/logo.png">

<?php print t('Copyright'); ?> &copy; <?php echo date("Y"); ?>


Views Infinite Scroll progress Indicator

I was able to do this as below.

Add the below in your custom.js file

// Sets the fullscreen progress indicator.
(function ($) {
  'use strict';
  Drupal.behaviors.privacyPolicyLinked = {
    attach: function (context) {
      Drupal.Ajax.prototype.setProgressIndicatorFullscreen = function () {
        this.progress.element = $('
&nbsp;
');
        $('body .pager').before(this.progress.element);
      };
    }
  };
})(jQuery);

And in your custom.css , add your styles as below

.ajax-progress-fullscreen {
  background: url($assetsPath + '/images/status-active.gif') no-repeat center center;
  min-height: 16px;
  opacity: .9;
  padding: 3px;
  vertical-align: middle;
  width: 16px;
  position: relative;
}


Sending client to channel messages with nodejs integration

I can no longer reproduce this. Since the module did not update in the meantime I guess it a new version of socket.io that got updated via npm update.

The posts here have been of great help in further development of the functionality: http://theoleschool.com/tags/nodejs


field collection - taxonomy term can't display

By default the taxonomy term page will list all content (NODES) that is referenced by this term. In your case you are referencing the field collection item by this term.

To display the nodes in the term page you need to create a new view as below:

Create a view of type content and add a relation to the field collection type.
In the view filters you need to add filters by content type and another filter to restrict the result by the taxonomy you are using.
Add a contextual filter that will filter the results by the term id - provide a default value from the URL, thus will ensure that you are displaying only nodes referenced by the term id you are viewing.

now you need to use page manager, context, custom code, etc... to place this view in the term page.

How it will work:
When you are viewing a term page it will display the view we previously created. this view will extract the term id from the URL and query nodes related to the term.


how to get backtrace information for php errors in drush

This should be posted as a Feature Request in the Drush issue queue.  I started that off for you here:  http://drupal.org/node/1804600


Background images using Breakpoints and Picture

My solution was to use Group Background Image with the patch that you can get here. This allows background images, through the integration of the Picture and Breakpoints modules. The configuration is super easy, and you can change existing div field groups into background images in a split second.


ajax modified form drop down doesn't save

Ok, I finally got it right, here's the code of the function which does the work:

function chapter_sponsors_levels_set_levels($gid, &$form, &$form_state) {
  $query = 'Select * from {og_vocab_relation} where gid = :gid';
  $results = db_query($query, array(':gid' => $gid));
  foreach ($results as $result) {
    $vid = $result->vid;
  }
  $chapter_vocab = taxonomy_vocabulary_load($vid); //get the vocabulary associated with the group
  if(!empty($chapter_vocab)) {
    $terms = entity_load('taxonomy_term', FALSE, array('vid' => $chapter_vocab->vid));
    $form['field_sponsor_level']['und']['#options'] = array('_none' => '- None -');
    foreach($terms as $term) {
      $term_names[$term->weight] = $term->name;
    }
    ksort($term_names); //sort the terms by their weight and set them as the dropdown values
    foreach($term_names as $name) {
      $form['field_sponsor_level']['und']['#options'][] = $name;
      $form_state['field']['field_sponsor_level']['und']['field']['settings']['allowed_values'][$name] = $name;
    }
    $form['field_sponsor_level']['und']['#default_value'] = $form_state['build_info']['args'][0]->field_sponsor_level['und'][0]['value'];
    $form['field_sponsor_level']['und']['#title'] = $chapter_vocab->name;
  }
}


Put the Flexslider library in sites/all/libraries.

Check Status page for error with flexslider (admin/reports/status).


In Ubercart Which Hook is reponsible for adding product to the cart page(On clicking add-cart-button)?

If you want to alter the cart item, then you can use hook_uc_cart_alter of ubercart.

This hook is not in documentation of ubercart 7 but its still working for Ubercart 7.

  This is called every time the cart is rebuild (e.g. when products are
  added), so it's a good place to alter the cart item.

I have checked uc_coupon module and hook hook_uc_cart_alter is implemented into that module. So, you can try this hook.

Edit:
Code snippets to modify the price of item

/**
 * Implements uc_cart_alter.
 */
function mymodule_uc_cart_alter(&$items ) {

  foreach ($items as $index => $item) {

   //you can add condition for your bid product

    $items[$index]->price = 100;
  }
}

For reference:

http://www.ubercart.org/docs/api/hook_uc_cart_alter


Renders my safe_value instead of the value

I needed to change the filter of the field. That fixed the problem.


There is sharethis contrib module. You can use this module to share contents in lots of social media.

Also, this module can be used as block, content field and links area.

So, you can put a sharethis block in a view.

Here's what you need to do.

Install & enable module.
Under Configuration > web services, configure sharethis settings. (For the view, you should check block under content at the bottom)
In block settings, place sharethis block on content region.
Configure the sharethis block to only show it on the view.


Responsive Image Style:
Here you can tell WHEN and WHAT STYLE to apply
Image style:
Here you can tell WHAT OPERATION should take place on the original image.

Create a new image style with scale & crop (or whatever fits you) first,
and then set this image style to the right Responsive Image Style interval (in your case the smallest)


The Search module implements hook_cron(), and its implementation it invokes hook_update_index() to update the search index. One of that hook implementations is node_update_index(), which

Loads some nodes whose IDs are returned from a query
Renders those nodes, and passes their body content to search_index()

If the node body contains PHP code that redirects the users to a different page, or an implementation of hook_nodeapi() redirects the users when a node is viewed, that can cause problems to cron tasks.


There should be a crontab task for Drupal. If there is none, it falls back to Poormanscron - integrated into Drupal core since 7.x

  The module inserts a small amount of JavaScript on each page of your site that when a certain amount of time has passed since the last cron run, calls an AJAX request to run the cron tasks. However, this approach requires that your site gets regular traffic/visitors in order to trigger the cron request.

When check is initiated, it loops over modules and checks their status from URLs determined in function _update_build_fetch_url define at line 287* of update.fetch.inc file, in update core module.

For more details, examine update core module, code is pretty well documented.

Information valid for Drupal 7.25, may slightly change with version.


Using hook_form_alter to hide a field in a view exposed filter

One possible way to alter the exposed filter for specific view is the following:

/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
        // Check if the form contains exposed filter form element.
    if ($form_id == 'views_exposed_form') {
        // Here you can define the check for specific view so that it doesnt apply to all views.
        $view = $form_state['view'];
        // If you have multiple display in view than you can add a check for specific display
        // as '$view->current_display == 'DISPLAY_NAME' in the below if condition with '&&'.
        if ($view->name === 'MY_VIEW_MACHINE_NAME') {
            // Add your code for specific form.
        }
    }
}

And for hiding the label of particular element, check #title_display: Indicates how the label should be rendered. The label includes the #title and the required marker, if #required. If the #title is empty but the field is #required, the label will contain only the required marker.

  '#title_display' => 'invisible'

UPDATE:

Also you may try using hook_form_views_exposed_form_alter as below:

/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_views_exposed_form_alter(&$form, $form_state, $form_id) {
  // To check the form id of your view.
  print_r($form_id);
}


The Email Example in the Examples Project should be just the thing for you.


drupal_add_js does not support an ID attribute as it seems.
However, as a workaround, you can use drupal_add_html_head to add stuff to the head section.

Ex:

$element = array(
  '#tag' => 'script',
  '#type' => 'html_tag',
  '#attributes' => array(
    'src' => 'https://www.docserver1.co.uk/dsxc/client.js?acc=xx&integrated=true',
    'type' => 'text/javascript',
    'id' => 'dsxc_script',
  ),
);
drupal_add_html_head($element, 'dsxc');

//dpm(drupal_render($element)); Gives the following:
// <script src="https://www.docserver1.co.uk/dsxc/client.js?acc=xx&amp;integrated=true" type="text/javascript" id="dsxc_script" />

You can always embed these scripts in your html.tpl.php file, but if you want to add the stuff conditionally, I think this will work.


What is the best way to update Drupal periodically using a cron job?

How can we automate our updates when these exceptions take place?

Updates are not automatic. The update manager module will tell you (in the admin) when critical updates or updates are available for core or contributed modules. But nothing will automatically update it all for you. You can also have the system email you when updates are found, too - per site. This is also helpful for staying informed.

You could theoretically "auto update" with a CI/build workflow that builds X times per day, but there is more inherent risk there of breaking the site unless you are strict about versions of contrib, and specify drupal/core as ~8.0 and minimum stability stable. Though, that is not bulletproof. In the last update from 8.4 to 8.5, I had to patch over a contrib module due to a change introduced in core. That contrib module still has not updated to comply with the change. If I had this sort of workflow, core would have updated and broke the site. That isn't so much the fault of core, but the contrib module(s) not keeping pace with the changelog or the sometimes unfortunate BC breaks.

While auto update sounds like a good idea, its usually not worth the mentioned risk. I prefer to clone locally and run through the application to see if anything has changed, moved, or flat out broke instead of have it hit production immediately. I think most would agree.

With this latest PSA, everyone was given a weeks notice that it was coming so people could prepare and plan their release window around it. So there should have been plenty of time to stay informed, and most hosting companies (i.e.: ones who promote Drupal) should have notified their customers.

Wednesday is when the Security Team makes public any security issue on covered third-party modules.


How to do a db api join on "has no value"?

If I am reading this right, I think you need to use a left join and then test the nullness.

$the_query = db_select('foo', 'f');
  ->fields('f', array('nid', 'val'))

$the_query->leftJoin('bar', 'b', 'f.nid = b.col');

$results = $the_query->isNull('b.col');
  ->execute()
  ->fetchAll();

Very often, though, I will break down and do this with two queries.  The first will get a list of nids, the second will use a NOT IN condition.


How to redirect to original page after node create

I figured it out.  Just add the '?destination=the/url/you/want/to/redirect/to' to the /node/add/your-content-type' link.


Here's the trick that Kickstart uses (from commerce_kickstart.install).
The actual styling is in the Shiny admin theme.

/**
 * Implements hook_install_tasks_alter().
 */
function commerce_kickstart_install_tasks_alter(&$tasks, $install_state) {
  _commerce_kickstart_set_theme('shiny');
}

/**
 * Force-set a theme at any point during the execution of the request.
 *
 * Drupal doesn't give us the option to set the theme during the installation
 * process and forces enable the maintenance theme too early in the request
 * for us to modify it in a clean way.
 */
function _commerce_kickstart_set_theme($target_theme) {
  if ($GLOBALS['theme'] != $target_theme) {
    unset($GLOBALS['theme']);

    drupal_static_reset();
    $GLOBALS['conf']['maintenance_theme'] = $target_theme;
    _drupal_maintenance_theme();
  }
}


Clean way of building simple taxonomy browser of arbitrary depth

I figured out a way to do this with only the Views module. It's not perfect — it doesn't generate a nice URL and breadcrumb with the taxonomy lineage the way that my solution for a taxonomy of a single depth would do.

Static Depth Browser

For a taxonomy of static depth (where all terms have the same depth of child terms), you would do the following:

Create a view of nodes
Add relationship to taxonomy term (Term)
Add relationship to taxonomy term parent, accessible via Term (Parent)
Add relationship to taxonomy term parent, accessible via Parent (Parent Parent)
Repeat step 4 as many times as necessary for your taxonomy's depth.
Add contextual filters for each one and make sure they're in the proper order. Set to display a summary when filter is not in URL.
You'll probably want to override the breadcrumb and title for each filter.
???
PROFIT

Variable Depth Browser

For a taxonomy of variable depth (where some term trees have deeper levels of nesting than others), it's a bit more complex:

Add a new top-level term (Foo) to your vocabulary and put all other terms under it.
Create a view of terms with a page that displays term names
Add contextual filter: Taxonomy term: Parent term
When the default value is not in the URL, provide default value
Set default value to your top-level term name (Foo)
Specify validation criteria

Validator: taxonomy term
Criteria: your vocabulary name
Filter value type: Term name converted to term ID

Click the "+Add" button at the top of the Views panel to add an Attachment to the view.
Add to this attachment only (override) Relationship: Taxonomy term: Content with term
Add to this attachment only (override) display: fields: node titles linked to nodes, and remove (from this attachment only!) display: fields: term name
Add to this attachment only (override) contextual filter: Taxonomy term: Name
When filter value is not available, provide default value: Raw value from URL: Path component: 2 (or more if your Page path has >1 component)
Attachment settings: Attach to: [name of the page display you just made]
???
PROFIT

Screenshots of Views' UI for reference:


How do I add an external link in a module?

There seems to be very little information on this matter, maybe it's not that common to try to achieve something like this, but I stumbled across this thread while searching for a solution and I'd like to add my thoughts.
The comments stating that links.task.yml is for local tasks is right, but when it comes to external links, it's not that simple. As far as I know, you need routing to add links that way, and routing is for internal links, right?
So in the end I did it this way in Drupal 9:
  function my_module_menu_local_tasks_alter(&$data, $route_name) {
    $data['tabs'][0]['node.extra_tab'] = array(
      '#theme' => 'menu_local_task',
      '#link' => array(
        'title' => t('Extra tab'),
        'url' => Url::fromUri('https://theurl.com', array('attributes' => array('target' => '_blank'))),
        'localized_options' => array(
          'attributes' => array(
            'title' => t('Extra tab'),
          ),
        ),
      ),
    );
  }

You can also add something like if ($route_name == 'entity.node.canonical') to narrow it down and also if (\Drupal::routeMatch()->getParameter('node') == 'my_content_type') in case you want this to work only on certain content type(s).


Okay, I solved it by using by using an unformatted list instead of a table.

Here is my code in the end:

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

<?php print $title; ?>

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>

<?php
  $numRows = 6; /* Which row do you want the view to appear? E.g. 6 means that rows 6, 12, 18, etc. will have the view */
  if ((($id - ($numRows - 2) ) % ($numRows - 1)) == 0 && $id !== 0):
?>

<?php print views_embed_view('VIEW_MACHINE_NAME', 'DISPLAY_ID',''); ?>

  <?php endif; ?>
<?php endforeach; ?>


Cannot change an existing field's type. in field_update_field() line 240 of field.crud.inc

This is my solution to this problem, i'm going to also document how I found the solution.

If you see the message that something went wrong stop and look at the logs that Drupal reports back to you and take the time to read them.

In this example I was getting this error due to a specific module and when Drupal was faulting out the module basic_cart_order was the last one to be rebuilding based on the logs.

Now that I knew what module was faulting out it was time to find out why. I found the fields that where causing the message field_address and I looked within in that module for that value.

grep -R "field_address"

That brought me over to this file

sites/all/modules/basic_cart/basic_cart_order/basic_cart_order.features.field_base.inc

I opened up that file and made a couple of changes to all the fields that where causing a conflict to the database. You can find all the fields that cause the error in your log message. I added a prefix to all the fields with basic_cart_order.

This fixed the problem down to the line that was throwing the error.


Create a page view called search (Add the fields to display)
Add a path "/search"
Add the contextual filter "Global: null"
Add a filter "Search: search terms", expose the filter.
Expose the form in a block to use the search form elsewhere on your site.


I am looking to export webform submissions to cck instead of typing each submission in Drupal 6?

You could try:
First export the data to csv.

Then, import with feeds.


How can I redirect users upon password reset?

You can define submit function in your password form_alter and then $form_state['redirect'] = 'user'; or 'user/register'


Yes you can easily do it in addition to this code. You need to create another url to delete a record from the database

$items['deldata'] = array(
'title' => 'Delete data',
'page callback' => 'form_delete_form',
'page arguments' =>array(1),
'access callback' => TRUE,
);

function form_delete_form($arg){
$query = db_query("delete * from the 'table_name' where 'id' =$arg");
drupal_set_message("Record deleted successfully.");
drupal_goto('formdata');

}

function form_data_form()
{
  global $base_url;
 $results = db_query('SELECT * FROM {drupal}');
 $header = array(t('Id'),t('Name'),t('College'),t('Education'),t('Percentage'),t('Application'), t('Options'));
$rows = array();
foreach($results as $result){
$rows[] = array(
$result->id,
 $result->name,
 $result->college,
 $result->education,
$result->percentage,
 $result->application,
'id.'>Delete',
);
}
return theme('table',array('header'=>$header,'rows'=>$rows));
}

Hope it works for you!


Getting drush to install missing dependencies automatically into libraries

It's the module that handles "libraries" dependencies - not Drush. AFAIK you can't force Drush to ignore hook_requirements implemented by the module in (the install file). Some modules, for example Colorbox, provides a Drush command to download the missing libraries dependencies, but it's not automated.


The syntax would be along the lines of:

$adate =  date('Y-m-d');
$tvisit = db_result(db_query("SELECT counter_id FROM {counter_today} WHERE counter_date LIKE '%s%%' ORDER BY counter_id DESC LIMIT 1", $adate));

The changes from your original:

Put {}'s around table name so if you are on a shared database, drupal can put a prefix on automagically.
Put LIKE's % in the sql itself, not in the variable.  You need to put in %% since % itself is drupal's way of starting a variable (kinda like \\ to put in a \)
Put %s in in front of that for the variable, which is a string.  Remove the {}'s since they are for table names.  Granted, php will find $adate in there since it's all wrapped in ""'s but then you open up yourself to sql injection etc (however remote it would be in this specific example).
Put the $adate variable in the function call as an argument.
Take out the ``'s surrounding the field/column names.


Site is redirecting to old domain on button submission, files are linking to old domain

Yes, you have to edit it to dev.example.com. In the Drupal code, the modules use a function who returns the base URL. So if this URL is the old site... it resolves to the old site.

It's also used to protect your website against XSS.


Have you tried creating a relationship?

Sounds like that might give you the data you need, but you'll need to test it out.


Thanks for the advice. The solution:

For example, to get a three-hourly five-day forecast for Dunkeswell Aerodrome:

  $base = 'http://datapoint.metoffice.gov.uk/public/data/';
  $resource = 'val/wxfcs/all/json/3840?res=3hourly';
  $api_key = '&key=abcde12345abcde12345';
  $url = $base . $resource . $api_key;
  $response = drupal_http_request($url);
  $data = json_decode($response->data, TRUE);


/**
 * Implements hook_form_FORM_ID_alter() for login.
 */
function MYTHEME_form_user_login_form_alter(&$form, &$form_state) {
  $form['register_user']['#prefix'] = "
 " . t("Don't have an account?") . "";
  $form['register_user']['#suffix'] = "
";
}

This is how I've added a wrapper to a form element using prefix and suffix. Hope it helps.


Views list with picture as left, title and content as right

If you are just trying to create a layout for a node, not a view, then take a look at Display Suite. You can choose a simple layout in the settings e.g Header with left and right columns, then drag and drop which node fields you want into those areas.

There are lots of good help videos too.


Custom Profile Type and UPS Shipping Service

Commerce UPS calls commerce_physical_order_shipping_field_name($order) to determine what field holds the shipping profile for a given order. That means you can then use Commerce Physical's hook_commerce_physical_order_shipping_field_name_alter() to specify a per-order shipping profile field.


$page['main_menu'] is not menu. It's the region with name main_menu. You can put there any block what you want. You can configure blocks on this page admin/structure/block

But in the basic drupal themes the main menu can be available in this variable $main_menu in the template page.tpl.php


How to display all records by default on a view with exposed filters

When editing the filter, you can choose to require it if it's a select type of filter, you can also provide a default filtering that's used (before the user inputs). My guess is that you need to tweak these settings. to make sure that the default view filter settings display all or a selection of your choosing.


How to echo block title render in specific  D7

To add classes to block you can use below module:

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

To add class to block title there is similar question before:

Adding classes to block title

Thanks!


Just use some JavaScript to hide the div, similar to the following code:

jQuery(document).ready(function() {
  $('.view-filters').click(function() {
    $(this).next().toggle('slow');
    return false;
  }).next().hide();
});


How to acess node object in hook_form_alter

Not all the forms contains a reference to a node. It is just some node forms which contain a node object, but hook_form_alter() is called for every form being output from Drupal.

What you need to do is the following:

Check $form['#node'] is set

if (isset($form['#node'])) {
  // …
}

Use a different hook, such as hook_form_node_form_alter() if you want to alter the node edit form for any content type, or hook_form_$type_node_form_alter() for the node edit form of the $type content type


Programmatically get menu block & alter classes

borrowed from here:

add the following code in your template.php file.

<?php
  function THEME_menu_tree__main_menu($variables) {
    return '
' . $variables['tree'] . '
';
  }
?>

this would update the
 for main menu, adjust as necessary. You can adjust further up the chain within the page.tpl.php file.


You can use Splashify module for this

  Display a splash page anywhere on your site by redirecting the user, showing a lightbox, or displaying a popup. This module is designed to be search engine friendly, mobile device friendly and offers multiple configuration options.

Otherwise you can try with lightbox and custom scripts an example is given here


How to increase default Drupal minimum cache lifetime options to a custom value?

Just set the variable 'page_cache_maximum_age' using variable_set in custom module to the value 31536000

variable_set('page_cache_maximum_age', 31536000);

If you install the Devel Module there is a page for viewing and editing variables.

Above is a quick fix. If you want to do a perfect way then you need to form alter the "system_performance" form and change the option of below field.

  $period = drupal_map_assoc(array(0, 60, 180, 300, 600, 900, 1800, 2700, 3600, 10800, 21600, 32400, 43200, 86400), 'format_interval');
  $period[0] = '<' . t('none') . '>';
  $form['caching']['cache_lifetime'] = array(
    '#type' => 'select',
    '#title' => t('Minimum cache lifetime'),
    '#default_value' => variable_get('cache_lifetime', 0),
    '#options' => $period,
    '#description' => t('Cached pages will not be re-created until at least this much time has elapsed.')
  );
  $form['caching']['page_cache_maximum_age'] = array(
    '#type' => 'select',
    '#title' => t('Expiration of cached pages'),
    '#default_value' => variable_get('page_cache_maximum_age', 0),
    '#options' => $period,
    '#description' => t('The maximum time an external cache can use an old version of a page.')
  );


How to make node edit form meta panel accordions default to closed?

There are different approaches to change this behaviour. For instance, you could choose between these two at least:

CSS + JS: using a selector like .layout-region-node-secondary (depending on Theme), you could loop using a jQuery $.each() over the different 'details' and, if you find the 'open' property, remove it.

PHP: Using Hook Event Dispatcher, you could attach to the node alter event and upon firing, you could just alter the form accessing the $form / $form_state variables and removing the CSS from the items you'd like to.


Actually, the drupal.org link above will work. At the bottom of the page there is a section that discusses bringing configuration files into the install directory. You can use Drupal Console (DC) to create the configuration files like this:

drupal config:export

It will put all the configurations in the public folder unless you specifiy a directory.

https://hechoendrupal.gitbooks.io/drupal-console/content/en/commands/config-export.html

https://www.drupal.org/docs/8/creating-distributions/how-to-write-a-drupal-8-installation-profile

EDIT

Also, I've added a Drupal.org page has a lot of resources for creating a distribution. On the sidebar it lists common make errors and other useful links.

If you check the release download page of your distribution, you can find the Drupal packager error messages if you send a distribution for packaging.

A lot of this needs to be learned by trial and error. I've spent a fair amount of time on this and still haven't gotten the hang of things.

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

EDIT

Also, there appears to be something called drupalorg_drush. It's a drush extension that helps build a replica of what drupal.org would do with your distribution files should you upload them to your project's Git repository. However, at the time of this writing, Drupal 8 version is not available.


Parsing value of a field from content to a webform field

Try using the webform node value module

  Fill a Webform field with the value of a node field.


How to manage version control for patched contrib modules?

Use Drush Make. It's built into Drush 5. Your makefile will serve as not only documentation of what patches you're using, but documentation of what versions of everything you're using, where to download external libraries, it's practically guaranteed to be up to date, and it means you no longer have to store contrib and external code in your source code repository. Just your custom code.

Basically, you create a file that tells Drush Make what version of core to download, which contrib modules and themes to download, which external libraries to download, where to place them (you can separate contrib modules to a "contrib" subdirectory, for instance), which patches to apply (to all of those).

Drush Makefiles are used to build Drupal distributions.

Have a look at a pretty simple makefile from Discursive, and a more terse makefile from OpenOutreach.

EDIT: I really should include a link to at least one makefile that uses a bunch of patches and a much better example of using Drush Make on a client project: WiseDecider (check the makefiles in that install profile directory, then also go up a directory to find the rebuild.sh script that "builds" it -- downloads, patches, etc. the site and sets up symlinks and such to glue everything together. Also a disclosure: Wise Decider is a client of the Drupal shop I work for and Discursive is the open-source version of another client project of ours.

EDIT 2: Don't use any kind of "automatic updates" with this method. The process is:

Update your makefile locally
Rebuild the site by rerunning the build script
Test on your local instance of the site against a new dump of the production database (don't forget drush updb)
Deploy the updated codebase to your testing/staging server (don't forget drush updb) for internal QA / client QA (if applicable)
Redeploy the updated codebase to production (and again, don't forget to run the db update scripts).

Our deployment scripts (included in Wise Decider) use rsync and symlinks to pushing code to the remote LAMP server.


How to use Drupal for managing a public website together with an intranet and an MSSQL database?

Drupal can most of this very well.

Someone with more experience can address how it can be set up for Intranet and Internet. It can handle multiple sites linked with data from same database (Not sure if this is what you want).

User permissions can be defined effectively down to the smallest content level so restricting access based upon any user categories you choose is not a problem.

Drupal works from a database (MySQL), apache, and php.  Transferring data will not be a problem for an experienced DB manager.

Images are stored as separate files on the site with references in the DB.  Images can be handled in a variety of ways on any page display including direct insertion.

Page layouts can be handled either through layout themes that handle HTML and CSS management and are fully customizable.

Drupal is exceptionally flexible and can do just about anything you can imagine.  There are hundreds of modules to choose from (all free and open source).

Having said all that, doing sophisticated site features is not for beginners and there is a steep learning curve for new site developers.  Getting a sophisticated site up and running requires an experienced Drupal developer.  Some of them are on this site and you can find others at Drupal.org.


How to use Rules to limit the number of searches to pull data from a remote API?

Preface
You added an interesting comment below your question, part of it is like so:

All users is registered via Keycloak and page will redirect to Drupal site after its successful registration. This redirected page is the custom view plugin created. For users to be able to add its company details. And so users will enter their VAT # to get data from the CVR Register. ...

Followed by this extra comment:

query/query?vat=12345678. First 'query' is the sitename, then 2nd is the menu path name

So you have a relative path like in this example /query?vat=12345678. And therefor the answer to your question (= Can this be achieve by Rules?) is Yes, Si, Oui, Ja ... Read on for more details to guide you ...
Solution
You may want to try the "Rules URL argument" module. Here is a quote about it (from its project page):

... provides two rules conditions based on URL arguments:

check if a URL argument is present.
compare the value of an URL argument.

It also provides an action that makes the value of an URL argument available as new variable to Rules.

The newly provided Rules actions and conditions can be found under the "URL Argument" conditions and actions groups in the rule configuration interface.
For an example of how to use it, refer to Comment # 3 in issue # 1686360 which is about "Pass an amount to the url, ie; site/content/node-title?amount=10 or /node-title?=amount:10". Here is the relevant part of it:

add a "Check if URL argument exist" condition to your rule and set the "ARGUMENT" value to "amount".
add "Provide URL argument value" action to the rule and set "URL ARGUMENT NAME" value to "amount" and in the "Provided variables" section "ARGUMENT FROM URL - Variable name" to e.g. "amount_from_url".

You will now be able to use the amount value as a variable "amount-from-url" for other actions in this rule.

So with that you can use Rules to (let's say) "monitor" the usage of that path by an authenticated user. Some more details about the custom rule you could create for this:

Rules Event: drupal is initializing (sorry, that's probably the only one that you would be able to use).

Rules Conditions (pick whatever fits, and/or mix however you want):

user has a specific role (or the negation of it).
check the current path (verify if it starts with query).
check if URL argument vat= is present.

The only thing left to do is to think of something appropriate for some Rules Action(s) to be performed, knowing that you do have these crucial data available:

the current user who tries to use this path again.
the actual value (=12345678) that was used.

Obviously, at a minimum you'd want to add a Rules Action to perform an appropriate "redirect" if the 3 attempts have been used on the same day already.
You'd have to do some more homework/refinements, but here is a blueprint of a basic solution that could work:

Solution 1 (easiest approach to implement):

Use the Flag module (eg with 3 none-global flags labeled like attempt 1, attempt 2 and attempt 3).
Add a Rules Action to flag the user with the relevant flag (corresponding to the number of succeeded attempts before).
Add an extra Rules Condition to verify that not all flags have been used (with the same flagging date!).

Solution 2 (= my recommended approach, though a bit tougher to implement): Use the Message module to create a custom activity log, to log each event where the actual URL has been used (with success). And improve the Rule above to add a rules condition to count the number of such messages (= custom activity log records) created already in the last 24 hours.

PS: I'm assuming this is about D7 ...


Another question on Drupal files folder permissions and security

Why have 755 on sites/default/files directory (and sub-directories) instead of 744? Isn't the files folder by definition for user files and system caching files? To flip the question around, is there any legitimate reason to allow "x" for the group/other users?

Without the "x" being set for a directory, the group/user will not be able to look inside the directory.  So you usually want the "x" bit set for group/users for the directory in order to be able to examine these in the CLI without being root.

  Is the new default .htaccess file (shown below for reference) that gets written to sites/default/files "secure enough" that even if a user hacks the front end or database, they can't really cause much havoc?

IMHO, the Drupal .htaccess is adequate for preventing executables downloaded to the upload from being executed.

However, having this file in place does not protect you from front-end or database exploits. And attackers gaining access to execute PHP from the database can remove or replace it.

So you also want to prevent PHP injected into the datebase from being executed. You do this by removing the core PHP module. Do this:

rm -rf modules/php/

You should never enable this misfeature (it has been removed from core in D8), but by physically removing out, you eliminate the risk of somebody making a succesful SQL injection exploit also being able to execute PHP.

Provided you don't use it (and you shouldn't), and it is already disabled, removing it has no side-effects.


How to print the raw value of a custom user field in comments

You can use the field_get_items() to get all values for this field, after use field_view_value().
Example below:

// user_uid_optional_load() will load the user object with all custom fields

$account = user_uid_optional_load($comment->uid);

$items = field_get_items('user', $account, 'field_name');

// as a example I'm using the number 0 as delta
$value = render(field_view_value('user', $account, 'field_name', $items[0]));


How to use the value element to pass values internally from $form to $form_state['value']

The problem is that you'll need to set the type of the correct element to value, and that isn't what you've got at the moment. Notice how you use:

$form['field_devis_lien_fiche']['und'][0]['value']["#default_value"]

To access the field the first time round (which you've confirmed to be working). Logically then, if you want to change the same field to a value type, you need to do so on the same element:

$form['field_devis_lien_fiche']['und'][0]['value'] = array(
  "#type" => 'value',
  "#value" => $path,
);


How to display the user's url in a template?

You can use the path function in a Twig template:

{{ 'View user profile'|t }}

I don't know if user.url is a thing.


Access denied on hello world custom module

The issue is with the indentation of the hello_world.routing.yml file. Simply change the indentation of it to:

hello_world_settings:
  path: '/hello/world'
  defaults:
    _controller: '\Drupal\hello_world\Controller\HelloWorldController::myCallbackMethod'
    _title: 'Hello World'
  requirements:
    _permission: 'access content'

And the Access denied issue should be solved. The indentation of YAML file is  important, in Drupal 8. It should be as follow:

path, defaults, and requirements should be indented by 2 spaces
_controller, _title, and _permission should be indented by 4 spaces


How to pull active user name from drupal 6

Drupal 6 supports multiple DBMS connections easily in settings.php (to the same type of DBMS, eg 2 Mysql DBs, not 1 MySQL and 1 SQLServer).

You can use a function like hook_user to track who has logged in and feed that username into your 2nd database using the database api and for instance the db_query function. You also likely need db_set_active.

EDIT

I'm not sure exactly what your trying todo. You can always use php's ldap functions to talk to ldap and look for info on the "user" (if they're not logged in yet I have no clue what you'd grad from ldap ...). You could always use hook_form_alter to assign additional submit handlers on any default drupal form to perform custom tasks.

Having used ldap_integration for D6. You should realllly think about moving the site to D7 as the new ldap module is pretty nice and lets you save off ldap queries as re-runnable things :).


ajax button doesnt fire callback function

try adding '#submit':

$operations['delete'] = array(
  '#type' => 'submit',
  '#value' => t('Delete'),
  '#ajax' => array(
    'wrapper' => 'wizard-form-wrapper',
    'callback' => 'application_wizard_callback'
  ),
  '#submit' => array('application_wizard_submit'),
);


Under what circumstances should a site be placed into maintenance mode

In my experience working on some very high profile D7 installations, maintenance mode is always required during updates. The steps you took to perform your update are essentially the same as I've experienced. The reason for using maintenance mode is to essentially lock out users from making database changes that might corrupt the DB when update.php(drush updb) is run. I can't think of any good reason why you would do a production update without maintenance mode, unless you like playing Russian Roulette with a production DB. I also hope you're doing the updates during non-business hours or during a scheduled maintenance time.


Show if there are 'new' comments on a view of terms?

This works for me. I have a term view that shows the term name field and my code adds the new comment flag after the term name.

The code goes in a custom module.

You need to change to VIEW_NAME to your view name and the TAXONOMY_FIELD_NAME to the name of your field (like field_tags for example).

/**
 * Implements hook_views_pre_render().
 */
function MYMODULE_views_pre_render(&$view) {
  global $user;
  if ($view->name == 'VIEW_NAME' && $user->uid) {
    // Get all the tids of the views results.
    $tids = array();
    foreach ($view->result as $result) {
      $tids[] = $result->tid;
    }

    // Get all the tids that have recent comments.
    // Only return terms that relate to nodes that have not been viewed by
    // the current user since the last comment.
    $query = db_query("SELECT t.TAXONOMY_FIELD_NAME_tid
                         FROM {node_comment_statistics} c
              LEFT OUTER JOIN {history} h ON c.nid = h.nid AND h.uid = :uid
                   INNER JOIN {field_data_TAXONOMY_FIELD_NAME} t ON t.entity_id = c.nid
                        WHERE c.comment_count > 0
                          AND t.TAXONOMY_FIELD_NAME_tid IN (:tids)
                          AND (h.timestamp IS NULL OR h.timestamp < c.last_comment_timestamp)",
               array(':uid' => $user->uid, ':tids' => $tids));
    $commented_terms = $query->fetchCol();

    // Loop through the results and add the new comments flag where necessary.
    foreach ($view->result as &$result) {
      if (in_array($result->tid, $commented_terms)) {
        $result->taxonomy_term_data_name .= ' new comments!';
      }
    }
  }
}


EntityQuery how to get all delta and good for field_dates

As far as I can see you could already help your self by making your conditions more simple:

  just want to make a request to render all node when time() is between field_date_value AND field_date_end_value OR time() is < to field_date_value

So actually your final condition (which is equivalent with what you wrote is)
time() < field_date_end_value

Also I advice you to use the request time (from Time service) instead of time: in most of the case is that's what should be used.


How to correctly specify image links in a content type?

First set $base_url in your settings.php file in sites/default/ directory.
I am sure you are using ckeditor or some other editor. In editor setting use use relative URL for images and links.
Make sure your Apache mod_rewrite or rewrite_module is enabled.


What is the difference between path and theme path in theme registry?

From the hook_theme() docs:

path: Override the path of the file to be used. Ordinarily the module or theme path will be used, but if the file will not be in the default path, include it here. This path should be relative to the Drupal root directory.
theme path: (automatically derived) The directory path of the theme or module, so that it doesn't need to be looked up.


Alter Multiple Field Values by Testing "Field Type"

You can use FieldConfigInterface to get fields info.
Try the following:

use Drupal\Core\Field\FieldConfigInterface;

function MYMODULE_node_presave($node) {
  //- Call helper function to get all the fields
  $fieldsArray = getContentTypeFields($node->bundle());
  //- Loop through fields
  foreach ($fieldsArray as $fieldName => $fieldConfig) {
    ///- Example to check if type is text_with_summary
    if ($fieldConfig->getType() == 'text_with_summary') {
      /**
       * @TODO : Something here for field of type text_with_summary
       */
    }
  }
}

/**
 * Helper function to Get all fields of content type:
 *
 * @param $contentType
 *
 * @return array
 */
function getContentTypeFields($contentType) {
  $entityManager = Drupal::service('entity.manager');
  $fields = [];
  if (!empty($contentType)) {
    $fields = array_filter(
      $entityManager->getFieldDefinitions('node', $contentType), function ($field_definition) {
      return $field_definition instanceof FieldConfigInterface;
    }
    );
  }

  return $fields;
}


How to add custom theme to module block on Drupal 7?

Was too long for a comment...

If all you want is the last 5 posts of the current user - create a view:

choose content type
Create a limit under Pager (presumably of 5)
advanced - relationship author
filter by currently logged in user
sort by post date descending

This will create a view (be it a page or block) that shows the last 5 posts of whatever content you want for the currently logged in user. If you want to include it as a block, create as a block, and in the block configuration for that view (under structure/blocks), you can decide where on the page and for which pages you want the block to appear.

You can decide which content types are included via the filter, and decide the layout.


How to create variations in commerce file?

The set up should be:  a single product display whose product reference field has both the (I'm assuming) Windows file and Mac file.  The relevant product attribute being that taxonomy term.  So, in your product type, place that taxonomy term.  It sounds as if you put that taxonomy term on your product display, which is a node type.
Note:  products entities = variations in Kickstart 2.  Products I believe refer to product displays.


Views taxonomy terms page with two content types

Directly modifying the default "taxonomy/term/%" view is not a good option, you can clone the default view and can make the required changes to the cloned view.

The better solution for the above problem is the Taxonomy Display module. Taxonomy display lets you associate a vocabulary with a particular view. Now, when I click on particular term link, which is an alias for taxonomy/term/%, the view takes over and this is actually rendered correctly maintaining the integrity of the field structure.

The detailed documentation of taxonomy display module is available here.


How to implement POST request in custom services module?

In order to change into the POST request. You just change the source of resource from path to data. For example:

function module_rest_services_resources() {
  return array(
  'new_note' => array(
     'actions' => array(
       'retrieve' => array(
         'help' => 'Retrieves a note',
         'file' => array('file' => 'inc', 'module' => 'module_rest'),
         'callback' => '_module_rest_retrieve',
         'access callback' => '_module_rest_access',
         'access arguments' => array('view'),
         'access arguments append' => TRUE,
         'args' => array(
           array(
             'name' => 'id',
             'type' => 'int',
             'description' => 'The id of the note to get',
             'source' => array('data' => 'id'),
             'optional' => FALSE,
            ),
          ),
        ),
      ),
    ),
  );
}


How to move the content of 'Node content' display (Views) to the end of a view?

Have you tried playing with the "Row style" setting ? You could change it to "Fields" and select the node:title, node:body, node:nid and node:answers (?? does that exist ?? I'm guessing that answers are just comments, right ? In that case, node:comments).

Output them in the order that you want, but rewrite the node:nid as a link to the "post answer" url. I don't know this module, but say the answer url is node/xxx/answer, you can rewrite the node:nid field as

Post your answer


The answer comes from here: https://www.drupal.org/node/2187643.

Note: change "module" in the below code to the name of your module.

The first step is to register an event subscriber service. In module.services.yml:

services:
  module.route_subscriber:
    class: Drupal\module\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

Next, create your class RouteSubscriber and extend RouteSubscriberBase:

  namespace Drupal\module\Routing;

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

  /**
   * Subscribe to the Route to change page titles.
   */
  class RouteSubscriber extends RouteSubscriberBase {

    private function alterRoutes(RouteCollection $collection) {
      if ($route = $collection->get('entity.project_entity.add_form')) {
        // set the title (or override '_title_callback' below)
        $route->setDefault('_title', 'Create Project Request');
        // unset the _title_callback; alternatively you could override it here
        $route->setDefault('_title_callback', '');
      }
    }
  }

Note that you receive a RouteCollection in alterRoutes and then using the $collection-get() will return an instance of Route.  The documentation for Route can be found here: http://api.symfony.com/2.7/Symfony/Component/Routing/Route.html

If you're having trouble figuring out what your routes are, the excellent drupal console drupal route:debug tool will help you.


Classification: {{ content.field_classification.value }} not displaying

{{ content }} is a render array and does not have a .value, just use {{ content.field_name }}

You only need the .value when you want to print the raw values of an entity object like node, e.g. {{ node.field_my_integer.value }}


Try this:

Create a new taxonomy vocabulary called 'Media Type' with terms 'Image' and 'Video.'
Add a taxonomy field to your Media content type.
Add a taxonomy field to your view (hidden/exposed/however you'd like)

You'll then be able to filter by the value of the taxonomy field.


How do I troubleshoot specific Products missing from Commerce Search?

Not sure if this is proper 'etiquette' but here is the solution for -this- problem:

My Product Display has an Entity field which displays a list of 'related products' -- a common enough situation in a Shopping Cart system. The related products are a View which displays products linked to the parent product NID.

Like most sites, I imagine, the Index excludes unpublished products.

Apparently if any one of the Related Products is unPublished, this affects the Commerce and/or SOLR Search index for the -Parent- product. IOW: if any child product is unPublished the index skips the -parent- product as being 'unpublished'.

Not sure which module is at the root of this... or who to notify... but if the Commerce Guys monitor, this is a real 'gotcha'. I've run into this many times in Drupal where SQL Queries are not 'isolated' from one another... ie. a child view will affect a parent query.


How to initiate node_save() on module install?

If it's your own module, use hook_install():

Perform setup tasks when the module is installed.

or hook_enable():

Perform necessary actions after module is enabled.

If it's not your own module, use hook_modules_enabled():

Perform necessary actions after modules are enabled.
This function differs from hook_enable() in that it gives all other modules a chance to perform actions when modules are enabled, whereas hook_enable() is only called on the module actually being enabled. See module_enable() for a detailed description of the order in which install and enable hooks are invoked.


Views Taxonomy Term Argument With Multiple Terms

I think I have sort of worked out a solution. It displays correctly in the Views preview but not on the node itself. Maybe this will help though.

View settings:

Create a Block. Configure Block to display on content of type Post. Configure settings of View:

Fields

Content: Title

Filter criteria

Content: Published (Yes)
Content: Type (= Links)

Contextual filters

(field_tags) Content: Title

Using relationship: Term

Relationships

Content: Taxonomy terms on node (term)
Taxonomy term: Content using Tags

Using relationship: term

In my preview, when I enter the title of a Post as the contextual filter, I get a list of all the links tagged with the same tags as the Post. For some reason, when I view the actual Post it doesn't work but that might just be a caching issue or something on my end?


Have to hook into a function from a module

Just making a quickly research (I don't have time at this moment to test the code) inside the Linkedin Integration module I can tell you that I found a hook named linkedin_external_login

See the code in the linkedin_auth/linkedin_auth.module file in the line 124

/*
 * Implementation of hook_linkedin_external_login
 */

function linkedin_auth_linkedin_external_login($uid) {
  $name = db_query("SELECT authname FROM {authmap} WHERE uid = :uid AND module = :module", array(':uid' => $uid, ':module' => 'linkedin'))->fetchField();
  user_external_login_register($name, 'linkedin');
  drupal_goto();
}

Just implement your own hook_linkedin_external_login()


What would be best method to append bootrap css to non bootstrap themes but not affect layout?

You can customize your bootstrap package for download here:

  Customize Bootstrap's components, Less variables, and jQuery plugins to get your very own version.

http://getbootstrap.com/customize/

After that, you can add just the required CSS/JS to your theme as per the usual methods


Check that the following rule is not commented out in your .htaccess file:

RewriteBase /

If you have installed Drupal in a folder inside your root it should be:

RewriteBase /my_folder


SQL error after using Feeds Import with Taxonomies

Finally, I have discovered the problem. I deleted the taxonomy data with the module Taxonomy Manager. When importing the data with Feeds again, it believes that the data remains there, even if they longer no exists. From here, some failed imports can make database corrupted.

To regain integrity, I looked for the problem tid, and checked that it appears in field_data_* with entity_type = 'taxonomy_term' and field_revision_* with the same entity_type. I also appears in url_alias, and didn't find any more instance of tid's with the problems in any more tables. I truncated all these tables.

I also checked that both modules, when deleting taxonomy terms, if the tables are empty, they don't make an additional TRUNCATE, so the new tid's don't start at tid = 1.


Drupal 7: Filter nodes with a date range arround an exposed date

Have you tried adding an exposed filter in your view?  I'm assuming you're using a view already, and I'm assuming you're using Drupal 7 (it's always helpful to specify that in the question, by the way :-)).

Add the date in question to your list of filters, check the box to expose it to users and use the 'is not between' option.  Then you can either specify a hard coded date for the 'from' and 'to' or you can even use a relative date (second value type option) and specify something like '-30 minutes' and '+30 minutes' and it will re-calculate them based on the current time...

Hope this helps.  Let us know if it works.


Share same database tables with multisite instances

I understand your intention, but no. This is not the usual approach and has the potential to bring you all sorts of pains later on the line.

Once a project is deployed, you really need 2 databases. Say your live application needs a new feature, you would want to update your "dev" site with live server's data. So ...

You pull data from live server. Hint: drush sql-sync makes it as simple as drush sql-sync @live @dev.
You develop the feature ...
Push the code to production ... drush rsync @dev @live or whatever you use. (Git is also great for this btw)
Now we have to update the db changes and this is where it gets funky. If you have added or altered tables and data you cannot just sync the db because you will overwrite whatever data your users have posted since you pulled. The common way to handle this is having update hooks to insert the changes in your db. Following this approach, the update hook was deployed in step #3. All that is left to do is ..
Run live.com/update.php. This will trigger your update hooks and insert changes to db.

A few things to keep in mind that make this procedure dead easy:

Drush in conjunction with drush aliases and multiple settings.php for each environnment will make transferring code and  data back and forth a breeze.

Happy coding, cheers


How to publish unpublished nodes programmatically

Using db_query() is a Drupal 6 method, which is not used in Drupal 7.
To achieve your job I suggest this code (without any manual query).

// load the node object
$node = node_load($nid);
// set status property to 1
$node->status = 1;
// re-save the node
node_save($node);

If you have more node ID, and you want to publish all those nodes, you can use the following code.

$nids = array();
// Load all nodes in one go for better performance.
$nodes = node_load_multiple($nids);
foreach ($nodes as $node) {
  // set status property to 1
  $node->status = 1;
  // re-save the node
  node_save($node);
}


Custom block assigned to new region invalid

You can use this code:

function formalter_block_info() {

 $blocks = array();

 $blocks['buynow'] = array(

 'info' => t('Shoretel Buynow'),

 'status' => 1, // This will enable your block by default, and set it to region given in 'region' option

 'region' => 'buynow', // put <machine-name of your region> in place of footer
 'visibility' => BLOCK_VISIBILITY_NOTLISTED,

 'weight' => 2,

 );
return $blocks;
}


How to add a link to slide elements in MD Slider?

I have created a patch with the changes to convert a slide into hyperlink. Since I cannot upload a file here, I am copy-pasting the contents of my .patch file:

From 3f72f263b3673ce27ca4114963b007752b566c2a Mon Sep 17 00:00:00 2001
From: Raj Pawan Gumdal <gumdal@gmail.com>
Date: Sat, 6 Aug 2016 11:02:04 +0530
Subject: [PATCH 1/2] Ported changes regarding MD_Slider done for an older
 version

---
 .../templates/front/front_layers_render.tpl.php    | 13 ++++----
 .../templates/front/front_slide_render.tpl.php     | 35 ++++++++++++++++++++--
 2 files changed, 41 insertions(+), 7 deletions(-)

diff --git a/sites/all/modules/md_slider/templates/front/front_layers_render.tpl.php b/sites/all/modules/md_slider/templates/front/front_layers_render.tpl.php
index a8dd7fc..16c30b4 100644
--- a/sites/all/modules/md_slider/templates/front/front_layers_render.tpl.php
+++ b/sites/all/modules/md_slider/templates/front/front_layers_render.tpl.php
@@ -11,11 +11,14 @@
 <?php endif;?>
   <div class="<?php print $class; ?>" <?php print $data; ?>>
     <?php if ($layer->type == 'text'): ?>
-        <?php if (isset($link)):?>
-            <a href="<?php print $link;?>"<?php if (isset($layer->link["target"]) && !empty($layer->link["target"])) print " target='{$layer->link["target"]}'";?>><?php print $layer->title;?>
-        <?php else:?>
-            <?php print $layer->title;?>
-        <?php endif; ?>
+    <?php /* Raj: Changes to make MD_Slider slide as hyperlink */?>
+       <?php if (strpos($layer->title,'URL:') === false):?>
+           <?php if (isset($link)):?>
+               <a href="<?php print $link;?>"<?php if (isset($layer->link["target"]) && !empty($layer->link["target"])) print " target='{$layer->link["target"]}'";?>><?php print $layer->title;?>
+           <?php else:?>
+               <?php print $layer->title;?>
+           <?php endif; ?>
+        <?php endif; ?>
     <?php elseif ($layer->type == 'image'): ?>
         <?php if (isset($link)):?>
             <a href="<?php print $link;?>"<?php if (isset($layer->link["target"]) && !empty($layer->link["target"])) print " target='{$layer->link["target"]}'";?>>
diff --git a/sites/all/modules/md_slider/templates/front/front_slide_render.tpl.php b/sites/all/modules/md_slider/templates/front/front_slide_render.tpl.php
index 8df2c39..5dd71dd 100644
--- a/sites/all/modules/md_slider/templates/front/front_slide_render.tpl.php
+++ b/sites/all/modules/md_slider/templates/front/front_slide_render.tpl.php
@@ -18,10 +18,41 @@
       <div class="md-slider-overlay" style="background: <?php print $slide->settings['background_overlay']; ?>">

     <?php endif; ?>
-

+
+    <?php
+    // Raj: Check if there is a string which starts from "URL:". If so, extract the URL and make this div a hyperlink
+    $hasURL = false;
+    $URLString = '';
+    foreach ($slide->layers as $index => $layer):
+    $layerTitle = $layer["title"];
+    drupal_set_message("Layer object: $layer");
+    drupal_set_message("Layer title: $layerTitle");
+    // http://stackoverflow.com/a/4366748/260665
+    if (strpos($layerTitle,'URL:') !== false) {
+       $hasURL = true;
+       $URLString = str_replace('URL:', '', $layerTitle);
+       break;
+    }
+    endforeach;
+
+    if ($hasURL)
+    {
+       print "";
+    }
+    print "
";
+    foreach ($slide->layers as $index => $layer):
+    print theme('front_layers_render', array('index' => $index, 'layer' => $layer));
+    endforeach;
+    print "
";
+    if ($hasURL)
+    {
+       print "";
+    }
+    ?>
+
       <?php foreach ($slide->layers as $index => $layer):?>
         <?php print theme('front_layers_render', array('index' => $index, 'layer' => $layer));?>
       <?php endforeach;?>
-

+

 <?php endif;?>
--
2.7.4 (Apple Git-66)

From 74c3d0644fd505729163d4803c9a0f9cb014e679 Mon Sep 17 00:00:00 2001
From: Raj Pawan Gumdal <gumdal@gmail.com>
Date: Sat, 6 Aug 2016 14:04:39 +0530
Subject: [PATCH 2/2] Finalized the changes to support hyperlinking whole slide

---
 .../templates/front/front_slide_render.tpl.php     | 30 +++++++++++++---------
 sites/all/themes/IndianSnakes/css/custom.css       |  6 +++++
 2 files changed, 24 insertions(+), 12 deletions(-)

diff --git a/sites/all/modules/md_slider/templates/front/front_slide_render.tpl.php b/sites/all/modules/md_slider/templates/front/front_slide_render.tpl.php
index 5dd71dd..764d46e 100644
--- a/sites/all/modules/md_slider/templates/front/front_slide_render.tpl.php
+++ b/sites/all/modules/md_slider/templates/front/front_slide_render.tpl.php
@@ -9,6 +9,7 @@

 <?php if (!isset($slide->settings["disabled"]) || !$slide->settings["disabled"]):?>
   <div class="md-slide-item slide-<?php print $index+1;?>" <?php print $data_properties;?>>
+
     <div class="md-mainimg" style="<?php print $background_style;?>">
       <?php if (!empty($background_url)):?>
         <img src="<?php print $background_url;?>" alt="<?php print htmlentities($slide->settings["background_image_alt"], ENT_QUOTES, 'UTF-8');?>"<?php print $background_style;?> />
@@ -25,34 +26,39 @@
     $URLString = '';
     foreach ($slide->layers as $index => $layer):
     $layerTitle = $layer["title"];
-    drupal_set_message("Layer object: $layer");
-    drupal_set_message("Layer title: $layerTitle");
+//     drupal_set_message("Layer object: $layer");
+//     drupal_set_message("Layer title: $layerTitle");
     // http://stackoverflow.com/a/4366748/260665
-    if (strpos($layerTitle,'URL:') !== false) {
+    if (strpos($layerTitle,'URL:') === false) {
+    }
+    else {
        $hasURL = true;
-       $URLString = str_replace('URL:', '', $layerTitle);
+       $URLString = str_replace('URL:','',$layerTitle);
        break;
     }
     endforeach;
-
+//     drupal_set_message("URL: $URLString");
+//     drupal_set_message("Has URL: $hasURL");
+    $outputString = "";
     if ($hasURL)
     {
-       print "";
+       $outputString .= "";
     }
-    print "
";
+    $outputString .= "
";
     foreach ($slide->layers as $index => $layer):
-    print theme('front_layers_render', array('index' => $index, 'layer' => $layer));
+    $outputString .= theme('front_layers_render', array('index' => $index, 'layer' => $layer));
     endforeach;
-    print "
";
+    $outputString .= "
";
     if ($hasURL)
     {
-       print "";
+       $outputString .= "";
     }
+    print $outputString;
     ?>
-
+
+
 -->

 <?php endif;?>
diff --git a/sites/all/themes/IndianSnakes/css/custom.css b/sites/all/themes/IndianSnakes/css/custom.css
index 3d69b0d..3f0354e 100644
--- a/sites/all/themes/IndianSnakes/css/custom.css
+++ b/sites/all/themes/IndianSnakes/css/custom.css
@@ -27,3 +27,9 @@ display: inline-block;
 width: auto !important;
 height: 300px !important;
 }
+
+/* Reset the hyperlink style to normal inside slides */
+.md-slide-item a {
+    color: inherit;
+    text-decoration: inherit;
+}
\ No newline at end of file
--
2.7.4 (Apple Git-66)

I have defined a new "URL:" label protocol for each slide. If a slide has this label defined then the whole slide's div is converted into hyperlink with whatever link is provided after my URL: protocol. For example check this:

The code (patch) is configured such that label with text which begins with URL: is never rendered as text but it is used to convert the slide into a hyperlink.

For a live working example check: http://indiansnakes.org/homepage

Assumption:
The only limitation of this method is, you should not hyperlink any text or images which are used within this hyperlinked slide coz the anchor tags cannot be nested, apparently.

Edit: I thought its best to update the patch details in the MD Slider community as well, here it is: http://megadrupal.com/comment/13066#comment-13066

Also a gist is created with the contents of same patch: https://gist.github.com/gumdal/e580cd80199c871fa52f677538771551


Remove CDATA script from the page source

I'm assuming you're using an HTML5 DOCTYPE, The CDATA tags are required for XML-based documents (including XHTML).

The characters look to be hard-coded into common.inc, line 4287:

$embed_prefix = "\n<!--//--><![CDATA[//><!--\n";
$embed_suffix = "\n//--><!]]>\n";

Examining that code I think the only way to intercept it would be to override theme_html_tag() in your theme, e.g.

function MYTHEME_html_tag($vars) {
  if ($vars['element']['#tag'] == 'script') {
    unset($vars['element']['#value_prefix'];
    unset($vars['element']['#value_suffix'];
  }

  return theme_html_tag($vars);
}


After restoring the database from the live site to development site, the administrator users fails to log in

When login fails, you shall get the following error message:

  Sorry, unrecognized username or password. Have you forgotten your password?

You say:

  There is no way to login, no error message; simply I am not logged in.

This suggest that the problem is not with the admin passord, but something else (i.e. your restored site is somehow munged).  In that case, you need to start restoring it from scratch.

Resetting the password will not help if the site is munged, but for the record:

There are several ways to reset the Drupal admin password.  Here they are, sorted from the simplest to use to most difficult:

Request a reset password link sent via e-mail (the most used method).
drush upwd admin --password=<new_password> (as already mentioned by develkar).
./scripts/password-hash.sh <new_password> (as you've found out yourself).

Usually, all of these works.  The shell-script method (#3) is very similar to the drush method (#2), but unlike drush, the shell-script method requires you to insert the generated password hash in the database yourself (using phpMyAdmin or similar tool).


How can I include a list of what a user ordered (the line items) in an e-mail sent by Drupal Commerce?

The [commerce-order:commerce_line_items] token does not work when Completing the checkout process, which is the event for which the Send an order notification e-mail rule is triggered.

Instead, one way to do this is to use the Commerce E-mail module, which provides a [commerce-order:commerce-email-order-items] token and a new interface for editing the e-mail.  Note that you will need to disable the e-mail-sending rule when using this module (or else you will get duplicate e-mails, as the module help points out).


Try Block Refresh module.

  Block Refresh allows an administrator to configure a block to refresh
  it's content in a given number of seconds. Block Refresh uses
  jQuery/AJAX so the refresh happens "behind-the-scenes".


How to get fields definitions of a vocabulary in drupal 8/9?

\Drupal::entityManager() is deprecated, instead you should use \Drupal::entityTypeManager. From the docs:

Deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0. Use \Drupal::entityTypeManager() instead in most cases. If the needed method is not on \Drupal\Core\Entity\EntityTypeManagerInterface, see the deprecated \Drupal\Core\Entity\EntityManager to find the correct interface or service.

This is especially relevant here as the getFieldDefinitions() method has moved to a different service, entity_field.manager.
With all of this said, you can use the same method to get taxonomy term fields as any other bundle. As documented in this related answer:
$entity_type_id = 'taxonomy_term';
$bundle = 'article_tags';

// Load the field definitions for any bundle.
$my_bundle_fields = \Drupal::service('entity_field.manager')
  ->getFieldDefinitions($entity_type_id, $bundle);


Building a View or Panel(?) from an existing node and customize path and breadcrumb

The base url of the view would be home/resources/gallery/%/%/% this would ensure that the view is invoked only when all three arguments are present.

and Rather than sending one argument to the view you would be seinding three arguments.

Conference Type - The taxonomy term
Continent - The Taxonomy term
conference-name

Since your content would have all three condition to be true you would get the required url. Other wise you can set it to show a page not found or may do some other things as you want.


Parent theme hook is still being called when overwritten

Yes theme functions when overridden stay overridden in the sub-theme, but this is not a theme function, but rather a hook function used in a theme.

So hook_element_info_alter() whenever it is implemented will run.


Why not just use the addthis module rather than adding a block. If you however want to add a block, just go to admin/structure/block click on add block. Paste your script in and select filter type of php code and click save

If you do not have PHP filter in the filter type, enable it under the core module


How can I programmatically change the active theme?

In Drupal 8, you use theme negotiators, which essentially are services using a specific tag. See the theme negotiators implemented by Drupal, to understand exactly how they work; the example given in the change record is not updated.
user.services.yml
  theme.negotiator.admin_theme:
    class: Drupal\user\Theme\AdminNegotiator
    arguments: ['@current_user', '@config.factory', '@entity_type.manager', '@router.admin_context']
    tags:
      - { name: theme_negotiator, priority: -40 }

AdminNegotiator.php
<?php

namespace Drupal\user\Theme;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\DependencyInjection\DeprecatedServicePropertyTrait;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Routing\AdminContext;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Theme\ThemeNegotiatorInterface;

/**
 * Sets the active theme on admin pages.
 */
class AdminNegotiator implements ThemeNegotiatorInterface {
  use DeprecatedServicePropertyTrait;

  /**
   * {@inheritdoc}
   */
  protected $deprecatedProperties = ['entityManager' => 'entity.manager'];

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $user;

  /**
   * The config factory.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The route admin context to determine whether a route is an admin one.
   *
   * @var \Drupal\Core\Routing\AdminContext
   */
  protected $adminContext;

  /**
   * Creates a new AdminNegotiator instance.
   *
   * @param \Drupal\Core\Session\AccountInterface $user
   *   The current user.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\Core\Routing\AdminContext $admin_context
   *   The route admin context to determine whether the route is an admin one.
   */
  public function __construct(AccountInterface $user, ConfigFactoryInterface $config_factory, EntityTypeManagerInterface $entity_type_manager, AdminContext $admin_context) {
    $this->user = $user;
    $this->configFactory = $config_factory;
    $this->entityTypeManager = $entity_type_manager;
    $this->adminContext = $admin_context;
  }

  /**
   * {@inheritdoc}
   */
  public function applies(RouteMatchInterface $route_match) {
    return ($this->entityTypeManager->hasHandler('user_role', 'storage') && $this->user->hasPermission('view the administration theme') && $this->adminContext->isAdminRoute($route_match->getRouteObject()));
  }

  /**
   * {@inheritdoc}
   */
  public function determineActiveTheme(RouteMatchInterface $route_match) {
    return $this->configFactory->get('system.theme')->get('admin');
  }

}

The code is pretty easy to understand: The applies() method returns TRUE when the current route is the one for which your module wants to change the theme; the determineActiveTheme() method returns the theme machine name of the theme to apply.
See also ThemeNegotiator::determineActiveTheme() should not require a RouteMatch to be passed in for a possible change on the arguments received from the methods used by theme negotiators; if that patch is applied, you will need to change your theme negotiator code too.
That issue's status has been Needs work since May 10, 2018; it has been also moved to Drupal 9.2.x on December 28, 2018. Drupal 8.9.x could not get that change back-ported and it's probably safe to say that a Drupal 8.x module needs to use the RouteMatchInterface $route_match parameter for applies().


Quick edit destroys CKEditor formatting... any way to avoid it?

If you want to switch between text formats and not have your code erased go to:

/admin/config/content/ckeditor/edit/Advanced (for Filter HTML)

/admin/config/content/ckeditor/edit/Full (for Full HTML)

Then under Advanced Content Filter, select disabled.


Does a module for real-time data plotting exist?

Google Chart Tools

  Display live data on your site using Google Chart Tools Google Chart
  Tools module provides a simple API to Build custom interactive SVG
  charts.

  Views integration

  The Google Chart Tools Views module is based on the Views built in
  aggregation function. For basic instructions of using the Views
  integration module check the README.txt file

or

Quant provides an engine for producing quantitative, time-based analytics for virtually any Drupal component. Quant takes raw data about normal Drupal actions, such as node creation, and plots the activity over time, with the selected time being configurable. See the screenshot provided for a better understanding.

  Quant API (easily provide your own charts)

  The real power of Quant lies in it's ability to generate these charts
  with very little provided information. Quant offers a simple, yet
  flexible API to allow developers to include quant charts with their
  modules.


Forms - Clone form with different url + theme

You can create path(url) alias for this. Using alias the same url will be called.
Regarding theme you can alter form with some condition to assingn different theme.
e.g.

function YOURMODULE_form_alter(&$form, &$form_state, $form_id) {
 if(SOME_CONDITION){
  $form['#theme'] = 'FORM_THEME1'
 }else{
  $form['#theme'] = 'FORM_THEME2'
 }
}


How to make the permissions of a module more granular?

Rules (the module) is your friend ... Here is the rule (in Rules export format), that does exactly what this question is about (using the Visitors module as an example, like the ABC in the question):

{ "rules_limit_access_to_some_urls_related_to_visitors_" : {
    "LABEL" : "Limit access to some URLs containing \u0027visitors\u0027",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "1" : "1" } }
        }
      },
      { "OR" : [
          { "data_is" : {
              "data" : [ "site:current-page:path" ],
              "op" : "IN",
              "value" : { "value" : [
                  "visitors\/hosts",
                  "visitors\/hits",
                  "visitors\/referers",
                  "visitors\/user_activity",
                  "visitors\/pages"
                ]
              }
            }
          },
          { "text_matches" : {
              "text" : [ "site:current-page:url" ],
              "match" : "node\/\\d+\/visitors",
              "operation" : "regex"
            }
          }
        ]
      }
    ],
    "DO" : [
      { "redirect" : { "url" : "visitors" } },
      { "drupal_message" : {
          "message" : "Access to the content located at \u0022\u003Cstrong\u003E[site:current-page:path]\u003C\/strong\u003E\u0022 is not allowed.\r\n\u003Cbr \/\u003E\r\nAnonymous users can only see its corresponding menu item (login required).",
          "type" : "warning"
        }
      }
    ]
  }
}

After you enable the above rule, you can safely grant Access (view) "all results" produced by module ABC permission to anybody. That will make the menu items visible to anonymous users also (of course). The above rule will ensure that anonymous users will NOT be able to actually "view" the specified URLs. Instead they'll get a message starting with "Access to the report located at ...".

To make the above rule work in similar situations, just adapt the URLs (change 'visitors' to whatever fits), and the message to be shown for those who are not allowed to access those URLs.

Possible variations: instead of using the above rule for anonymous versus authenticated users, it can also be used for any combination of 2 roles. eg: "authenticated" versus "editors" (or whatever other role), in which case you'd grant the permission to "authenticated" (and use the role id for authenticated users).

Remarks:

This won't prevent the path from being omitted from menus. But that is exactly what is desired (as mentioned in the last phrase of the question).
What is above does not relate to any "other places" where path checks happen that aren't direct page access. But whenever one attempts to use those paths in those "other places" to actually visit such paths (URLs), the above rule will catch those situations also (provided such URL is correctly mentioned in either of the Rules Conditions in my sample above).


Send mail to product owner only when the email adress is available

The email address is added to the product by hand in a custom field

I supouse that the field for entering email, is an email field (must enter a 'valid email' in format: somename@someurl.something, avioding a 'blah blah email'), if so:
then in your rule add a condition: [your_email_field] is not empy, if that condition is far away to be implemented in rules area: condition, then use rules conditional module, when your a ready to implement 'send email' in your rule, before that accion, add condition: [your_email_field] is not empty, if user entered a 'fake email', drupal will send email, but it will not go anywhare, this way you can avoid your error, and only valid emails will be delivered.


What I suggested is that I would overwrite the $form array with an
  blank one but as I run my xdebug drupal seems to just ignore it
  because the $form array in its native status exists although I tried
  to overwrite it with a blank one.

What you describe does look like caching. Drupal returns what is cached, without running the code to build the form again.

You don't give much information, but you did tell in the comments, the form is part of a rendered page. If the form would be a page on it's own, then this is about access. If you only want control if a part of the page is displayed, then this is about blocks. The first thing to try is to configure the visibility of the form  block. If you can't configure it in ui, then there are several ways to put custom code in block or page level to remove the block. This depends when and where the block should be displayed.


Users are unable to approve a one way relationship

It looks like this actually was a permissions issue. In order for someone to be able to accept a relationship request, they also need permission to make the request.

In order to accomplish what I needed I also had to enable the "User Relationship Implications" module.


Where and how to conditionally redirect old aliases to new aliases

This solution is based on a suggestion by @4k4 at Redirect from within controller always goes to home page.

My custom module is named rsc.

In modules/custom/rsc the file rsc.services.yml includes the following:

services:
  rsc.event.Redirect404:
    class: Drupal\rsc\EventSubscriber\rscRedirect404
    tags:
      - {name: event_subscriber}

In modules/custom/rsc/src/EventSubscriber the file rscRedirect404.php contains the following:

<?php
namespace Drupal\rsc\EventSubscriber;

use Drupal\Core\EventSubscriber\HttpExceptionSubscriberBase;
use Drupal\Core\Url;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;

class rscRedirect404 extends HttpExceptionSubscriberBase {

  protected function getHandledFormats() { // required
    return ['html'];
  }

  public function on404(GetResponseForExceptionEvent $event) {

    $path = \Drupal::request()->getPathInfo();
    $path = [code to modify the path from old site to new site]

    if (($url = \Drupal::service('path.validator')->getUrlIfValid($path))) {
      $event->setResponse(new RedirectResponse(URL::fromUserInput($path)->toString()));
    }
  }
}

With this in place, I see 404 redirects before they get passed to the default handler. If I do the $event->setResponse(), the user is redirected as I specify. If not, normal processing occurs.

In reality, the line that says [code to modify the path from old site to new site] is multiple lines where I do several trial-and-error tests to figure out the correct new URL,  but everything else is just as I'm using it.


Admin -> Run Updates, Unresolved dependency

So what am I missing?

Nothing at all, the messages are pretty clear:

The version of CKEditor Media Browser that you're updating to has a dependency on File Entity 7.x-2.0 or greater. You have version 7.x-2.0-beta3, which is not greater than 7.x-2.0, so the upgrade isn't possible.

You need to update File Entity to the required version first, then proceed with the update of the media browser module.

Do bear in mind that the modules you're dealing with are in beta, and haven't had development effort in a while. It's entirely possible that you might not be able to perform the update. Case in point: https://www.drupal.org/node/2838674


What is the fastest/simplest way to add/manipulate PHP on a page?

You are in fact asking four questions here.

As jhedstrom said, you need to use the hook_block_info() / hook_block_view() hooks. A quick google search pointed to to this example: http://www.summasolutions.net/blogposts/how-create-basic-block-code-new-drupal-7
You can use the hook_block_view_alter() or hook_block_view_MODULE_DELTA_alter() hooks.
You can find detailed information about how to create a form in drupal in the quickstart guide. Note that this is for Drupal 6 but works the same way in Drupal 7 for the most part.
This does not require any code at all. In fact, doing this with code is doing it the wrong way. Instead, you can disable account registrations by visitors at Configuration > Account settings, set "Who can register accounts?" to Administrators only.


Drupal Coding D7 - Taxonomy - How do I establish the hierarchy and associated fields for taxonomy terms?

Here is an example:

// create the Foo vocabulary
$vocabulary = new stdClass();
$vocabulary->name = "Foo Name";
$vocabulary->machine_name = "foo_vocab";
$vocabulary->description = "Foo Description";
taxonomy_vocabulary_save($vocabulary);
// annoyingly taxonomy_vocabulary_save doesn't return any information about the vocabulary
$voc_vid = db_query("SELECT v.vid FROM {taxonomy_vocabulary} v WHERE v.machine_name = 'foo_vocab'")->fetchField();
$terms = array(
  'bar',
  'bat',
);
foreach ($terms as $term_name) {
  $term = new stdClass();
  $term->vid = $voc_vid;
  $term->name = $term_name;
  taxonomy_term_save($term);
}


Creating multiple destinations from one source

I usually use D7 migrate. But from what i've read of D8 either of these approaches should work:

  My problem is the first migration. The Migration API wants to map a single source to a single destination.

Option 1

In migration 1 simply import any encountered file into drupal. Then record the file id to a custom table of columns legacy_url, old_source_id, drupal_file_id for example in the complete() method of the migration.

In your second migration pass an array of drupal_file_id to your Node's file field from a select drupal_file_id from mytable where old_source_id = $old_source_id. This will attach the legacy files into the new Node. You may need still need to adjust any inline usage of images, or just use a view_mode to show the file list in D8.

Option 2

Just import articles (don't use a 1st migration for just files) and use complete() method in a migration to scan the HTML using DomDocument or simple_html_dom to find file urls and use the drupal API to save the remote file to drupal and then update the DOM with the new url. Create a custom rollback function to remove these files if needed.

Edit

Some example Drupal 8 file migration logic and classes can be seen at the following link. This may not address your exact issue, but in my opinion is good reference.
http://www.jeffgeerling.com/blog/2016/migrating-20000-images-audio-clips-and-video-clips-drupal-8


How to set field values when creating new node with Rules?

Yes you can.

Add action: Create a new entity >> select your content type

Add action: Set A Data Value and for data selector use, for example if want to set a value for the body then you use: entity-created:body

In your case entity-created:field-age

Add action: Save Entity >> entity-created


Calling exit() yes is a little bit too harsh and it does bring some consequences with it:

Typically when drupal_cron_run() finishes running all the cron jobs created with hook_cron() it logs into the watchdog the message "Cron run completed". Aborting your cron cycle mid-execution leaves you with no traces of how or when your cron finished.
When the cron cycle begins, Drupal creates a cron lock by using variable_set('cron_semaphore', time());, which prevents further cron cycles from running until you release the sempahore (manually) or until 3600 seconds pass since the last time you aborted the cron.

When your abort condition is met, you should at least do the following:

// Call cleanup function.
drupal_cron_cleanup();

// Release cron semaphore
variable_del('cron_semaphore');

watchdog('name_of_yourmodule', 'Aborted because XYZ.', array(), WATCHDOG_ERROR);

Also like @wiifm mentioned in his answer, a lot of critical functions defined by core and contrib depend on cron running to keep your site working. Abort cron and your site suddenly stops running smoothly. I would really avoid doing this.


You can create a separate library for external bootstrap stylesheet, which will give you flexibility to load bootstrap css before loading global-styling css. Here's how to do it:

YOURTHEMENAME.info.yml

# Defines libraries group in which we can add css/js.
libraries:
  - sp/bootstrap // ADDED - note: this should go before your global-styling
  - sp/global-styling
...

YOURTHEMENAME.libraries.yml

# note: bootstrap library should go before global-styling
# use { type: external } for external resources
bootstrap:
      css:
        theme:
         '//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css': { type: external }
global-styling:
      css:
    ...