How do I change priority of two different implementations of hook_node_access()?

Use hook_module_implements_alter():

  This hook is invoked during module_implements(). A module may implement this hook in order to reorder the implementing modules, which are otherwise ordered by the module's system weight.

Example:

function MYMODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'node_access') {
    // Move your module's implementation to the end of the list
    $group = $implementations['MYMODULE'];
    unset($implementations['MYMODULE']);
    $implementations['MYMODULE'] = $group;
  }
}

In the possible event that another module also implements hook_module_implements_alter to move its own implementation of hook_node_access to the end of the list, you can get cunning and make sure your implementation of the alter hook runs last too:

  if ($hook == 'node_access' || $hook == 'module_implements_alter') {
    // Move your module's implementation to the end of the list
    $group = $implementations['MYMODULE'];
    unset($implementations['MYMODULE']);
    $implementations['MYMODULE'] = $group;
  }


Multisite Drupal with Organic Groups problem.. custom /user and /user/register links for each group?

I would probably look at PURL for this, an API to make a part of a URL persistent.
PURL itself does nothing since it's an API, but you can get started with OG Purl.
Be warned, it's more advanced to be creating your own bridge like OG Purl does. A lot of motivation is required :)


Create exposed filter for Views PHP value

If you are using Views PHP, then you are using it's alpha or development version. Alpha tests means that maintainer expects there to be bugs and want you to report them in issue queue. Development version almost certainly have issues, that's the nature of ongoing development.

Having that said, you shouldn't attempt to use exposed filters on fields that are not in database, and cannot be readily joined and used in SQL WHERE with your data. Unless, of course, module that provides it already implemented it properly, and it appears it is not the case here. So your options are:

Forget Views PHP for dates, and use regular Date to get date fields attached to your entities, and Date views submodule for views exposed filters, or
Post a bugreport and wait for it to be fixed. Just don't really expect it to happen, as module currently lacks manpower and is seeking co-maintainers.


How to add a custom field to apache solr?

1) Copy /modules/contrib/search_api/src/Plugin/search_api/processor/AddURL.php into your own custom module at /src/Plugin/search_api/processor

2) Rename and rework (see below)

3) Add your extra field to the index at /admin/config/search/search-api/index/myindex/fields

4) Enable the processor on your search_api index

5) Reindex content and verify in solr that your new custom field is indexed.

http://127.0.0.1:8983/solr/#/mysolrcore/schema-browser?field=sm_mymodule_content_type, click on "Load Term Info" to see data loaded in.

Here's an example:

namespace Drupal\mymodule\Plugin\search_api\processor;

use Drupal\search_api\Datasource\DatasourceInterface;
use Drupal\search_api\Item\ItemInterface;
use Drupal\search_api\Processor\ProcessorPluginBase;
use Drupal\search_api\Processor\ProcessorProperty;

/**
 * Adds a custom type filter to the indexed data.
 *
 * @SearchApiProcessor(
 *   id = "mycustom_field",
 *   label = @Translation("Custom Field"),
 *   description = @Translation("Add a custom field to search index"),
 *   stages = {
 *     "add_properties" = 0,
 *   },
 *   locked = true,
 *   hidden = false,
 * )
 */
class CustomField extends ProcessorPluginBase {

  /**
   * machine name of the processor.
   * @var string
   */
  protected $processor_id = 'mycustom_field';

  /**
   * {@inheritdoc}
   */
  public function getPropertyDefinitions(DatasourceInterface $datasource = NULL) {
    $properties = array();

    if (!$datasource) {
      $definition = array(
        'label' => $this->t('Custom Field'),
        'description' => $this->t('custom field'),
        'type' => 'string',
        'processor_id' => $this->getPluginId(),
      );
      $properties[$this->processor_id] = new ProcessorProperty($definition);
    }

    return $properties;
  }

  /**
   * {@inheritdoc}
   */
  public function addFieldValues(ItemInterface $item) {
    $entity = $item->getOriginalObject()->getValue();

    $custom_field = '';

    // Use $entity to get custom field.

    $fields = $this->getFieldsHelper()
      ->filterForPropertyPath($item->getFields(), NULL, $this->processor_id);
    foreach ($fields as $field) {
      $field->addValue($custom_field);
    }

  }
}


Authenticated users can not see own Ubercart order detail

I found the offending code. It was the code for a block to display a link to "My Orders" if the user had any orders. I removed this code from the block, and the order detail now displays for authenticated user.

The offending code:

global $user;

$uid = $user->uid;

// print 'This is my user id ' . $uid;

        $count = 0;
        $args = array($uid);
        $view = views_get_view('uc_orders_user');
        $view->preview('page', $args);
        $count = sizeof($view->result);

// drupal_set_message($count);

  if ($count > 0) {
    return TRUE;
  } else {
    return FALSE;
  }

Do not know why this code causes the error, but it does.  If I find a way to tweak it to work, I'll post it here.


See the Multistep module. Although it is under development for Drupal 7.


How do I add an 'order complete' from the Commerce module to the Rules events in Drupal 8?

After trying out combinations and with the helpful comments, the solution was to follow the Rules documentation but change the event to commerce_order.place.post_transition which I got from the tutorial.

The final code was to create a MODULENAME.rules.events.yml file and add the following code:

commerce_order.place.post_transition:
  label: 'Order has been completed'
  category: 'Order'

This created the option in the dropdown and allowed me to create the rule that triggered the action.


How to improve comments when using Acquia Marina theme

The only options for changing the styling of the comments in Acquia Marina are to customize the theme or to install a third-party commenting system such as Disqus http://drupal.org/project/disqus

If you decide to customize the styling of Acquia Marina, here are a few tips and resources:

Documentation on customizing a Fusion-based theme. Be sure to read the section on "Using local.css" http://fusiondrupalthemes.com/support/documentation/customizing-your-theme

If you are not very familiar with CSS, a good, general tutorial on what CSS is and how to use it - http://www.w3schools.com/css/default.asp

The Firebug plugin for Firefox is very helpful for troubleshooting CSS and discovering what CSS rules need to be written to make changes to your theme's styling. Here is a tutorial on using that plugin: http://www.kristarella.com/2009/02/how-to-use-firebug-for-css/


Manage photo default settings in Node gallery module

There is a Theming Function inside the theme.inc (\node_gallery\theme\theme.inc) file:

theme_node_gallery_api_manage_items_form($variables)

In there is everything you need. Copy this whole function to your template.php, rename the function to YOURTHEMENAME_node_gallery_api_manage_items_form($variables) and change the desired text. I think this should to the trick.

Paste the below code inside your active theme template.php file and make sure to change to you theme name.

    /**
     * Theme function for Manage Items form.
     */
    function elegant_theme_node_gallery_api_manage_items_form($variables) {
        $form = $variables['form'];

        if (empty($form['items'])) {
            return t('This gallery is empty.');
        }
        // Pull in the multi-select functionality from core.
        drupal_add_js('misc/tableselect.js');
        // Get fieldname to retrieve the filepath for the thumbnail without
        // loading the node.
        $relationship_type = node_gallery_api_get_relationship_type($form['#gallery']->type);
        $enable_rotation = FALSE;
        if ($relationship_type->settings['manage_items']['enable_rotation'] && (image_get_toolkit() != 'gd' || function_exists("imagerotate"))) {
            $enable_rotation = TRUE;
            drupal_add_library('system', 'ui.dialog');
            drupal_add_library('system', 'ui.draggable');
            drupal_add_library('system', 'ui.resizable');
            drupal_add_js(drupal_get_path('module', 'node_gallery') . '/js/ng_manage_images.js');
        }
        $header = array(
            t('Album Cover'), //changed from Cover to Album Cover
            t('Preview'),
            t('Edit'),
            array(
                'data' => t('Delete'),
                'class' => 'select-all',
            ),
        );
        if ($enable_rotation) {
            $header = array(
                t('Album Cover'), //changed from Cover to Album Cover
                t('Preview'),
                t('Edit'),
                t('Rotation'),
                array(
                    'data' => t('Delete'),
                    'class' => 'select-all',
                ),
            );
        }
        $rows = array();
        foreach (element_children($form['items']) as $nid) {
            $element = &$form['items'][$nid];

            $row = array();
            //Cover checkbox
            if ($form['is_cover']) {
                $row[] = drupal_render($form['is_cover'][$nid]);
            }
            //preview
            $file = $element['item_file']['#value'];
            if (!empty($file)) {
                $file_object = (object) $file;
                $file_view = file_view($file_object, 'node_gallery_api_admin_thumbnail');
                $row[] = drupal_render($file_view);
            }
            else {
                $row[] = '';
            }
            //edit link
            $edit = drupal_render($element['edit_form']);
            if (!empty($element['ngid'])) {
                $edit .= drupal_render($element['ngid']);
            }
            $row[] = $edit;
            //Rotation
            if ($enable_rotation && !empty($file) && $file['type'] == 'image') {
                $row[] = drupal_render($element['rotate']);
            }
            elseif ($enable_rotation) {
                drupal_render($element['rotate']);
                $row[] = '';
            }

            $row[] = drupal_render($element['remove']);
            $rows[] = array('data' => $row);
        }
        $output = theme('table', array(
            'header' => $header,
            'rows' => $rows,
            'attributes' => array('id' => 'upload-attachments'),
            )
        );
        $output .= theme('pager');
        $output .= drupal_render_children($form);
        return $output;
    }


My Feature depends on a module. Do I have to specify that module's dependency, as well?

If you use ctools calls in your module, then you should declare it as a dependency. Otherwise no need.


Checking two databases when logging in a user with a custom module

Never tried, but you can basicaly:

try hook_user() but you may not catch the case where the user doesn't exists in drupal but your other site.
create your own login form & callback and:

check if user exists in drupal with user_external_load()
if user exists on your external site either login or register on drupal using user_external_login_register()

You may find some interesting code in the openid_authentication().


In my case the issue ended up being pretty simple to fix. I found that the function entity_translation_form_alter() was testing to see if my entity's edit form was suitable for alteration. My edit form failed the very first test because entity_translation_edit_form_info() was returning false.

entity_translation_edit_form_info() was returning false because my form didn't have $form_state[$entity_info['translation']['entity_translation']['edit form']] set and set to the entity I was trying to edit.

tl;dr: Make sure you set a value in your edit form's $form_state at the path you declare in the edit form element of the settings array for your entity returned by your implementation of hook_entity_info().


Yes, you can do this with a Contextual filter in Views.

Create a Content View of your desired nodes, then add a Contextual Filter (I'm assuming your categories are actually Taxonomy terms referenced from nodes) for the Field with that Taxonomy reference.

Configure it with these options:
    When the filter value is NOT available
    Display a summary
    Format List
    Base path (you must enter the Page path if this isn't the first Page Display in your Views)
    Display record count with link
    More
    Transform spaces to dashes in URL

This way you get a list of term IDs that link through to a list of nodes tagged with those terms.

You probably want the term name to be displayed instead of the term ID. In that case remove the Contextual filter, we'll add the one for Taxonomy term Name, but we need a Relationship first for that information to become available.

So add a Relationship Taxonomy term referenced from field_category (or whatever the field is called in your case), require it if you don't want summary results without a category.

Then add a Contextual filter Name from Taxonomy term Category, it will use the Relationship we created, and configure it like above.


I believe you are using the wrong template in order to access the relevant information. As your comment states your view template is for the entire View, and as you say it looks through the entire document and will always find the content type if any content of that type is present.

Since you are trying to affect a single field, you should look at other template suggestions for fields only in order to process the fields individually instead of trying to do it at the whole View stage.


Check that the .htaccess file exists in the Drupal root. Sometimes people unzip/untar or copy paste Drupal directories and this file is excluded by some operating systems and file transfer programs.

Drupal 7 .htaccess: http://cgit.drupalcode.org/drupal/tree/.htaccess?h=7.x

Drupal 8.2.x .htaccess: http://cgit.drupalcode.org/drupal/tree/.htaccess

This is usually the cause of what you report.

Otherwise, this could be an issue with how Apache or IIS is setup to serve your Drupal site. Since you can really get in the weeds with server configurations such as Apache, it is recommended you use something like Acquia Dev Desktop or DrupalVM to install and run a Drupal site locally, so you can sidestep issues and run a local site under generally accepted best practices for a LAMP stack tuned for Drupal.


This can be done with drupal console, you can find it here: https://hechoendrupal.gitbooks.io/drupal-console/content/en/index.html

The command to use is this:
drupal module:install --overwrite-config

Just install drupal console and use the command.


Syntaxhighlighter Insert do not working with CKEditor 4

It's simple - switch to WYSIWYG module and install CKEditor as library. CKEditor module and WYSIWYG module are separated projects that happens to use the same library, so if you want to use modules and articles designed to work with WYSIWYG, you need WYSIWYG.


Access denied for custom configuration form translation

Got it finally working.
The 'name' array in config_translation was not matching with the actual file.

samplewil.settings.yml file should be renamed to samplewil.config.yml :)


Function not working in contextual filter

I just get it done by enabling validation criteria, I selected content validation with node content type and its working fine.


Create contextually filtered view of shared fields across multiple content types

I haven't tried anything exactly like this buts it sounds like it is very possible if you mess with your AND, OR settings. Since they share the same field and that is what you are filtering on there should be no issue with that being your contextual filter.

Look at your regular filters under 'Filter Criteria'. Filter on the content type in an OR group using 'And/Or, Rearrange' (the arrow next to 'Add'). And it should work.


You can do this with the Aegir hosting System http://www.aegirproject.org/
It presents an intuitive front end to multisite.


How to remove paragraph tag from ckeditor?

In Drupal 8, you may need to implement hook_editor_js_settings_alter and set config.autoParagraph to false, as referenced here: CKEDITOR.config.autoParagraph

/**
 * Implements hook_editor_js_settings_alter().
 */
function MODULE_editor_js_settings_alter(array &$settings) {
  foreach ($settings['editor']['formats'] as $name => $value) {
    $settings['editor']['formats'][$name]['editorSettings']['autoParagraph'] = FALSE;
  }
}


Two levels of options in add to cart form

This is not how Drupal Commerce normally works w/ attributes - you typically define all of the possible variants as SKUs, associate them all together on the Add to Cart form, and show a form with both attribute select lists shown at once. You can alter that form to your heart's content, though, hiding one select list until another is adjusted - but note that Drupal Commerce also doesn't support an attribute not having a selection out of the box. This is a technical limitation of how the form is designed to work, but there is an open issue in the queue trying to support that.


How can I check if a node references a Drupal Commerce product?

There isn't a short function, though that's not a bad idea for a feature request. However, it's not that difficult using the Field Info API to determine if a given node contains a product reference field. One method would be using field_info_instances().

With this function and your node object, you can retrieve an array of all field instances on your node with the following code:

$instances = field_info_instances('node', $node->type);

You would then need to loop over the returned instances and use field_info_field($instance['field_name']) to load the field info array and see if the type of any given field is commerce_product_reference. If so, then you know the node can at least refer to a product... but that doesn't mean a reference is actually established.

For that you'd need to make sure the node contained data for that instance. That could be as simple as checking if (!empty($node->$instance_name)), but it'll depend on how you're actually building / using these reference fields.

One simpler way to find if a product reference instance is on the node is possible if you know your reference field's name. For that you can use field_read_instance() with the following code to return the info array of the instance or FALSE if it doesn't exist for the given node type:

$instance = field_read_instance('node', $field_name, $node->type);

Hope those help, and feel free to open an issue in the Commerce issue tracker for any related helper functions under the "Developer experience" component. I suggest you spend time getting to know the Field Info / CRUD APIs, as they'll be very helpful to you in your Drupal 7 development.


How to update the search title and page title depending on facet options

The solution is on the Facet API Bonus module's project page:

Integration with Page Title module Now you can set search (views) page titles using Page Title module. Module provides possibility to set tokens 'facetapi_results' and 'facetapi_active' groups. So in title we can display number of results on the page or values of active facets. As there can be multiple active facet values please use following pattern to use facetapi_active tokens:
list<[facetapi_active:facet-label]: [facetapi_active:active-value]>

This will make coma separated list of active facet labels and their values.


How to replace the Bartik default menu with Superfish

I found a report, How to apply Bartik main-menu styles to other menu modules similar to Superfish. Essentially, the trick is not to apply the CSS styles used by Superfish to the CSS styles used by the theme, but to include the CSS styles used by the theme in the CSS styles used by Superfish.

The steps reported in that post are the following (I am editing them to change the format).

Create a new style sheet (NewStyleSheet.css) and save it to your file directory.
Edit the block settings for Superfish in /admin/structure/block. This step list assumes you are using a template that includes a "Menu Bar" or similar block area.

Move the block "Superfish X" to the "Menu Bar" region, by changing the drop down selector value to "Menu Bar."
Click "Configure" under "Operations," on the far right of the setting page.
Under "Superfish Settings," change "Menu Type" to "NavBar."
Optionally, select "NO" on both "Drop shadows" and "Auto-arrows", as this would take more time to modify the CSS to get them to show up properly.
In "Advanced Settings," add your new stylesheet location to "Extra CSS."

This is the content of the new CSS file.

/* $Id: whiteTab.css,v 1.0 2011/02/18 05:45:00 erok415 Exp $ */

/*-------------------------------------------------------------*/
/*                                                             */
/*      Important - Be sure to change all references           */
/*      from #superfish-3 below to match the number of the     */
/*      Superfish "X" block region you are using in your       */
/*      Block Settings. I used block region Superfish 3,       */
/*      hence I am using #superfish-3 below.                   */
/*                                                             */
/*-------------------------------------------------------------*/

/*-------------------------------------------------------------*/
/*                                                             */
/*   I have not attempted to use style the 4th level flyout,   */
/*      Auto-arros or the drop shadow features.                   */
/*                                                             */
/*-------------------------------------------------------------*/

#menu-bar{
  margin-bottom:10px;/* Add padding so secondary navigation doesn't run over search sidebar. */
}

sfHover, ul#superfish-3 > li:hover{
  background: none repeat scroll 0% 0% transparent; /* Remove the default background on top level tabs in default state and hover state. */
}

ul#superfish-3 li.sfHover li  a:hover, ul#superfish-3  li.sfHover  li a.active{ /*Secondary Nav: add effect to hover or active state here. */
  color:#09F;
  width:100%;
}

ul#superfish-3 > li > a{ /* Fist level horizontal navigation. */
  margin:4px 2px 0 0; /* Spacing around tabs. */
  color: #333;
  background: #fff;
  background: rgba(255, 255, 255, 1.0);
  float: left; /* LTR */
  padding:0px 6px 6px 6px;
  /* height: 1.8em;
  line-height: 2.4em;
  padding: 0 0.8em; */
  text-decoration: none;
  /* text-shadow: 0 0.5px #999; */
  font-weight:bold;
  -khtml-border-radius-topleft: 8px;
  -khtml-border-radius-topright: 8px;
  -moz-border-radius-topleft: 8px;
  -moz-border-radius-topright: 8px;
  -webkit-border-top-left-radius: 8px;
  -webkit-border-top-right-radius: 8px;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
}

ul#superfish-3 > li.sfHover {
  background: none repeat scroll 0% 0% transparent; /* Remove the default background from the sfHover state. */
}

ul#superfish-3 > li.sfHover > a { /* First level hover and active state. */
  margin:4px 2px 0 0; /* Spacing around tabs. */
  color: #333;
  background: #999;
  background: rgba(153, 153, 153, 1.0);
float: left; /* LTR */
  padding:0px 6px 6px 6px;
  /* height: 1.8em;
  line-height: 2.4em;
  padding: 0 0.8em; */
  text-decoration: none;
  /* text-shadow: 0 0.5px #999; */
  font-weight:bold;
  -khtml-border-radius-topleft: 8px;
  -khtml-border-radius-topright: 8px;
  -moz-border-radius-topleft: 8px;
  -moz-border-radius-topright: 8px;
  -webkit-border-top-left-radius: 8px;
  -webkit-border-top-right-radius: 8px;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
}

/*------------------- Secondary Nav -------------------*/
.sf-navbar > li > ul{ /* Add background color to secondary nab only. */
  background:none repeat scroll 0% 0% rgb(51, 51, 51);
  background: #333;
}

ul#superfish-3 > li > ul{
  left:-15px; /* Align the menu with the left edge of design. */
  border-right:30px solid #333;/* Add the background color to the right edge because the style attribute above leaves a blank spot due to global conditions. */
}

ul#superfish-3 > li > ul > li {
  left:15px;/*Fix: aligns secondary level nav text with top level nav*/
  border:0;
}

ul#superfish-3 > li.sfHover > ul > li > a{ /* Secondary Nav: Remove tab effect from sfHover state applied to lower level nav. */
  color:#fff;
  background: #333;
  -khtml-border-radius: 0px;
  -moz-border-radius: 0px;
  -webkit-border-top: 0px;
  border-radius: 0px;
  width:100%;
  height:2.0em;
  line-height:1.1em;
  padding:6px 0 0 6px;
  margin:0 16px 0 0;
}

ul#superfish-3 > li > ul > li > a{ /* Secondary horizontal navigation. */
  color:#fff;
  font-weight:bold;
  /* text-shadow: 0 0.5px #CCC; */
  background: none repeat scroll 0% 0% transparent;
  -khtml-border-radius:0;
  -moz-border-radius:0;
  -webkit-border-radius:0;
  padding:0;
}

/*--------------- Third level DropDown navigation ------------*/
ul#superfish-3 > li > ul > li > ul {
  -khtml-border-radius: 0px;
  -moz-border-radius: 0px;
  -webkit-border-top: 0px;
  border-radius: 0px;
  margin:0;
  padding:0 0 0 6px;
  border:0;
  left:-0px;
  background: none repeat scroll 0% 0% transparent;
}

ul#superfish-3 > li > ul > li > ul > li  {
  margin:0px;
  border-right:0;
  left:0;
  border:0;
  padding:6px 6px 0px 6px;
  background:#333;
}

ul#superfish-3 > li > ul > li > ul > li:hover{
}

ul#superfish-3 > li > ul > li > ul > li > a {
  background:#333;
  margin:0;
  padding:0 6px 0px 6px;
  line-height:1.3em;
  background:#333;
}

ul#superfish-3 > li > ul > li > ul > li > a:hover {
  background: none repeat scroll 0% 0% transparent !important;
}


I think the Views Aggregator Plus module can be of help. Among others it has possibilities to tally and enumerate views fields, so I think you can make the summary table you're asking for.

The module description is as follows:

  In addition to what Views and Views Calc do, this module:

  enumerates group members
  produces tallies, i.e. textual histograms
  aggregates on Views PHP code-snippet evalutations
  can filter out result rows on regexp patterns
  gives you sorting on Views' Math expressions
  can process Webform submissions
  lets you add your own custom aggregation functions

  ... and it puts summary statistics at the bottom of your aggregated
  table as well!


How to show breadcrumbs for taxonomy terms in Drupal 7

Use Taxonomy Menu Trails module. its better than 'Taxonomy breadcrumb'.


How to theme "group by" header in a view

Theming views can be done in a number of files.  For best assistance I suggest in views you look at the "Theme Information" option.  It can be found at {drupal site}/admin/structure/views/nojs/display/{view name}/page/analyze-theme (It's under the right hand side "Advanced" column).

On that screen you will find a list of all the files that you Drupal will look for to theme for the view concerned, ranging from the very specific (views-view-fields--{view-name}--{display-name}.tpl.php for row styling) to a slightly more generic views-view.tpl.php (Covers every view)  You can drill further down depending on what your view selects (Fields, Rendered Entity, Display Suite content etc) but the Theme information link shown above should provide you with a list of every file that you can provide to Drupal for theming.

Remember to flush your cache when you add a new theming file so Drupal knows about it.


Assuming you want your breadcrumbs like this:

  Home/La Casa >> Node/Nodo >> Friends/Amigos

You could override template_preprocess_breadcrumb like so:

  function MY_THEME_preprocess_breadcrumb(&$variables)
  {
     $breadcrumbs = &$variables['breadcrumb'];
     foreach($breadcrumbs as &$breadcrumb)
     {
         $breadcrumb .= '/' . locale($breadcrumb, null, 'SP');
     }
   }

Don't quote me on the langcodes, and this would require that you have the locale module installed and enabled, but it should output the above example breadcrumb.


Think of it as "the number of seconds since the the start of the day". To get the number of hours from that:

59400 / 60 / 60 = 16.5

So 16.5 hours since the start of the day: 16:30, or 4:30PM.

If you're looking to get something meaningful out of '16.5' for display on the front end, the timefield module has a theme function:

$formatted = theme('timefield_formatter', array('time' => $time));

Or if you have the value in the field of an entity object, you could use field_view_field() instead. The theme function has more options, you'd need to scan through the module code to understand what these are and which you might want to use.


Have a look at the API documentation for drupal_mail_system(), there you'll have code to override the default MailSystemInterface.

For an exemple of how to override it, have a look at the Postmark module.
You can then redefine the format() function:

class YourModuleMailSystem implements MailSystemInterface {

public function format(array $message) {
  //remove this formatting.
  //$message['body'] = implode("\n\n", $message['body']);
  return $message;
}

//...
}


Sounds to me like you ACTUALLY want Menu block in tandem.

  So… have you ever used the Main and Secondary menu links feature on
  your theme and wondered “how the hell do I display any menu items
  deeper than that?”

I think the following is what you're after, but the module is pretty configurable if I'm mistaken.

Create your taxonomy menu as you normally would, and instead of putting that menu block in the sidebar (or wherever), put a menu block generated block there. Then in the settings for the menu block click Advanced. Under this tab, there's now a chekbox titles Make the starting level follow the active menu item. If you check that box, then the top level will reflect the current page.


For debugging try to output the result of:
\Drupal\Core\Url::fromRoute('<front>')->setAbsolute()->toString()

Is this the wrong protocol, too? Then your browser terminates with a different protocol than the CDN to your web server.
Symfony is able to detect the correct protocol, but you need to configure the CDN (reverse proxy) in settings.php.


Delete block settings when removing a block from hook_block_info()

I hope this should work if I get your question right.

db_delete('block')
  ->condition('module', MODULE)
  ->condition('delta', DELTA)
  ->execute();
db_delete('block_node_type')
  ->condition('module', MODULE)
  ->condition('delta', DELTA)
  ->execute();
db_delete('block_role')
  ->condition('module', MODULE)
  ->condition('delta', DELTA)
  ->execute();

cache_clear_all(MODULE_DELTA, 'cache_block');

Where MODULE resembles your module name and DELTA resembles your block's delta.


How to export (send) image from website to Instagram?

You can use module InstaPost for posting nodes to Instagram. Some details about it (from its project page):

  This module allows users to post nodes automatically to the online
  mobile photo-sharing, video-sharing, and social networking service
  Instagram.

Disclosure: I'm the maintainer of this module.


In your field settings at the end you've a "More" section, click there and then check the "Output machine name"'s option.


Prod CentOS core-only site work fine but local Ubuntu backup has no css loaded

Did you try the 777 recursively inside the files folder? (so it applies on files/css and files/js subfolders)

Also I would check if SELinux is enabled on your CentOS server to discard you downloaded an incomplete copy of your website due to lack of permissions. Use the getenforce command to check if it's set to permissive.
In case of necessary you can use the following command to set the context of files folder to read/write:

chcon -R -t httpd_sys_rw_content_t files


How to create widget element with unlimited values?

I would think that there would be a property as well but I can't think of one for text fields. I know that you can use field collections though.

Edit: I was mistaken Field Collections will not work for custom forms, however This tutorial worked for me.


How to disable Commerce, but still have the module for later use?

Drupal modules in general can be disabled and uninstalled without major problems. Last version of Drupal Commerce (1.5) includes 20 modules, and some of them are totally independent. You definitely can disable Cart and Cart UI modules without disabling others such as the Product and Tax modules.

However, there is an important bug in Drupal Commerce relevant to re-enabling modules that it's still not fixed. See http://drupal.org/node/1361562


There was a page that would allow you to subscribe to different projects, but it has been removed.
The only way to subscribe to project issue queues is the one you described.

The link to subscribe to the issue queue of a project is present in two places:

in the project page, in a block to the right side
in the project issue queue, under the issue queue title


Are you looking for a 'local' flag? Flags are already separated into global and local flags. For example, a global flag might be 'report this comment' and once one person flags the comment it is flagged for everyone. Local flags on the other hand are unique for each user, so for example a 'bookmark this' flag would only be for the current user context and other users wouldn't be able to modify their flags. From the documentation:

  Flags may be per-user, meaning that each user can mark an item
  individually, or global, meaning that the item is either marked or it
  is not marked, and any user who changes that changes it for everyone.

You set whether a flag is global or local when you create it.


Inline images of body is not getting migrated

Looks like the Drupal 6 site which you are wishing to migrate was using the wysiwyg_imageupload module for uploading the images to the content region.
If you have a look at the Repository viewer of the module, you'll see that the module defines certain input filters : Drupal Wiki inline images to be precise which converts the images saved in format [[wysiwyg_imageupload:15:]] into the real path when the page is rendered.

To resolve this, you'll have to implement the prepare function and actually change the value of the content and replace the filter formats with src and then run the migration.


Structuring a user rating/rebuttal system

Use the Flag module to create a Rebut flag, but do NOT make it a 'global' flag though. The flag is to be created (configured) by an admin, but each user (authorized to use the flag) will then be able to "rebut rating" using such flag. If it would make sense, you may want to have multiple flags configured for this (eg: Rebut-low , Rebut-medium, Rebut-high, whatever that would "mean" in your case).

Then create a view (with the views module) for each flag, whereas you create a "views relationship" with such flag(s).

If you're not familiar with the Flag module, checkout the set of 8 video tutorials about the flag module.

You might also want to look at some of the Flag related modules, such as (partial list):

Views, to create lists of flagged content, users, etc, such as in the video about Creating global flags and listing flagged content in Views.
Rules, to trigger rules for anything that is flagged, such as in the video about Triggering rules with Flag, or to set flags with the Rules module, such as in the video about Setting flags with Rules.

Refer to Flag's Community documentation for (way) more details.

Note: Via Rules it should be possibly to add logic to verify the "usage" of such flag.


In the specific example you make, there aren't plugins involved. The hook in invoked from NodeViewBuilder::renderLinks(), which executes the following code.

  $links = array(
    '#theme' => 'links__node',
    '#pre_render' => array('drupal_pre_render_links'),
    '#attributes' => array('class' => array('links', 'inline')),
  );

  if (!$is_in_preview) {
    $entity = Node::load($node_entity_id)->getTranslation($langcode);
    $links['node'] = static::buildLinks($entity, $view_mode);

    // Allow other modules to alter the node links.
    $hook_context = array(
      'view_mode' => $view_mode,
      'langcode' => $langcode,
    );
    \Drupal::moduleHandler()->alter('node_links', $links, $entity, $hook_context);
  }
  return $links;

To know if a plugin is involved, you need to read the documentation. Plugin API in Drupal 8 give the general documentation, but then you need to read more specific documentation pages, for example Block API in Drupal 8.
A plugin could be annotated, so in some cases you can find any plugin implemented by Drupal core by looking at the classes annotated with a specific class, which is what happens with form input elements, which are classes annotated with \Drupal\Core\Render\Annotation\FormElement. The documentation page gives a list of the classes annotated with that Annotation class, so you can find any plugins of that type.

Then, as @CLive said, if you are simply wondering if you should use a hook, just look at the documentation page for that hook: If it has been deprecated, the documentation reports that, and tells you exactly what you should use: a different hook, a plugin, a specific class.
Also, as said from @mradcliffe, change records reports the changes done in Drupal, and for which version. They are helpful if you want to look at the changes that could interest the code you are writing.


Easiest way to add an existing site to a Drupal 6 multisite setup?

Not a complete guide, but here are some hints.

In general, modules aren't a problem, Drupal can deal with it if you move them around. Just do a cache clear after moving them and Drupal will go out and look for the enabled modules in all possible places (mainly sites/all/modules and sites/yoursite/modules). Make sure that you have no hardcoded path in your modules (contrib modules probably don't, but maybe custom ones), always use drupal_get_path() and similar functions.
You can do a big part of the multi-site conversion in your existing site, just rename the default folder to yoursite.com. Note that you need to execute drush commands within that order or use the -l argument from then on, if you use drush.
You probably want to move modules from sites/all/modules to sites/yoursite.com/modules in a first step (see first point). The existing site will probably have modules in sites/all/modules, you can then download them to your local site. Note that modules in sites/yoursite.com/modules override those in sites/all/modules. Then, figure out which modules are common, note that downgrades aren't possible, if you used a newer version of a module, you either need to keep it or upgrade the one in sites/all/modules. Make sure to properly test the changes (your site and the existing multi-sites, if you change anything in  sites/all/modules). Same game for themes.
The main issue will probably be file links in the files table, which you will need to change if your previous public path was in sites/default/files. If you already do the multi-site switch locally, you can again do and test this locally. Luckily, this has improved in D7, which doesnt't store the actual file path but something like public://the_file.jpg.
It is possible to share some tables, for example the users table, by having a single database for all sites and use a common prefix for some tables and a different one for others. If that's the case, you're in for some work (as you will need to rename all separated tables and merge the content of the shared ones). But it should be doable.
If you have hardcoded path's in your nodes and other content, you'll probably need to update them manually. You might be able to write a script that does it, but that could be tricky, dependin on how the path looks exactly.


is it good idea to add js file for every page?

This question is borderline one, it's one of these topics where art meets science of software development.

Either way, drupal_add_js() should be avoided. Always favour #attached property, and if possible, add libraries, not single JS files.

For site-wide vs single page: you probably have some kind of JS and CSS aggregation enabled. Using different sets of files is wasteful - it means that for every page your client needs to download another aggregated file. Leaving the same set everywhere allows clients to use cached aggregated version - and this is (usually) the least time-consuming and least transfer-consuming way to go.

As Clive reminded, there are situations that are exceptional. Sometimes you need different versions of jQuery, or conflicting sets of libraries, and aggregating them can result in JS error, or create really big aggregated file. In situations like this you may not want to include all of them, or simply it might be impossible due to conflicts. Even then minimizing the number of "sets" is a good idea.

If you have a really big script used only on one rarely used subpage, some aggregation modules will allow you to exclude it from aggregation and always serve separately - a wise choice if you have 1kb of JS logic that you need in one place only, for example. This part is an art of profiling, not really knowledge and recipes.


How to combine two nodes based on common title in Views?

Are you using multiple taxonomy terms field to enable the Large, Medium,etc sizes?

On the Views when you click on that taxonomy field, is there a way to show all fields in one line combined instead of separating them? Then use the Rewriting options so that you display with something like this:

[title] - [Sizes]: [Price]

Not sure if it will work, but worth a try. Experiment with separating out the different tokens and combining them in the Rewriting option.

Oh, what Alex said might work too.


Block in node view showing but does not show up when rendering node in Views

You are mixing up full node (view mode) and single node (page, canonical URL). Blocks only get added to pages. In regions.
I'm not sure right now, but isn't there from core already a block reference field you can add to a node type? Use this. Or use the Block Field module. And then set your specific block as default value.
Alternatively you can use a pseudo field (a.k.a extra field) from a custom module to render your block. Has the advantage that it then can't be changed by editors.


It looks that there is no need to inject anything. Just use a "use" statement inside the class

class MyModuleService {
  use \Drupal\Core\StringTranslation\StringTranslationTrait;

  function a() {
    $this->t('should at least not complaint.');
  }
}


Programmatically delete a webform submission by sid without first loading it

You always need to load before delete, there is no "better" solution.

  I am affraid from affecting the performance of the website since the
  above handler will be executed a lot

Loading one entity at a time is no performance issue whatsoever.

$webform_submission = \Drupal\webform\Entity\WebformSubmission::load($sid);
// Check if submission is returned.
if (!empty($webform_submission)) {
  //Delete the Submission
  $webform_submission->delete();
}


What is the correct name to give to a taxonomy term page template file?

I use, for instance,

page--taxonomy--term--6.tpl.php

Make sure you clear the cache in Configuration > Performance > Clear all caches after creating your template.


Adding template suggestion for twig based on page and content type

Try this out:

/**
 * Implements hook_theme_suggestions_page_alter().
 */
function myModule_theme_suggestions_page_alter(&$suggestions, $variables) {
  $node = \Drupal::routeMatch()->getParameter('node');
  if ($node instanceof \Drupal\node\NodeInterface) {
    $suggestions[] = 'page__' . $node->bundle();
    $suggestions[] = 'page__node_' . $node->bundle();
  }
}


Returning a custom command via AjaxResponse

Indeed, one way to do this is to implement CommandInterface in a new class, as described here: https://www.mike-miles.com/blog/creating-ajax-callback-commands-drupal-8 . This method adds the new command to Druapl.AjaxCommands.

However, if it's not desirable to implement the interface, a similar thing can be done with the existing InvokeCommand that implements CommandInterface, as in the example here: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Ajax%21InvokeCommand.php/class/InvokeCommand/8.2.x

My minimalistic example:

Server-side (NULL can be some CSS selector instead):

$response->addCommand(new InvokeCommand(NULL, 'customRedirect', ['/']));

Client-side:

jQuery.fn.customRedirect = function(target) {
    if (something)
        location.replace(target);
    else
        do_something_else();
};


Display list of users with a specific role to guest users

Please check this setting, Also check the user permission.


Deactivating the internal path is technically route normalization by redirecting incoming requests, which in D8 is provided by the module Redirect:

  D8: Maintaining a canonical path and redirecting alternative URL's
  like non-aliased path, path without language prefixes and so on
  (Previously provided by Global redirect)

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


Creating Select Fields in a module with Drupal 7

Something like this should work:

// Create field definition
$field = field_info_field('field_my_select_field');
if (empty($field)) {
  $field = array(
    'active' => '1',
    'cardinality' => '1',
    'deleted' => '0',
    'entity_types' => array(),
    'field_name' => 'field_my_select_field',
    'foreign keys' => array(),
    'indexes' => array(
      'value' => array(
        0 => 'value',
      ),
    ),
    'module' => 'list',
    'settings' => array(
      'allowed_values' => array(
        'Yes' => 'Yes',
        'No' => 'No',
      ),
      'allowed_values_function' => '',
    ),
    'translatable' => '0',
    'type' => 'list_text',
  );

  $field = field_create_field($field);
  drupal_set_message('Created field_my_select_field');
}

// Create field instance on entity bundle
if(!field_info_instance('node', 'field_my_select_field', 'my_node_type')){
  $instance = array(
    'bundle' => 'terms',
    'default_value' => array(
      0 => array(
        'value' => 'Yes',
      ),
    ),
    'deleted' => '0',
    'description' => '',
    'display' => array(
      'default' => array(
        'label' => 'hidden',
        'module' => 'list',
        'settings' => array(),
        'type' => 'hidden',
        'weight' => '4',
      ),
    ),
    'entity_type' => 'node',
    'field_name' => 'field_my_select_field',
    'label' => 'My field label',
    'required' => 0,
    'settings' => array(),
    'widget' => array(
      'active' => 1,
      'module' => 'options',
      'settings' => array(),
      'type' => 'options_select',
      'weight' => '3',
    ),
  );
  field_create_instance($instance);
  drupal_set_message("Added field_my_select_field field to node");
}


$users = \Drupal\user\Entity\User::loadMultiple();
$field = $user->get('field_custom_field');
$value = $field->getString();


There are 4 different field types that contain a text

string
string_long
text
text_long

What long means should be obvious, the difference between string and text is that text has a format (like full_html or basic_html) while string is always plain text.

You are currently using string_long, it doesn't make sense to show a wyswiwyg editor for that, since it would always escape all HTML. Use text_long instead.


How to add Tags to images being uploaded?

You can use a combination of the modules File Entity and File Entity Inline. File Entity will allow you to add fields to different file types, including images, and File Entity Inline will display all those added fields after clicking "Upload" whenever a user creates or edits content.

In order to make this work with Multiupload Imagefield Widget, you will need to apply two patches, one patch to multiupload_imagefield_widget.module, and one patch to file_entity_inline.module.

These patches are simple enough that they can be applied manually.

First install the modules File Entity and File Entity Inline. Go to Structure > File types > Image > Manage field and add the Term Reference field you want and any other fields you desire for the Image file
Apply the patches. For the sake of convenience I'm pasting below the lines that need to be replaced.

In the directory where your drupal installation lives in the server, find the file multiupload_imagefield_widget.module, usually located under the path sites/all/modules/multiupload_imagefield_widget. Add the following lines at the very end of the file:

/**
 * Implements hook_file_entity_inline_widgets().
 */
function multiupload_imagefield_widget_file_entity_inline_widgets() {
  $widgets = array();
  $widgets['image_miw'] = array(
    'element_type' => 'mfw_managed_file',
  );
  return $widgets;
}

Save.

Then find the file file_entity_inline.module, usually in the path sites/all/modules/file_entity_inline/. Find the line:

if (empty($element['fid']['#value']) || !isset($element['#entity_type']) || !isset($element['#field_name'])) {

and replace it for:

if (empty($element['#value']['fid']) || !isset($element['#entity_type']) || !isset($element['#field_name'])) {

and find the line:

$file = !empty($element['#file']) ? $element['#file'] : file_load($element['fid']['#value']);

and replace it for:

$file = !empty($element['#file']) ? $element['#file'] : file_load($element['#value']['fid']);

Save.

Go back to your site, clear the cache. Then you should be good to go. Be sure to select Multiupload as the widget for the Image field. After selecting the files and clicking Upload, the page will show thumbnails for each file and whatever fields you have added to the image file entity in step 1.

ONE BIG CAVEAT: If you ever install an update or upgrade for either patched module, you will lose your patches, unless they are "committed" to the new module versions. The maintainers of both modules seem to be dragging their feet committing these patches. Multiupload Imagefield Widget has had two new versions without this patch being committed. File Entity Inline hasn't been updated in at least 3 years...


How do I enable users to have a browse button (by clicking on the image icon)so that they can upload a picture.

You need a  combination of the imce module and imce bridge module to do this

IMCE

  IMCE is an image/file uploader and browser that supports personal
  directories and quota.

IMCE BRIDGE

  Allows to use IMCE module with Wysiwyg module.


How do I hide render elements if a checkbox that controls a form #state is checked?

You are right, a 3rd party module is overkill for this! I often find myself using a small js file to spice up the #states behavior. You can pretty much even bybass #states totally with this mecanism, but hey. #states is the drupal way of doing things. That does not mean it can't be assisted with JQuery.

Here is a quick snippet of my current quick project that is a form in a webform using the techniques (#states + jQuery) to tweak many things in the ui depending on what options are selected. This code should be in a .js file, loaded in module by the module's .info file, or you can have it in a drupal_add_js call.

I left all in there so you can see how with jQuery you can control fieldsets, option boxes and most anything you can think of. Notice also if you fancy as a bonus you can integrate all the jquery native animation functions like fadeIn() fadeOut(). There are also examples of that in the code below.

(function ($) {  // Notice code is in a behavior, use your module name
  Drupal.behaviors.yourModuleNameHere = {
    attach: function (context, settings) {

  // On load hide stuff. This will be shown when options are selected.
  $('#webform-component-inscription--enfant-1').removeClass('collapsed');
  $('#webform-component-inscription--enfant-2').removeClass('collapsed');
  $('#webform-component-inscription--enfant-1').hide();
  $('#webform-component-inscription--enfant-2').hide();
  // $('.form-submit').hide();

  $('#webform-component-inscription--information-supplementaire').hide();
  $('#edit-submitted-inscription-nombre-denfants', context).change(function () {

    var selected_option = $(this).val();

    if(selected_option === "1"){
        $('#webform-component-inscription--enfant-1').removeClass('collapsed');
        $('#webform-component-inscription--enfant-1').fadeIn(800);
        $('#webform-component-inscription--enfant-2').fadeOut(800);
        $('.form-submit').fadeIn(800);
        $('#webform-component-inscription--information-supplementaire').fadeIn(1000);
    }
    else if(selected_option === "2"){
        $('#webform-component-inscription--enfant-1').fadeIn(800);
        $('#webform-component-inscription--enfant-2').fadeIn(1500);
        $('#webform-component-inscription--information-supplementaire').fadeIn(2200);

    } else {
          $('#webform-component-inscription--enfant-1').fadeOut(800);
          $('#webform-component-inscription--enfant-2').fadeOut(800);
          $('.form-submit').fadeOut(800);
          $('#webform-component-inscription--information-supplementaire').hide();
          console.log("in extra information.");
         // $('#webform-component-inscription--enfant-1').addClass('collapsed');
        //  $('#webform-component-inscription--enfant-2').addClass('collapsed');
        }
      });
    }
  };
}(jQuery));

Of course, this method I am using  only acts on the presentation layer, if the fields you want to act on needs to be validated,  a server-side call is probably needed anyways and your method is probably better in that case.


Clear input field after click without attach any external script

I doubt it, that would be re-inventing the wheel IMO...what you're describing is pretty much what jQuery is for. Consider this code, which is a basic representation of what you're trying to do:

$(function() {
  $('#some-element').bind('someEvent', function() {
    $('#some-other-element').val('');
  });
});

That's only 3 meaningful lines of code, and is so trivial that writing a function to wrap around it would be counter-intuitive. The resulting code would end up being equally or more verbose, and all it would do is basically pass parameters blindly to a jQuery function.

Don't forget if you want to invoke any Javascript at all you're going to need an external JS file (or at the very least inline code). I would suggest using the above 3 lines in that external/inline JS would be preferable to using any sort of wrapper function (even if one does exist).


loading templates of region within page.tpl regardless of blocks being present

First of all I think you should be sure you know the difference between regions and template variables. Second, there are different approaches to your question:

A) Custom region + block

You could indeed define a new region. This can be done in one of the two ways:

in your theme's .info file (best way) like this regions[regionname] = Region name
in the template.php file (haven't tried or felt the need to use this one)

After you defined your new region you can add blocks and content to it. You could just skip defining a new region and just add your block to the footer region or the region appropriate to your needs.

In your case your myTheme.info file would look something like this:

; $Id$
; @file: myTheme.info

regions[footertop] = Footer Top

output the region variable ($footertop)

/**
* @file page.tpl.php
* $footertop contains all the HTML content for that region
* and the blocks belonging to that region
*/
print $footertop;

.info file is cached in the database, so you need to clear the cache
add a new block: www.example.com/admin/build/block/add
add the block to the footertop region: www.example.com/admin/build/block/list/myTheme

When should you use this approach: when you have static content or/and just some snippets of text/html you want to add to your site. Remember to choose an appropriate input filter, otherwise some/all of your content might get filtered out.

Source: http://drupal.org/node/171224

B) Template variable

We want to define a new general variable available for all templates. Something like $content or $is_front. How do we do this: good old friend hook_theme :)

Create a new template file footertop.tpl.php and in it add the static data you want to add

/**
* Implementation of hook_theme()
* @file template.php - in your active theme
*/
function myTheme_theme(&$existing, $type, $theme, $path) {

  /*
  * If you are sub-theming another theme, like Zen,
  * you might need to do something like this
  * $hooks = zen_theme($existing, $type, $theme, $path);
  */

  $hooks['footertop'] = array(
    'template' => 'footertop',
    // 'arguments' => array(), // We could specify some arguments, useful when the content is not static
    // 'path' => $path . 'to/file' // This is also usefull if your template is in a subfolder
  );

  return $hooks;
}

/**
* Now we make our variable available to other templates
* file template.php - in your active theme
*/
function myTheme_preprocess_page (&$vars, $hook) {
  $vars['footertop'] = theme('footertop');
}

Now to add the variable in a template just do this:

/**
* @file e.g. page.tpl.php
*/

/* Some other code */

<?php print $footertop; ?>

/* Other code */

Source:

http://api.drupal.org/api/drupal/developer--hooks--core.php/function/hook_theme/6
http://drupal.org/theme-guide/6-7

Now if you want to be a pro with drupal theming or development you should get yourself a book on this matter. It helped me a lot when I was struggling to understand how Drupal theming works :) You'll defined find the right one for you.


Save node when content with reference to it is created

in rules (sorry the terminology is not exact) :

action : node save
condition : type = review
select the bussiness from the review
resave that business (you will have to force it probably)

or the same in a hook (node_api, operation save, nodetype review)

the best would probably be creating an agregated view end embedding that into your node (or attaching with a block, many possibilities)


Of course as soon as I posted this I figured an answer. This looks a little ugly, but I guess this is the way to go:

public function content() {
  $nodes = $this->getStudents();

  foreach ($nodes as $node) {
    $student = \Drupal::entityTypeManager()
      ->getViewBuilder('node')
      ->view($node);
    $students[] = render($student);
  }

  return [
    '#theme' => 'dashboard',
    '#students' => $students,
  ];
}

Basically, I'm looping through the list of nodes, getting the view builder on each, then calling the render function and adding it to a new array. I had stumbled on this earlier because I was using viewMultiple, which output another array...

If you have a cleaner implementation with viewMultiple let me know.


Yes there is no problem inserting code in a feature. I guess the con is that you do not need to introduce a new module.


Accessing field values in node--mycustomtype.tpl.php

To get a web-accessible URL for the file you need to use file_create_url() on the field's uri property. You can also make use of theme_image() so you don't have to write the HTML yourself:

$vars = array(
  'path' => file_create_url($content['field_headshot'][LANGUAGE_NONE][0]['uri']),
  'alt' => $title,
  'attributes' => array(
    'class' => array('speaker_headshot')
  )
);

$img = theme('image', $vars);

print $img;

Since this code will clutter up your template file you might want to consider putting in a preprocess function instead, something like:

function MYTHEME_preprocess_node(&$vars) {
  if ($vars['node']->type == 'headshot') {
    $items = field_get_items('node', $vars['node'], 'field_headshot');
    $image = array_shift($items);

    $image_vars = array(
      'path' => file_create_url($image['uri']),
      'alt' => $vars['title'],
      'attributes' => array(
        'class' => array('speaker_headshot')
      )
    );

    $vars['image'] = theme('image', $image_vars);
  }
}

Then in your template file you can just print $image; to get the HTML output.


Which hook to allow specific users to add/edit/view comments?

There is no hook to do this. One possibility that doesn't require editing of the comment module is to change the comment status of the node depending on the current user using hook_node_load:

function MyModule_node_load($nodes, $types) {
    global $user;
    foreach($nodes as $node) {
        if(!user_has_access_to_node($user, $node)) {
            $node->comment = COMMENT_NODE_HIDDEN;
        }
    }
}

The hook will be called after the one in comment module, and will prevent users from posting comments unless user_has_access_to_node returns true.

The implementation of user_has_access_to_node would simply check if the current user is in the list of users allowed to edit the viewed node.


Build a grid with time slots in multiple rooms

The bat module - https://www.drupal.org/project/bat would work for this use case without any custom code required.


How to prevent image files being duplicated while importing nodes with the Feeds module?

I found a solution to this. What you need to do is to install the Media Feeds module.

In your CSV file there is a column called e.g. image and reference the image using public://myimage.png.

Then in your mapping delete the original image mapping and create a new image mapping. When you do this you will have a new option for the image mapping.  Make sure you set the target configuration to "Source is exactly the filename".

No more duplicated images.


I'm not sure I'm understanding this well, but perhaps you could create a new Content Type that holds all the career information that's common to all campuses. Then create a Content Type for each campus that has an Entity Reference field with unlimited cardinality (meaning that it allows you to have references to an unlimited number of careers). You can then create Views of campuses OR of careers with a relationship to the other Content Type, which will allow you to display the other Content Type fields in your table or list of nodes.


It depends on what the enhancements you are making but the way I've done this same process before is to export the finished code improvements to a features module or other custom module from my dev site and use that to update the live site.

You mentioned a few examples:

"adding tags" -> you could export the improved taxonomy and then import it on the new site using a number of modules, ex. taxonomy_xml or taxonomy_csv
"making a better menu" -> the features module allows you to export your menu and import on other sites
"dynamic blocks" -> easiest to just code these in a custom module (probably the simplest kind of module to write) and enable on the new site


Here is the way I would approach your issue:

Prepare two IIS+MSSQL servers, Staging and Production
Do a fresh install on Staging
Use tool like Features, UUID, and data migration module of your choice to move configuration and data from Development to Staging
Tie loose ends on Staging
Copy Staging to Production
Replace my dev with something less unlike production


How to hide a sub level menu from being expanded?

In the Add/Edit menu_block options, you can specify the Maximum depth of the menu tree to 1.


Difference between $form_id and $form['#id']?

Next should make sense:

<form action="somepath" id="search-theme-form"> <!-- id = $form['#id'] -->
  <input type="hidden" name="form_id" id="edit-search-theme-form" value="search_theme_form"/> <!-- value = $form_id -->
</form>

Terms:

#form['#id'] = store html form attribute id:

  Used to populate form elements' id property. In rare cases,
  you can set this value yourself on a form element, to override the
  default setting.

$form_id - point to Drupal form function name, in html it's form hidden element:

  The unique string identifying the desired form. If a function with
  that name exists, it is called to build the form array.


change field value in a view using preprocess_views_view_fields

You are probably not accessing the fields array correctly, and creating your own additional renderable array within $vars.

Install the Devel module if you haven't already and put

dpm($vars);

at the top of your function.  That will allow you to view the structure of the object on the screen (make sure you're logged in as user 1).


You cannot change order id as other functionalities are dependent on it.But you can change order number before saving order to shopping cart status by using  hook_commerce_order_presave($order).

function example_commerce_order_presave($order) {
   if ($order->status == 'cart') {
   $order->order_number = 'new order number;
   commerce_order_save($order);
   }
 }


requesting suggestions on using core poll module

You can try Decisions module in your site. This module depends on VotingAPI module. This module have some nice features. I havent tested much but its good module to look at. Good Luck.


Use drush to install it.

In case that don't work, try installing only BigPipe module to see if it is really a Core(experimental) modules problem or it's just some modules that are problematic and still need more development for drupal8 application.
As it is written here the only stable experimental module is BigPipe.


How to use views filter on an entity property

I have now done some experimentation and find that yes, what I needed to do was use hook_views_data_alter to tell views how to handle the properties I had added above.  Here is the code inside my hook_views_data_alter function:

$data['crm_core_contact']['notes'] = array(
            'title' => t('Notes'),
            'help' => t('The notes for the contact'),
         // Information for displaying the notes field
                'field' => array(
            'handler' => 'views_handler_field',
            'click sortable' => TRUE,
  ),

    // Information for accepting a note as a filter
        'filter' => array(
        'handler' => 'views_handler_filter_string',
  ),
    // Information for sorting on a note.
        'sort' => array(
        'handler' => 'views_handler_sort',
  ),
);


How to make filter that can find users by location of each other in miles or kilometers?

IP Geolocation Views and Maps looks like what you are looking for. It can obtain user's location, and it integrates with Views using Views PHP as it's connector.


You can probably use OpenLayers, with MapBox to create custom map layers with MapBox.com


I found the solution myself, with the following code.

// Get all languages of the site
$languages = \Drupal::languageManager()->getLanguages();

// Route of contact for example:
$route = 'contact.site_page';
foreach ($languages as $language) {
  $url = new Url($route, [], ['language' => $language]);
  $uri = $url->toString();
}


How can I add a header and footer field to all drupal generated blocks?

You can use block.tpl.php

  Default theme implementation to display a block

And add html in the same template file.


I think you are looking for User Stats module.

  Provides commonly requested user statistics for themers, IP address
  tracking and Views integration. Statistics are:

  days registered;
  join date;
  days since last login;
  days since last post;
  post count;
  login count;
  user online/offline;
  IP address;


Prevent a "default value" checkbox being created with entity?

I am sure there are other (better )ways but the way i got around this issue, which fundamentally was about not having the default turn up in my views further down the line, was to implement a hook on hook_views_pre_view and show/hide the fields as i wanted:

function mymod_views_pre_view(ViewExecutable $view, $display_id, array &$args)
{
  ...
  $fields[$field_name]['exclude'] = TRUE;
}

worked for me hope it helps someone else.


Writing to a specific or new element in a multi-value custom field

You're nearly spot on, the only problem is whatever field array you put in $edit will overwrite the array that's in there now; no merging happens behind the scenes. This is probably the correct behaviour as you should be able to overwrite the field completely if you need to.

At the moment each time you use

$edit['field_key'][LANGUAGE_NONE][]['value'] = $key_save;
user_save($account, $edit);

The field is being re-initialised as whatever's in $edit['field_key'], i.e. a single element.

To append to the array you could do something like this:

$field_items = $account->field_key;
if (!is_array($field_items)) {
  $field_items = array();
}

$field_items[LANGUAGE_NONE][]['value'] = $key_save;
user_save($account, array('field_key' => $field_items));


How to customize the add-to-cart form using hook_form_alter?

You can use this snippet to customize the add to cart form:

/**
 * Implements hook_form_alter()
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if (strpos($form_id, 'commerce_cart_add_to_cart_form_') === 0) {
    // Your form modifications go here.
  }
}

The $form_id changes based on the product that is in it, so you have to check for the string at the beginning of the $form_id variable.

You can theme it and/or change markup in the form like you would a regular form.


Multi-site variables table for shared variables (extending variable_set)

Reading is possible, but may be costly

Code for variable_get() is:

function variable_get($name, $default = NULL) {
  global $conf;
  return isset($conf[$name]) ? $conf[$name] : $default;
}

So you need to set:

global $conf;
$conf['shared_variable'] = your_function_to_obtain('shared_variable');

Where to put it?

If your function uses other site variables, including ones provided via UI, best place seems to be a hook_boot(). You need to make sure your hook_boot() is called first. To get your module to run first, use hook_module_implements_alter() or easier and less reliable way - Modules weight module.

If you don't use any values provided via UI, you can (maybe should) put it in settings.php instead. You don't need to use global in settings.php.

Writing is way more trickier

Code for variable set() is:

function variable_set($name, $value) {
  global $conf;

  db_merge('variable')->key(array('name' => $name))->fields(array('value' => serialize($value)))->execute();

  cache_clear_all('variables', 'cache_bootstrap');

  $conf[$name] = $value;
}

As you can see, there are no hook calls, nothing. It just saves data altogether. variable_del() shares that problem.

What you can do is to override very forms, providing your own save handler that will copy data to shared table. This will not solve the issue of saves and deletes outside form submits, if they happen in module in question. Other approach would be to use triggers directly in RDBMS to synchronize tables - more reliable, but harder to maintain.

Advanced PHP debugger

A bit hardcore approach is to override built-in functions. Yes, you can do it without touching core.

You need PECL apd >= 0.2

In your settings.php (or in your module's *.inc, but include in settings.php) implement override_function($function_name, $function_args, $function_code) for variable_del and variable_set. Do not attempt this for reads, unless you want huge performance hit.


Use "Global: PHP" field to get the required parameter value. If views_php is not installed, then use this link, views_php to install the module and give the permission using admin/people/permissions.

Go to your Views -> CONTEXTUAL FILTERS -> ADD -> Select "Global: PHP" then you can retrieve the parameter using $_SERVER[QUERY_STRING] and retrieve the value.

And also you can use $_GET['nid'] to get the value.


It's quite possible to do. But there may be some cases where you need to do some custom code. That also totally depends on your business requirement.

However, please follow this one How to set different languages for different domains, and display the language switcher accordingly?

In Drupal 7 Domain Access module is the best one to make multi domain sites. This has a helper module called Domain Locale which is what you need I guess from the question asked.


How to integrate with the jQuery Mobile framework?

There are currently people working on an integration of jQuery Mobile and Drupal.

Take a look at the jQuery Mobile module and the jQM Theme.  They are both currently only in dev, but I don't think there is much else out there yet.  If you prefer you could always do the integration yourself and use the basic Mobile theme.

The creators of this module and theme also have a video from Drupalcon Chicago that was very interesting: Drupal on the go with jQuery Mobile


After hunting through notify.module, I saw what the issue was.

The line that the error was occuring at was:

foreach ($res_nopub as $row) {
  db_query('DELETE FROM {notify_unpublished_queue} WHERE cid = :cid AND nid = :nid', array(':cid' => 0, ':nid' => $row->nid));
}

The array $res_nopub is constructed by the function _notify_select_content by:

// Get published nodes in unpublished queue
$res_nopub = db_query('SELECT q.nid
FROM {notify_unpublished_queue} q
INNER JOIN {node} n
ON q.nid = n.nid
WHERE q.cid = :cid AND n.status = :status
ORDER BY q.nid asc',
array(':cid' => 0, ':status' => NODE_PUBLISHED));

The issue that occurred was that the only node within the queue of notifications was an unpublished page. There were no published pages within the unpublished table, and the unpublished table was not empty. Because of this, the array $res_nopub is constructed, but is empty. This throws an error at line 956 due to attempting to iterate over an empty array with a for each.

I fixed this error by first checking the length of the array at line 956 before iterating.

if (sizeof($res_nopub) > 0)//check size of array before iterating
{
    foreach ($res_nopub as $row) {
      db_query('DELETE FROM {notify_unpublished_queue} WHERE cid = :cid AND nid = :nid', array(':cid' => 0, ':nid' => $row->nid));
    }
}

I've tested this very simple fix and yes, it does work.


Custom date range format on a node by node basis

You just need to add template_preprocess_node(&$vars) to your template.php and check the value of checkbox that is controlling the date format

Date object store start date as value key and end date as value2 key. You need to check on that.

if($checkbox) //checked
  //display one format
else
  // display another format

You can use php date api functions to format your date


How to solve Bootstrap Theme settings override problem?

I solved this problem by disabling the ModSecurity on cPanel.

  ModSecurity is an Apache module that applies a set of rules to the activities of software run on Apache. It is used by some hosting environments to assure security, but some rules can interfere with the normal operation of Drupal.


Drupal content slider like ImageFlow and GalleryFormatter

Views slideshow will do the job for you:

  Views Slideshow can be used to create a slideshow of any content (not
  just images) that can appear in a View. Powered by jQuery, it is
  heavily customizable: you may choose slideshow settings for each View
  you create.


How to add separator field to user profile

Option 1:
Add one contact field that has cardinality 3 and stores the name, email and address.

Option 2:
Alter the form and put name, email and address in one fieldset.


Why is hook_menu_local_tasks_alter called twice?

If you are familiar with the command line, you can use the following command to return file names and line numbers where this hook is being called.

For example, change directories into your /sites/all/modules directory or other module directory and run,

(assuming your are using mac or linux)

$grep "menu_local_tasks" * -rn

or as Clive has it below.

$grep "drupal_alter(\'menu_local_tasks\'" * -rn

*Note, the backslashes escape the single quotes.

Jason.


How to display items in Rules data selector in alphabetical order

This is not an answer in any way, but

on around line 150 of rules.autocomplete.js, there is this code..

  Drupal.rules.autocomplete.prototype.success = function(data, request, response) {
    var list = new Array();
    jQuery.each(data, function(index, value) {
      list.push( {
        label: value,
        value: index
      });
    });

    this.cache[request.term] = list;
    response(list);
  };

That could possibly be where you need to add some code to rearrange the list. It might be there or it might be elsewhere.. It's a huge module.

If you manage it, create a patch for yourself that can be applied each time the module is updated.


How to define an image style where images are the exact same dimensions (e.g. grid of square images), without cropping or distorting the image?

If you don't mind applying a block background colour, this seems to be possible with Imagecache Actions module.

Download and enable the Imagecache Actions module and its imagecache_canvasactions submodule.
Add a normal "scale" action to the desired size (300 x 300). This keeps the aspect ratio.
After, add a "Define canvas" action, then set to the same dimensions under "exact size".
Make sure "Resize canvas under image" is ticked, choose an appropriate background colour, and go. This fills in any gaps to the desired size with whatever colour you choose (or transparency if you choose no colour).


A simple solution is to override the default content list or to create an alternative one using Views and VBO.

With views it's easy to create sortable tables. I believe a view of the content listing is already predefined in either VBO or Views.


Drupal 6 - Theme custom search form results

Whatever u have done so far is correct. Only thing left now is to render the content from ur preprocess 'rootcandy_preprocess_rootcandy_my_search_results' to ur 'rootcandy-my-search-results.tpl.php'. U have to start debugging in this way.

Check ur $vars['form'] contains ur form values in  'rootcandy_preprocess_rootcandy_my_search_results'
create a variable in preprocess and try using it in ur rootcandy-my-search-results.tpl.php.
Eg: $vars['testing'] = "this is to confirm that variable is working in rootcandy-my-search-results.tpl.php"
if you print $testing in ur rootcandy-my-search-results.tpl.php and it gives "this is to confirm that variable is working in rootcandy-my-search-results.tpl.php" Which means its working fine.
Then you can pass ur form results to the tpl file.
Eg: $vars['result'] = drupal_render($vars['form']['result']);

Try this. Ur first goal will be making sure u can get ur preprocess values in ur tpl file.


Drupal views - 2 latest reports and related content

You can create view in a view using View Field View (https://drupal.org/project/views_field_view):

Create a view of reports
Create a view of amendments which takes a contextual filter of node id and filters amendments which have a field reference with that node id value
Put the view amendments view in a view of reports as a field (using above mentioned module - see it's documentation for more specific info if necessary)

Btw. just a thought - isn't it possible for you to switch the architecture and have the node reference field in the document content type, referencing the amendments? - this way you wouldn't need a view in a view and it would be easier to display it.


How do I redirect users to the page they were before logging in to my site?

Have a look at the Login Destination module.

In custom code, to issue a redirect in Drupal use the drupal_goto() function. Drupal has a massive API, use it.


Paragraph image URI with image styles in paragraphs-item.tpl

Probably your best bet is to have something along the following in the 'paragraph--ptype.tpl.php' file:

<?php print theme('image_style', array('style_name' => 'size_400x600', 'path' => $field_image['und'][0]['uri'])); ?>
<?php print theme('image_style', array('style_name' => 'size_750x524', 'path' => $field_image['und'][1]['uri'])); ?>
<?php print theme('image_style', array('style_name' => 'size_550x365', 'path' => $field_image['und'][2]['uri'])); ?>

Where ptype is obviously the paragraph type that has this field.

I originally answered for Drupal 8 because I missed the D7 tag. Doh! I'm leaving the original answer below for reference.

First, a good way to apply an image style in an image field template:

{% for item in items %}
  {{ item.content|merge({'#image_style': 'size_400x600'}) }}
{% endfor %}

For your use case, you could do something like:

{% for item in items %}
  {% set style = 'size_400x600' %}
  {% if loop.index0 == 1 %}
    {% set style = 'size_750x524' %}
  {% elseif loop.index0 == 2 %}
    {% set style = 'size_550x365' %}
  {% endif %}
  {{ item.content|merge({'#image_style': style}) }}
{% endfor %}

However, since the twig code is starting to get complicated, you should probably think about handling it in a preprocess function.

Alternatively, you can do some of this at the paragraph template level (assuming the image field is on the paragraph):

{% if not paragraph.field_image.isEmpty() %}
  {% if not paragraph.field_image[0].entity.uri.isEmpty() %}
    {% set img_url = paragraph.field_image[0].entity.uri.value | image_style('size_400x600') %}

  {% elseif not paragraph.field_image[1].entity.uri.isEmpty() %}
    {% set img_url = paragraph.field_image[1].entity.uri.value | image_style('size_750x524') %}

  {% elseif not paragraph.field_image[2].entity.uri.isEmpty() %}
    {% set img_url = paragraph.field_image[2].entity.uri.value | image_style('size_550x365') %}

  {% endif %}
{% endif %}

You will need the twig_tweak module for that. Some of the safety checks in there may be extraneous. YMMV. As before, the complex twig code means this would be good to put into a preprocess function.


hook_views_pre_render -> how to access variables

Install the Devel module if you haven't already and use dpm($view); to see the structure of the view, then you can drill down to the part of the variable that you wish to inspect.

The devel module will print the result of your dpm() in the message area as long as there are no syntax errors in your module crashing the site.

I have found drush cc all (Linux command line tool) to be useful in finding syntax errors though I suspect there is a better way.


Stop Advanced Forum cutting off the username?

It seems Drupal core truncates the username to 25 characters. I have not tried this but this seems to be the solution for Drupal 7 (code added below for reference).

function MYTHEME_preprocess_username(&$vars) {

  // Update the username so it's the full name of the user.
  $account = $vars['account'];

  // Revise the name trimming done in template_preprocess_username.
  $name = $vars['name_raw'] = format_username($account);

  // Trim the altered name as core does, but with a higher character limit.
  if (drupal_strlen($name) > 25) {
    $name = drupal_substr($name, 0, 20) . '...';
  }

  // Assign the altered name to $vars['name'].
  $vars['name'] = check_plain($name);

}

Add this code in your theme's template.php file, and change MYTHEME to the machine name of your theme, and change the number 25 to something that fits your theme.


Secure Pages Module or force HTTPS Across Whole Site?

Frankly, I bypassed Secure Pages and just forced all traffic to be HTTPS via htaccess. I prefer all traffic to be forced HTTPS.

SecurePages generally works up front, but I have seen a lot of wacky behavior with it that I just don't bother anymore.


using Feeds Xpath Parser to import RSS feeds

You have to fully understand the XPath queries logic to use the parser. It's very powerful once you get it, but it needs a bit of practice.

Here is a good starting page : http://www.w3schools.com/xpath/

Note that you have two parts in the UI for the queries :

One to set the context, which is the element all further queries will be run from
One for each field

The context element depends on your document and the logic of the data inside. Usually, you set the context each 'entity' or node is saved in, and then query fields or attributes for the different fields.

For example, if you have a 'Thing' entity like this :

<Thing>
<id>1</id>
<name>Name One</name>
</Thing>
<Thing>
<id>2</id>
<name>Name Two</name>
</Thing>

... you would set the context to /Thing and then each field query to name and id. You also have a syntax to query attributes.

Also, be aware Feeds is only compatible with XPath 1.0 syntax.


How to uninstall the Service links module?

As far as I can see, Service Links 7.x-2.1 does not create tables of its own and the uninstall hook only deletes some configuration variables.

If you can't see the module in the uninstall tabs then you have probably deleted the module's folder before uninstalling. If this is the case, you can restore the module's folder and then uninstall the module (no need to enable it again).

Or you can run DELETE FROM variable WHERE name LIKE 'service_links_%' to your database.


How to modify existing language's language code?

I'm not sure if this will work, so BACK UP YOUR DATABASE FIRST, but I think that you should be able to run the following query to change fix it:

Let's say for example you were wanting to use Japanese. The language code is 'ja', but people often mistake it as 'jp'. If this was your case, and you wanted to change 'jp' => 'ja', you can run the following query:

UPDATE locales_target SET language = 'ja' WHERE language = 'jp'

Then clear your cache.

If this doesn't work, return your database to its previous state using the backup you took at the start (because you took a backup, right?!)


Change system mail on run time when sending mail

You can alter the mail using hook_mail_alter(&$message)

  Alter an email message created with MailManagerInterface->mail().

with in message array you have 'from' field as well.

Example

function mymodule_mail_alter(&$message) {
  if ($message['id'] == 'modulename_messagekey') {
    // Login to get domain specific email id.
    $email_id == _some_logic_to_get_email();
    $message['from'] = $email_id;
  }
}

Refernce: https://api.drupal.org/api/drupal/core%21core.api.php/function/hook_mail_alter/8.2.x


Entity Print Content Modification For Views

I don't think that your template suggestion is correct in this case, so {{content.field_bright_news}} may not work.
A few things I can clarify for you are as follows:
{{content.field_bright_news}} - this variable is only available in the template of the content type containing that field, it cannot be used in the view template.
For your quote, it is missing the following:

By default this module only installs the PDF view mode for Nodes. If you have any custom entities on your Drupal site and want to hide the "View PDF" link on those, you must first create a PDF view mode for the entity type. To do this navigate to "admin / structure / display-modes / view" and click on "Add view mode". In the list click the entity type for which you would like to create the PDF view mode. You'll now be asked to name the view mode, you can name it whatever you like but make sure the machine name is just "pdf", which will be automatically prefixed with the entity name. You can now follow the steps in the previous paragraphs for your custom entity.

That is, you must create a display mode for that content type to have a template suggesting as the form
node--content_type--display_mode.html.twig
And that means, {{content.field_bright_news}} can be used in the template suggested above.


new version of XML Sitemap module helped me.

  The XML sitemap module creates a sitemap that conforms to the
  sitemaps.org specification. This helps search engines to more
  intelligently crawl a website and keep their results up to date. The
  sitemap created by the module can be automatically submitted to Ask,
  Google, Bing (formerly Windows Live Search), and Yahoo! search
  engines. The module also comes with several submodules that can add
  sitemap links for content, menu items, taxonomy terms, and user
  profiles.


How to force initial imported node to not have draft status using feeds?

Even though this question is related to the Workflow module, the solution you're looking for should come from the Feeds and/or Rules module, as further explained in my answer below.
1st attempt: Feeds Rules module
The Feeds Rules module might be what you are looking for. Excerpt from its project page:

... provides some Rules integration for the Feeds module.
It provides:

Feeds processor: a processor for Feeds to create content via Rules. (Currently only simple data types like text and integer are supported).
Rules Event: Feeds After Import
Rules Data: Feeds Source (properties: ID, imported)

Recommendation: this might work, however there is only a dev version available for this module ... my advice = no go.
2nd attempt: Native Feeds module
The Feeds issue about Rules integration & enable modules to customize imports adds a hook hook_feeds_before_import(). Here are some quotes from that issue (bold markup added here):

... such that a rules integration could use it to customize the imported entities before saving + to skip saving.
Based on the hook we could add an event for it + an action for skipping the import. The entity could be manipulated with the usual rules actions else too.

Of course, in the question here the goal is to not skip saving. But instead "customize the imported entities before saving" and/or "manipulate the entity with the usual rules actions". More specifically: set the value of "state" to "Saved".
Recommendation: much better already, but it is not exactly right yet (and requires using a hook, i.e. writing some custom module) ... There has to be a Rules based solution ...
3rd (and Final) attempt: A rule that should do the job
Inspired (challenged) by the "I tried adding a rule upon feeds presave, but it never gets to the save since it is a draft" part of this question, I created a rule. Here is the export that rule, which I believe should be a perfect answer to the question (also because it doesn't require custom PHP code ...):
{ "rules_update_entity_after_import_via_feeds" : {
    "LABEL" : "Update field imported via feeds",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "workflow_rules", "feeds" ],
    "ON" : { "feeds_import_node" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_workflow_status" } }
    ],
    "DO" : [
      { "workflowfield_field_set_state" : {
          "node" : [ "node" ],
          "field" : [ "node:field-workflow-status" ],
          "workflow_state" : { "value" : { "3" : "3" } }
        }
      }
    ]
  }
}

To get this to work, I enabled the Workflow API module (of course ...), and also it's submodules  Workflow UI,  Workflow Field and Workflow Rules.
My Workflow itself has only status "Draft" and "Done" (identical to the question here).
The rule above only applies to "node", and only for those "nodes" that have a field defined with machine name "field_workflow_status" (if you want to use another field name, change the rule accordingly and it should work also ...). In my case I used "Article" as the content type, though the "entity_has_field" prevented that I had to hardcode the content type in my rule ...
Obviously, and to be complete, Feeds and Rules are also part of the solution.


How can I force a user to submit webform before viewing certain pages?

Your best bet is to use this the splasify module: https://drupal.org/project/splashify

As for popping it up only once, you'll have to set a cookie somehow to track that it has popped up already. It might be suppored in that module already.


Pathauto can't do this, it can only generate aliases to the default view mode.

You can write your own Pathauto module, which generates for each view mode a separate aliases. For a single purpose module there is not much work to do, you only need to generate the aliases and use

\Drupal::service('path.alias_storage')->save($source, $alias);

to save them.

The problem is, you get a very large url_alias table.

Or use route_callbacks: in *.routing.yml, then define in this callback for each view mode a different route, which calls a Controller, which then in case you have a hit on the route will look up the middle part of the alias and return a redirect to the node in the requested view mode. This is without the static alias table, but may take longer for each request.


You need to add the following rewrite in your Drupal .htaccess

RewriteCond %{REQUEST_URI} !/APP-FOLDER-NAME/.*

Then in the root of the angular application folder you need the following in your .htaccess

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]

RewriteRule ^(.*) /APP-FOLDER-NAME/index.html [NC,L]


First of all, I hope you didn't edit any files in core :)
Secondly, you can of course add the custom scripts in the HTML twig file, but you need to add this template to you active theme and clear theme registry (or all) cache in order for the changes to appear.

Here is a complete html.html.twig file code:

{#
/**
 * @file
 * Default theme implementation for the basic structure of a single Drupal page.
 *
 * Variables:
 * - logged_in: A flag indicating if user is logged in.
 * - root_path: The root path of the current page (e.g., node, admin, user).
 * - node_type: The content type for the current node, if the page is a node.
 * - head_title: List of text elements that make up the head_title variable.
 *   May contain or more of the following:
 *   - title: The title of the page.
 *   - name: The name of the site.
 *   - slogan: The slogan of the site.
 * - page_top: Initial rendered markup. This should be printed before 'page'.
 * - page: The rendered page markup.
 * - page_bottom: Closing rendered markup. This variable should be printed after
 *   'page'.
 * - db_offline: A flag indicating if the database is offline.
 * - placeholder_token: The token for generating head, css, js and js-bottom
 *   placeholders.
 *
 * @see template_preprocess_html()
 *
 * @ingroup themeable
 */
#}
<!DOCTYPE html>

    <title>{{ head_title|safe_join(' | ') }}</title>
    <css-placeholder token="{{ placeholder_token|raw }}">
    <js-placeholder token="{{ placeholder_token|raw }}">

    {#
      Keyboard navigation/accessibility link to main content section in
      page.html.twig.
    #}

      {{ 'Skip to main content'|t }}

    {{ page_top }}
    {{ page }}
    {{ page_bottom }}
    <js-bottom-placeholder token="{{ placeholder_token|raw }}">

    Positive SSL Wildcard

You can put this file in your active theme /templates folder, clear cache and it'll load the logo on every page.
There are other ways to do so like using custom module to inject the code, but for simplicity, you can use this solution.


Drupal Calendar, why some events appear as "all day" events even if they are not "all day" events?

This is probably an old "bug" in calendar: https://drupal.org/node/881224
Have you tried to give your dates an end date?


is it a security hole to verify an uploaded supposed-to-be-zip file as a zip with zip_open()?

That seems reasonable to me. I would probably place the file in a temporary directory first and then use zip_open on it in that location.

You may also be able to use OS level commands (which come with their own risks) to verify the integrity of the file without actually unzipping it.

Are you going to store the zip files as zip files after being uploaded? Doing so presents additional issues since zips can be used to contain lots of files that may or may not be appropriate. You may want to get a list of the contents of the file to automatically include in your field so people downloading them will know if the file contents are valid. You could also integrate with something like http://drupal.org/project/clamav to scan all the files that are uploaded.


How to set an action to unpublish a comment with rules?

If you choose the action "Set a data value" and a comment is visible to the action (e.g. because the triggering event is "After saving a new comment") then the data selector will let you choose

comment:status

which you can then choose to set to "Published" or "Unpublished", or (via a data selection) to another available value.


Get a particular module's information programmatically

No - as you've already discovered, the association is the other way around (i.e. a list of modules against each hook, not a list of hooks against each module). Nothing in Drupal's core needs to know a list of all hooks a module implements, so no such function exists. As there's no requirement for a module to declare which hooks it provides (though they can through hook_hook_info()), such a function would be difficult or impossible to implement reliably.

If you can trust that all the modules you have installed are well documented, you could write something that looks in the comment block of each function for Implements hook_, and build a list yourself that way. Or you could compile a list of all the hooks you're interested in knowing about, run each of them through module_implements, and build your list.
Assuming by "menu link" you mean a path provided by a module that has the default menu type, and will subsequently appear in a menu automatically, something like this will do it for all modules:

$menu_items = array();
foreach (module_implements('menu') as $module) {
  $func = $module . '_menu';
  if (function_exists($func)) {
    foreach ($func() as $router_path => $item) {
      if ($item['type'] == MENU_NORMAL_ITEM) {
        $menu_items[$module][$router_path] = $item['title'];
      }
    }
  }
}

That will probably need to be be tweaked for your requirements.


View Mode not showing up under Manage Display

Writing out my comment as an answer.

This apparently needs a manual cache clear right now to work.


I've found that Drupal 6 views dont support such feature.

The solution was to implement the module_views_query_substitutions hook and alter the query manually:

function module_views_query_substitutions($view)
{
    $view->query->where[0]['clauses'][3] =
        str_replace('=', '>=', $view->query->where[0]['clauses'][3]);
}


Take a look this link: token.inc
What you need is to create a module that implements hook_tokens and hook_token_info.


What methods are there to load more ROWS into a View display without reloading the page?

The Views Infinite Scroll module is an alternative solution for ajax pagers in views however I haven't used it so I cannot comment on how well it works.

It also works a little differently to views load more so it may or may not meed your requirements.