Menu on mobile phone - How to directly show second level of menu?

You can force the desired behavior via CSS or via Javascript (jQuery). For instance, check with jQuery if main menu is displayed on mobile. If so, then display its children, too. The CSS way would work if "main menu" is displayed by adding a class. If so, then you can, from CSS, display the second level when that class is present.


How can I handle restricted items on a Drupal Commerce site with special display and checkout rules?

So found that I was mostly in uncharted water on this but I waded through and I am mostly done building, so I will explain how I did it for the next guy.

I used quite a few modules, including a few custom modules...

Commerce wishlist was used as a template to create two custom modules 'request a quote' and 'request a sample'.` They are essentially extra carts with custom actions.

Another custom modules was used to alter/disable parts of the commerce line item based on CCK field values. It will also be responsible for altering the checkout process/adding safety coniditions when I get around to that.

Taxonomy maintains a multi-dimensional product hierarchy. Tokens, Url Aliases and Views with 'global exposed filter' + views_php create the catalog. Views are embedded into tpl files and passed arguments programmatically from node properties in lue of using product references (I needed more customization/arguments) than they offered.

The answer in short to building most of my problems was to be very Drupal-y about it and ignore a lot of the out of the box functionality of commerce...Aka: Take the views hammer to it!

That's about it. Good luck future Drupal Commerce dev!


Comments with Facebook Auth User and anonymous

You could try the disqus module, which uses the disqus service.

It is arguably better than using facebook comments because it also allows people to comment using other social network accounts, not just facebook.

It also allows guest commenting.

Depends on your requirements though as to whether or not that is an acceptable solution.


Field groups are configurations which are not translated via the translation interface. I am quite sure that the string "Account settings" that is translated in your project does not come from your field group. Just change the label of a field group to any other string - you will not find the string in the translation interface.
You need to activate the "Configuration Translation" module.


How can I send html email notifications with entityforms?

Here some more detailed guidance on how to solve this:

HTML EMAILS

You will need to download and set up Mime Mail.

The latest version of Entity Form (currently 7.x-2.0-rc1) comes with it's own preconfigured rules. You'll need the Entity Rules module for these. You can clone or edit these.

Alternatively you can set up your own fresh rules in the 'normal' way by using the 'After saving a new entityform submission' event.

Whichever method you go for you will need to add the 'Send HTML e-mail' element to the Actions stage of the rule (you can remove the existing actions if you cloned the packaged entity rules).

You can configure KEY, TO, CC, BCC, SENDER NAME, SENDER E-MAIL ADDRESS, REPLY E-MAIL ADDRESS, SUBJECT, BODY, PLAIN TEXT BODY, ATTACHMENTS, LANGUAGE.

EMAIL FILE ATTACHMENTS:

A lot of people have trouble getting file attachments to work with Entity Forms.

To do this:

Edit the action and within the attachments section you can add a file path token, e.g.

[entity:THE_FILE_FIELD_NAME:file:path]

Check the Replacement Patterns for the field name and make sure you use 'file:path' as above and you will get an attachment on the HTML email.

Other file tokens include:

[entity:THE_FILE_FIELD_NAME:file]

[entity:THE_FILE_FIELD_NAME:file:url]

[entity:THE_FILE_FIELD_NAME:file:size]

You may wish to use these in the email body for example.

Here is a list of file tokens. There are other useful tokens listed on there too.


Okay, solved it.

I wasn't suppose to add the action under Components, rather I was suppose to add the action under Rules Scheduler > Schedule component evaluation.


Drupal Custom Search Results Per Content Type

Here's a sketch of an answer: in a views template for the result set you will have access to the original results in $view->result. If the view is set up for fields output, and includes all the fields required including content type, you can iterate through it 3 times, each time ignoring entries that have the content type you don't want for that case.

It's quite hard to come up with clean-looking code because of the way that views names the field data, but if you don't mind that, you can use the dpm() function of the Devel module to inspect it then code accordingly.


Add user email and username under the "View" tab at /user/%

You can always create a block through Views and display this information. Here's how to do that:

Create a new view, choose to show "Users" and create only a block.
Add "E-mail" field.
Add "Contextual filter" for the "User: Uid" field.
For filter configuration choose "Provide default value" and then "User ID from URL".
Show the block in content area, and configure it so it's displayed only on specific pages. Enter the aliased path you use for user profiles. For example: profile/*. This is necessary because the system URL for user profile pages is user/[uid], which you cannot distinguish from user/login, user/register and so on.

Do note that this will make the username/email available to everyone who has the permission to view user profiles.

Hope this helps.


How do I check the value of a field if its empty?

@vinhd proposition is correct, by the way you can also use the isEmpty() method from the field list interface. It can be more adapted for complex field types.
if ( $node->hasField('field_your_field') && !$node->get('field_your_field')->isEmpty() ) {
 //... do something
}


Show last node of every term in one Views

Create a view to show content
Add page display and set path setting to news/%
Add contextual filter "Has taxonomy term ID"
Add sort criteria "Authored on (desc)"
In pager settings check "Display a specified number of items" and set "Items per page" setting to 1.

Note that this will produce URLs with numeric term IDs (i.e. news/123).
To make use of term names you need to configure a relationship to the term so you get the information about the term into view, then use term name contextual filter.


If you wish to allow anonymous comments but remove the Homepage field, you can do so in either a custom module or theme function that implements hook_form_FORM_alter().

Via a theme function (source, mengi on drupal.org):

function THEME_form_comment_form_alter(&$form) {
  $form['author']['homepage']['#access'] = FALSE;
}

Or via a custom module:

function MYMODULE_form_comment_form_alter(&$form) {
  $form['author']['homepage']['#access'] = FALSE;
}

Note: Anonymous comments may be reasonable if you use other anti-spam measures such as honeypot fields and javascript-filled anti-spam fields.


How do I filter on day & month from a date field?

Maybe you could conjure up something with the Regular expression inside the Date Filter, but that is usually not a nice path.

I haven't tried it but maybe you can do it with Contextual Filters (Under Advanced settings in the third column in Views). There is a separate Contextual filter for month, and for day:

node.field_date (month) and node.field_date (day)

Configure them with Default values Current date.


Solution: Use a regular query instead of a EntityFieldQuery to load all entity revisions.

Explanation:

In the age function on entity.inc there's this comment:

  Blockquote
     * Note that this only affects field conditions. Property conditions always
     * apply to the current revision.

So as long as you provide a property condition, you will get only the last revision id. If you query with fieldCondition, you will get the revisions, as the age method is actually querying the field revision table and not the node revision one (field_sql_storage.module):

  else {
    $tablename_function = '_field_sql_storage_revision_tablename';
    $id_key = 'revision_id';
  }

Otherwise, the entity table is queried so it will always return the entities and not the revisions.

You could do a addTag and modify the query object there but at this point the modifications will be so big that it's actually better to do a regular query instead.

Example using generic info for the entity and entity api entity_revision_load.

  $entity_type = 'command';
  $value = 1;
  $entity_info = entity_get_info($entity_type);

  $query = db_select($entity_info['revision table'], 'revision');
  $query->fields('revision', array($entity_info['entity keys']['id'], $entity_info['entity keys']['revision']))
    ->condition('revision.' . $entity_info['entity keys']['id'], $value);
  $revisions = $query
    ->execute()
    ->fetchAllAssoc($entity_info['entity keys']['revision']);

  $entities = array();
  foreach ($revisions as $key => $revision) {
    $entities[] = entity_revision_load($entity_type, $key);
  }


Using triggers to add new user to a mailing list

I am not sure about how you've configured your environment but have you looked into this module? It appears to extend the rules a little bit.

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


Views api: how to create a 'conditional' join

I havent done this in Views 3, but try the following, adopted from Views2 blog post applied to your code:
http://www.agileapproach.com/blog-entry/views-2-table-aliases-and-extra-criteria

# I think you had typo in your join for table2 where
# you had as the final key 'table1'.
$data['table3']['table']['join']['table2'] = array(
  'left_table' => 'table2',
  'left_field' => 'id_2',
  'field' => 'id_2',
  'extra' => array(
      array('field' => 'type', 'value' => 'blah'),
    ),
);


Behavior being fired on backend causes AJAX error

Funny how sometimes you write out the question, and it makes you think about it in a different way!

The issue is that the behavior is obviously saved somewhere and called on an ajax event, EVEN if the js is not being called on that page! This was funny behavior to me, but the quick fix (maybe not the right fix) was to check the current path, and not run the JS inside that behavior if the path had "edit" in it.

Drupal.behaviors.myBehavior = {
  attach: function (context, settings) {
    (function($) {

        jQuery(document).ready(function() {

        var pathname = window.location.pathname;
            // If the page does NOT contain edit
            if (! (pathname.indexOf('edit') > -1) ) {

               // All of the JS stuff....

            }
        });

    }(jQuery));
  }
};

I will leave this question open for a few days as I would be interested to see if there's a better way of doing this. Ideally some way to control which behaviors are called on which pages?


It's hard to recommend something without more specifics. How are you imagining the way people can vote? Are they voting for their favorite player for that game, and can only vote for one player per game? Do they give "thumbs-up" to as many players as they want? Do they assign X out of 5 stars to a player?

The Fivestar module is very popular, and has pretty good documentation.

The Rate module is also popular, has a lot of different ways of voting, and there is a YouTube video showing how to use it.


See this example from Functions - In Twig Templates:

{# Link to node page. #}
{{ 'View node page'|t }}

in which you need to use the route to edit the node: entity.node.edit_form


Can I somehow edit libraries.yml files from the backend using the admin panel?

To directly answer your question, yes, you can edit config with the devel module. Install it, then configure it to display the Config Editor.

To answer your question pragmatically, I need to point out that making direct edits to configuration on a regular basis is a recipe for disaster. I think you would be better served using the Asset Injector module, which will allow you to add CSS and JS on the fly, without tinkering with configuration files.

If it is an absolute necessity to modify the library definition, then I think that hook_library_info_alter() is what you need. However, as leymannx points out, libraries aren't intended to be constantly manipulated on the fly. This brings me back to using the Asset Injector. The CSS injector portion is pretty much perfectly suited to your use case; it allows for adding and editing CSS through the admin interface. The CSS injector allows for multiple rules, and these can each be targeted based on path and/or theme.

If you combine this with custom classes attached to the page, then you can use those classes in your CSS rules. You can implement hook_preprocess_page() to do this:

myproject_preprocess_page(&$variables) {
  $node = $variables['node'];
  if ($node) {
    // Assume that the Taxonomy Vocabulary machine name is "category".
    /** @var \Drupal\taxonomy\Entity\Term[] $terms */
    $terms = \Drupal::entityTypeManager()
      ->getStorage("taxonomy_term")
      ->loadByProperties(["vid" => "category"]);
    // Get all categories present on the current node.
    $categories = $node->get('field_category')->getValue();
    // Get just the TIDs as a simplified array.
    $categories = array_column($categories, 'target_id');
    // Ensure that there is a class array.
    $variables['attributes']['class'] = $variables['attributes']['class'] ?? [];
    foreach($categories as $category) {
      // Craft a HTML-compliant class name based on the label.
      $variables['attributes']['class'][] = \Drupal\Component\Utility\Html::cleanCssIdentifier($terms[$category]->label());
    }
  }
}


I think you will find there is a conflict somewhere that is preventing the specific word (as it is a link) from being translated, and this submodule should overcome the conflict. I would utilise the "Menu Translation" submodule as it will specifically achieve what you are attempting above, and hopefully make it simpler! I would use the Translate and Localize Menus option (a detailed guide of how to do that is here)

If you are still stuck, and are using SuperFish for your menus (even though this is supported in i18n), there is a work around here and this may overcome the problem also.

Lastly, just in case, ensure you have this update, the most recent version, installed also.


If you don't want to code it manually, you can check this module JS injector which lets you inject JS code into your site.

  Allows administrators to inject JS into the page output based on
  configurable rules. It's useful for adding simple JS tweaks without
  modifying a site's official theme - for example, a 'nighttime' color
  scheme could be added during certain hours. The JS is added using
  Drupal's standard drupal_add_js() function and respects page caching,
  etc.

  This module is definitely not a replacement for full-fledged theming,
  but it provides site administrators with a quick and easy way of
  tweaking things without diving into full-fledged theme hacking.

  The rules provided by JS injector typically are loaded last, even
  after the theme JS, although another module could override these.


Zen theme doesn't append content titles to breadcrumbs

The theme breadcrumbs were being overridden by the Path Breadcrumb module. You can fix this in the Path Breadcrumb settings.


Drupal rules discount matrix - look up by taxonomy term

If you want to use rules (and with commerce I think it makes sense), and you are comfortable with PHP, I would recommend writing your own module that defines the custom conditions and actions that you need to look up and apply discounts.

In my experience, the rules interface starts to break down quickly when use cases become even moderately complex. You can spend a lot of frustrating time fiddling with the interface, trying to get it to do what you want.

By writing your own conditions and actions, you keep the complex logic in code, where you can easily debug, access, and compare any information you might need.

In addition, your custom actions and conditions will be nicely exposed in the rules interface, and keep the high-level logic of your commerce solution tidy in one place.

Docs are here: https://drupal.org/node/298486. Drupal commerce itself has many good examples of custom actions and conditions to use as reference.


How to access protected property in feed object?

There is no public method on the State object that returns the messages. The public methods on the object are:

progress()
setCompleted()
setMessage()
displayMessages()
logMessages()

The method displayMessages() is the closest method you can use to access the messages, the messages are then transferred to \Drupal\Core\Messenger\Messenger, which has a method called all() to return all the messages on that object.

PHP also has an API called 'Reflection', which - among more - allows you to bypass visibility settings on class properties and methods. The main purpose for this API is to retrieve doc comments for functions, classes and methods. I wouldn't recommend to use this unless if it is for debug purposes.

Note that since Feeds 8.x-3.0-alpha6 the messages are also displayed on the feed page while an import is not yet completed.

Why do you need access to the messages? Maybe you can open a feature request ticket in the Feeds issue queue to request adding a public method for retrieving the messages.


RESTws POST List (text) field type Error

The JSON format for list (text) for checkbox type would looks like follows

{"title":"My Day","type":"page","field_days_closed_v":{"und":["sunday", "monday"]}}

I've tested this, and working fine.

Here field_days_closed_v is the machine name of the  List text field (checkbox type). similarly sunday, monday are the values of checkbox type so change them accordingly.

Hope this helps. :)


Is --overrides an accepted option in drush 8.x?

It appears to be in the master branch, but not yet in 8.0.x.


How to require a JS library in a composer.json file

The instruction in Webprofiler completely right and it's referral to composer.json in the root directory, here another example to add react to Drupal:

    {
        "type": "package",
        "package": {
            "name": "facebook/react",
            "version": "v16.3.2",
            "type": "drupal-library",
            "dist": {
                "url": "https://github.com/facebook/react/archive/v16.3.2.zip",
                "type": "zip"
            }
        }
    }

After that, I run:

composer require --prefer-dist facebook/react:16.3.*

Completely works fine and the package was download to libraries folder.

From what you posted I can see that you did not add the package information.

This need to be changed VENDORNAME/PACKAGENAME so in the above example:

VENDORNAME is facebook

PACKAGENAME is react

here is how you get this information, the attached image from React Github repository

also, you can find that information in the repository URL.

here is the full repositories part I have it in one of the projects I'm working on:

 "repositories": [
        {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        },
        {
            "type": "package",
            "package": {
                "name": "d3/d3",
                "version": "v3.5.17",
                "type": "drupal-library",
                "dist": {
                    "url": "https://github.com/d3/d3/archive/v3.5.17.zip",
                    "type": "zip"
                }
            }
        },
        {
            "type": "package",
            "package": {
                "name": "facebook/react",
                "version": "v16.3.2",
                "type": "drupal-library",
                "dist": {
                    "url": "https://github.com/facebook/react/archive/v16.3.2.zip",
                    "type": "zip"
                }
            }
        },
        {
            "type": "package",
            "package": {
                "name": "components/highlightjs",
                "version": "9.7.0",
                "type": "drupal-library",
                "dist": {
                    "url": "https://github.com/components/highlightjs/archive/9.7.0.zip",
                    "type": "zip"
                }
            }
        }

    ]

If your module defines external dependencies which not hosted on Packagist or Drupal.org then Drupal core will not automatically discover or manage these dependencies.

You must use the wikimedia/composer-merge-plugin package to accomplish this. This plugin is installed with Drupal core.

Thats why in Webprofiler module they add the instruction to readme not to the composer.json in Webprofiler directory.


How to configure a Slideshow with thumbnails in modal window

I was able to find a perfect solution to this, very easily as always. I use module Lightbox2, with the Slideshow option. Now I don't put the href with the reference to the big images in the small images - that would be standard behaviour, but I create 3 empty href with the data (the data come from an array passed to the .tpl.php):

<a href="<?php print $image_value["filename"] . "-960.jpg"?>" id="imagelink<?php print $conti; ?>" rel="lightshow[products]<?php echo $conti; $conti++;?>" >

The images themselves have other code which just changes the main image:

function change_photo(filename, conti){
    var object = document.getElementById("product-photo");
    object.src = filename + "-480.jpg";
    contagen = conti;
} // function

And finally in the onClick of the main image, I launch the slideshow by simulating a click of the empty links at the begginning of the code:

function launchslide(){
    var object = document.getElementById("imagelink" + contagen);
    object.click();
} // function


Is it better to use module_invoke_all(), or  module_invoke() and module_implements()?

There is little difference; module_invoke_all() runs the following code:

function module_invoke_all() {
  $args = func_get_args();
  $hook = $args[0];
  unset($args[0]);
  $return = array();
  foreach (module_implements($hook) as $module) {
    $function = $module . '_' . $hook;
    if (function_exists($function)) {
      $result = call_user_func_array($function, $args);
      if (isset($result) && is_array($result)) {
        $return = array_merge_recursive($return, $result);
      }
      elseif (isset($result)) {
        $return[] = $result;
      }
    }
  }

  return $return;
}

The only difference is that with module_invoke_all(), for example, func_get_args() is invoked only once, while when using module_invoke() func_get_args() is called each time module_invoke() is called; that is a marginal difference, though.
There are a few cases where module_implementing() and module_invoke() are used, normally when a module needs to know which module is invoked, such as in the case of search_get_info() that builds an array of information about the modules implementing search functions.

function search_get_info($all = FALSE) {
  $search_hooks = &drupal_static(__FUNCTION__);

  if (!isset($search_hooks)) {
    foreach (module_implements('search_info') as $module) {
      $search_hooks[$module] = call_user_func($module . '_search_info');
      // Use module name as the default value.
      $search_hooks[$module] += array(
        'title' => $module,
        'path' => $module,
      );
      // Include the module name itself in the array.
      $search_hooks[$module]['module'] = $module;
    }
  }

  if ($all) {
    return $search_hooks;
  }

  $active = variable_get('search_active_modules', array('node', 'user'));
  return array_intersect_key($search_hooks, array_flip($active));
}

Another example is image_styles(), which gets the list of all the image styles implemented by the modules, and that uses the following code:

  foreach (module_implements('image_default_styles') as $module) {
    $module_styles = module_invoke($module, 'image_default_styles');
    foreach ($module_styles as $style_name => $style) {
      $style['name'] = $style_name;
      $style['module'] = $module;
      $style['storage'] = IMAGE_STORAGE_DEFAULT;
      foreach ($style['effects'] as $key => $effect) {
        $definition = image_effect_definition_load($effect['name']);
        $effect = array_merge($definition, $effect);
        $style['effects'][$key] = $effect;
      }
      $styles[$style_name] = $style;
    }
  }

In both the cases, the retrieved information is put in an array where the index is the short name of the module.


Can I download all data from drupal.org?

http://updates.drupal.org/release-history/project-list/all is a XML-document that lists all projects and their releases. It's a large file, but should provide all the info you need.


How can I get the filesize of an image with an image style programmatically

You can get the size of the original image easily:

$size = filesize($data->field_field_photo[0]['raw']['uri']);

But the size of an image file behind a derivative path is impossible to get reliably. The files aren't generated until the URL is first visited, so the file may simply not exist yet.

For those that do already exist, you can use image_style_path():

$path = image_style_path('img-lib', $data->field_field_photo[0]['raw']['uri']);
if (file_exists($path)) {
  $size = filesize($path);
}

If it's 'mission-critical' to get the file size, you can always force-create the derivative there and then with image_style_create_derivative():

$path = image_style_path('img-lib', $data->field_field_photo[0]['raw']['uri']);
if (file_exists($path)) {
  $size = filesize($path);
}
else {
  if (image_style_create_derivative('img-lib', $data->field_field_photo[0]['raw']['uri'], $path) === TRUE) {
    $size = filesize($path);
  }
}

if (!isset($size)) {
  // Something went wrong creating the derivative...
}

It's worth noting that you shouldn't do all (or any really) of the above directly in a template file. Instead, move your logic out to a preprocess function and pass variables in.

And if you're looking for full-on 'best practice', instead of accessing the field data directly through the array (e.g. $data->field_field_photo[0]['raw']['uri']), prefer field_get_items() for procedural-style, or an EntityMetadataWrapper if you're comfortable with OO.


How do I return a Twig template inside the build method of a block class?

In your modules *.module file you must implement hook_theme() like this:

/**
 * Implements hook_theme().
 */
function fax_theme() {
  return [
    'fax_custom_theme' => [
      'variables' => [
        'test' => NULL, # Makes the {{ test }} variable available in the template.
      ],
    ],
  ];
}

Then you can return this in your block:

$test = 'My custom variable';
return [
  '#theme' => 'fax_custom_theme',
  '#test' => $test, # Assigns a value to the {{ test }} variable.
];

This makes the {{ test }} variable available in your theme.

Then add your template to the module under fax/templates/fax-custom-theme.html.twig.

Template names are using dashes instead of undercores.


Custom block won't display in admin - Drupal 7

Try the next code below, it work for me:

/**
 * implements hook_block_info().
 */
function mymodule_block_info() {
  $blocks['hello-message'] = array(
    'info' => t('Message'),
    'status' => TRUE,
    'visibility' => BLOCK_VISIBILITY_LISTED,
    'pages' => 'example/1*',
    'cache' => DRUPAL_NO_CACHE,
  );

  return $blocks;
}

/**
 * implements hook_block_view().
 */
function mymodule_block_view($delta = '') {
  $block = array();

  if ($delta == 'hello-message') {
    $block['subject'] = t('Message');
    $block['content'] = t('Hello World!');
  }

  return $block;
}

See https://api.drupal.org/api/examples/block_example%21block_example.module/7


How to manage form display non programmatically?

The most close approach that I was found is the Display Suite module.

Display Suite allows you to manage the display of content editing forms for entities (such as nodes, views, comments, users, et cetera). This can be useful if you want to provide the users of your website with a customized edit form (and you don't need to implement the hook_form_alter()).

When enabled Display Suite Forms takes over the Drupal core functionality that let you arrange the fields via the "Manage fields” tab.

Manage display of an editing form

Enable the sub module Display Suite Forms at Administration > Modules (admin/modules)
Go to Administration > Structure > Display Suite (admin/structure/ds)
Click "Manage form" for the entity (e.g., "User") that you like to change
At the bottom of the page, in the vertical tab "Layout for ... in form" choose "One column" and click "Apply"
Chose the Hidden option in the field.
Save the changes

Another way is the use of the Rules Forms  module, but you need make a rule for this after enable the module.

Go to the "Form events" page in the Rules administration menu
(admin/config/workflow/rules/forms).
Select the checkbox "Enable event activation messages on forms" and hit the "Save settings" button.
Go to the form on your site that you would like to customize with Rules, e.g. go to 'node/add/article' to enable events on the "Create Article" form.
On the top of the page you see a drupal message with a link to activate events for the form, click it.
Enter a human-readable label for identifying the form.
In some cases you may want to enable events for individual buttons on the form. To do so, check the checkbox labeled "Enable button level validate/submit events".
Confirm the activation by clicking the "Activate" button.
Go to the "Triggered rules" admin page (admin/config/workflow/rules) and click the "Add a new rule" link.
Fill out the label, choose a form event by selecting one in the "Rules Forms" group and confirm with "Save changes".
Now you can select "Hide an element in the form" and select the element to hidde.

Reference:

https://www.drupal.org/node/1795380
https://www.drupal.org/node/1456178


Alter menu structure when using Superfish menu

The Superfish module bypasses the usual Drupal theming hooks for menus and implements its own. You will need to override the theme_superfish() function in order to change the HTML around those menu items. Copy that function out of superfish.module into your theme's template.php file. Replace the word "theme" in the function name with your theme's machine name, and make your edits.


How to condition output based on a URL query string

There are three layers where rendered content can be cached:

The Page Cache, which stores complete pages based on the URL for anonymous users.
The Dynamic Page Cache, which stores pages with placeholders for dynamic content that is rendered on each request.
The Render Cache, which stores individual rendered elements.

Each has a corresponding cache bin that can be disabled during development in settings.php

To set an additional cache context in hook_preprocess, so that the Dynamic Page cache knows to re-render that fragment and the render cache stores variants as needed, update the #cache variable:

function hook_preprocess_HOOK(&$variables) {
  $variables['#cache']['contexts'][] = 'url.query_args:exclude_urls';
}


Use an image instead of a menu link in Drupal 7

I am answering my own question, as I googled and found something, mixed it and carved my own way to do it.

function mytheme_menu_link(array $variables) {
  global $base_path;
  $element = $variables['element'];
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);

  if($element['#title'] == 'Home') {
    $element['#localized_options']['html'] = TRUE;
    $get = '';
    $output1 = l($get,$element['#href'], $element['#localized_options']);
    return '
' .$output1    . "
\n";
  } else {
    return '
' . $output . "
\n";
  }
}


How do I display a summary page after finishing a multistep form?

Multistep forms are pretty well documented in Examples for Developers module. Basically if you need a summary before posting, add one more step, as steps have access to values from previous ones. If you need a "thank you" page, use usual redirect. That's the answer for question in title, at least.

If you are using some modules than stops you from doing it the traditional way described above, you need answer from someone familiar with that particular modules. Sorry, cannot help you specifically with ctools wizard.


Formatting is lost after publishing the content

Is it possible your input format is a "filtered HTML"? If I'm not in wrong it removes a lot of attributes: try to change it to "Full HTML" and verify the behaviour...


Contact form - leaving the form and resuming it later

Yes, you can build a contact form with the Webform module and use its "Save Draft" feature.


Grouping content by taxonomy, multiple taxonomies by node

You have many solutions available.

Solution 1:

Enable "Use aggregation" option with the default settings, it should be enough.

Solution 2:

You can create a view of terms and add a "Relationships" with "Taxonomy term: Content using Category". As fields you have to add the content fields (with the new relation) and the term name (used for the grouping).

This is an example of the view assuming the content type is "article", the category field is called "field_category" and the vocabulary is "category":

$view = new view();
$view->name = 'nestedexample';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'taxonomy_term_data';
$view->human_name = 'nestedexample';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'nestedexample';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['style_options']['grouping'] = array(
  0 => array(
    'field' => 'name',
    'rendered' => 1,
    'rendered_strip' => 0,
  ),
);
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: Taxonomy term: Content using Category */
$handler->display->display_options['relationships']['reverse_field_category_node']['id'] = 'reverse_field_category_node';
$handler->display->display_options['relationships']['reverse_field_category_node']['table'] = 'taxonomy_term_data';
$handler->display->display_options['relationships']['reverse_field_category_node']['field'] = 'reverse_field_category_node';
/* Field: Taxonomy term: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'taxonomy_term_data';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
$handler->display->display_options['fields']['name']['link_to_taxonomy'] = TRUE;
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['relationship'] = 'reverse_field_category_node';
/* Field: Taxonomy term: Name */
$handler->display->display_options['fields']['name_1']['id'] = 'name_1';
$handler->display->display_options['fields']['name_1']['table'] = 'taxonomy_term_data';
$handler->display->display_options['fields']['name_1']['field'] = 'name';
/* Sort criterion: Content: Title */
$handler->display->display_options['sorts']['title']['id'] = 'title';
$handler->display->display_options['sorts']['title']['table'] = 'node';
$handler->display->display_options['sorts']['title']['field'] = 'title';
$handler->display->display_options['sorts']['title']['relationship'] = 'reverse_field_category_node';
/* Sort criterion: Taxonomy term: Name */
$handler->display->display_options['sorts']['name']['id'] = 'name';
$handler->display->display_options['sorts']['name']['table'] = 'taxonomy_term_data';
$handler->display->display_options['sorts']['name']['field'] = 'name';
/* Filter criterion: Taxonomy vocabulary: Machine name */
$handler->display->display_options['filters']['machine_name']['id'] = 'machine_name';
$handler->display->display_options['filters']['machine_name']['table'] = 'taxonomy_vocabulary';
$handler->display->display_options['filters']['machine_name']['field'] = 'machine_name';
$handler->display->display_options['filters']['machine_name']['value'] = array(
  'category' => 'category',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'nestedexample';

Solution 3:
Another solution is adding a relationshipt with the taxonomy terms "Content: Taxonomy terms on node" and use the taxonomy term from the relationship as group by field.
I hope this will help you.


What type of field are you using ? If it is a body_format using a format (i.e.: Filtered HTML, Full HTML) verify the filter settings. Probably Limit allowed HTML tags is enabled and the  tag is not part of the allowed tags.

To verify / change settings, it is under admin/config/content/formats and click on configure link of your used format.


Problem with integer field format in Drupal 7

Go to the "Manage display" tab and edit "Thousand marker".


Found the solution for this, I used Hierarchical Select
and it worked like a charm.


How to add custom sort order to a taxonomy field list?

The Taxonomy Term Reference Sortable Widget module appears to meet your requirement. Once installed, the module will provide a widget that can be selected for a taxonomy term field via its widget type panel. (Admin -> Structure -> Content Types -> My Content Type -> Manage Fields -> My Field -> Widget Type).

If you have a lot of different terms available this may not be a good choice because it displays a full master list of terms from which you select and order those you need. It does not have an option for using autocomplete to build the set.


Which module facilitates looking up database schemas of custom content type?

I think the Schema Module can handle that...

  Schema documentation: hyperlinked display of the schema's embedded documentation explaining what each table and field is for.

I confess I haven't tried it but the module page mentions

  the INFORMATION_SCHEMA database that the Schema module uses to inspect the database.

so I imagine it has the functionality you're looking for, plus inspection of the live db if you need it.

Or if you don't mind wading through a large krumo array you can always use drupal_get_schema()

dpm(drupal_get_schema());


Specify which Migrate entries need to be updated using prepareRow

The recommended way to do what you are trying to do is with drush. Is drush available to you? if so have cron execute a drush mi command. See https://drupal.org/node/1561820. Also make sure your highwater mark is set up correctly. See https://drupal.org/node/1223936.


user/login page displays but gives a 404 error on firebug

The solution is in your Apache config file. Enable ‘LoadModule rewrite_module modules/mod_rewrite.so’ in httpd.conf file and clear the cache and then login again.


Build a form dynamically with the results of a view?

Build the custom form from inside the view and attach it to the view before rendering:

mymodule.module

/**
 * Implements hook_views_pre_render().
 */
function mymodule_views_pre_render($view) {
  if ($view->id() == 'myview') {
    // get field values from the view result
    $values = [];
    foreach ($view->result as $row_id => $row) {
      foreach ($view->field as $field_id => $field ) {
        $values[$row_id][$field_id] = $field->getValue($row);
      }
    }
    // build form with the view result
    $form = \Drupal::formBuilder()->getForm('Drupal\mymodule\Form\MyForm', $values);
    // attach the form to the view
    $view->attachment_after = $form;
  }
}

Use the view result for building the form:

/src/Form/MyForm.php

class MyForm extends FormBase {

  public function buildForm(array $form, FormStateInterface $form_state, array $values = NULL) {
    // build form with $values
  }


Updating views to views 3 Beta 3 created 2 new OG views, OG Nodes was one of them and it fixed the issue.

Note:  Adding blocks to "Content" would ignore weight (order) of the blocks, I had to create a content-top and content-bottom area in page.tpl.php!


Route AJAX failure messages to console instead of popup

You can check Prevent JS alerts module..

Project page says

  This module is an answer to the issue: #1232416: Drupal alerts "An
  AJAX HTTP request terminated abnormally" during normal site operation,
  confusing site visitors/editors, which describes a big problem for end
  users: JavaScript alert();'s for end users on AJAX errors by Drupal
  core. Perhaps it will one day become obsolete, when this bug is fixed.
  End users are often frightened of these errors and don't know, if they
  have "destroyed the internet" ;)

  This module completely suppresses ALL JavaScript alerts and instead
  prints them to console via console.error! Important: It does NOT ONLY
  suppress the core alerts, but also custom alerts.


What is the syntax for using a contrib module's service from within a hook implementation?

You can access services via \Drupal::service('service.name').
You need to know the service's name to access it, though. Looking at the s3fs module, I can see in the module's s3fs.services.yml file that the class your requesting is available with the service name s3fs.
$s3fs = \Drupal::service('s3fs');
$result = $s3fs->getAmazonS3Client($config);


It must be because you are adding the unsigned attribute to text fields.


How to limit the products available to choose from, in the inline entity form of a product display

When you are adding an existing product to a product display there is an autocomplete field that you can use to search existing products.

This field is called entity_id. If you use hook_form_alter() and inspect the form you'll see this field has a property called #autocomplete_path.

e.g.

$form['product_display_variations'][LANGUAGE_NONE]['form']['entity_id']['#autocomplete_path'] = 'inline_entity_form/autocomplete/node/product_display_variations/product_type';

You can visit that URL and see it just returns a set of json formatted results.

You can create your own path with hook_menu() and then use your path instead of the default one (make this change in hook_form_alter).

In your custom menu callback you can apply any additional logic (e.g. filtering by uid) to just return a sub-set of products. Then use drupal_json_output() to return your dataset.


Output Flexifield content as Excel file?

Have you tried the CSV export provided by Views Bonus Pack? It's not true XLS, but does it need to be, as long as it opens in Excel and the data is correct?


May be the css property for the image in the full page was written as width:100% and height:auto , so it will always makes an image in large full size. you can check by inspect element to see the correct path of image style is coming or not.

You can get the image path from there and paste that in new tab to see what size of image is coming without applying any css rules.

Hope this will help you.


Get image file values in $form_state in media entity form

Normally you use a ConstraintValidator for validating entities. In this case core invokes a hook so that you can add your own error messages to the existing file validation process:
function hook_file_validate(Drupal\file\FileInterface $file) {
  $errors = [];

  if (!$file->getFilename()) {
    $errors[] = t("The file's name is empty. Please give a name to the file.");
  }
  if (strlen($file->getFilename()) > 255) {
    $errors[] = t("The file's name exceeds the 255 characters limit. Please rename the file and try again.");
  }

  return $errors;
}

About the caveat for using form alter. You can add custom #upload_validatorsto the image widget. Add settings if necessary:
$element['#upload_validators']['my_custom_file_validator'] = [$my_setting];


Use contextual filter global null to pass values to override field result

Took me a while but i solved this problem with something like this:

Added 3 Global: Null context filters and then i configured them with something like this:

For global 1:
WHEN FILTER VALUE IS NOT IN THE URL>>Provide default value>>Type:RAW value from URL>> Path Component: 1 >> Checked Use Path Alias >> Apply changes

For global 2:
WHEN FILTER VALUE IS NOT IN THE URL>>Provide default value>>Type:RAW value from URL>> Path Component: 2 >> Checked Use Path Alias >> Apply changes

For global 3:
WHEN FILTER VALUE IS NOT IN THE URL>>Provide default value>>Type:RAW value from URL>> Path Component: 3 >> Checked Use Path Alias >> Apply changes

And with that you can get the values to use them when you want to override a field output using contextual filter values.


Drupal views autocomplete filter inserts html tags

@MPD: Yes the problem was due to the formatter. The field format was set to Filtered HTML. Once I changed that to Plain Text in Views Exposed Filter settings for the autocomplete filter for the field, it worked. It was a simple change that I did not notice.

Thanks.


How do I get clean output with indented structure

HTML Tidy can do what you're wanting, but this is designed as text format, Configuration » Content authoring » Text formats which are used in fields rather than the whole site.

Is should be possible with some work to pass the entire theme though HTML Tidy


Without having to do too much you can use CSS Injector: https://www.drupal.org/project/css_injector

Just install the module and then make your CSS rule to only work on the assigned admin theme.

There are of course other ways to do this, you can write a custom module and add CSS that way as well.


First recommendation: Just use MediaWiki for the whole thing. It's not as nicely modular as Drupal but it has a lot of facilities. And as a bonus it's likely that upgrading will be easier (Dn->Dn+1 has always been a pain to me, MW upgrades have always been very smooth for me).

If you still want to use Drupal, I would use MediaWiki's parsing. E.g. fetch articles through index.php?action=render&title=Page_Name. It's probably best to simply fetch data when needed but with a long cache time (e.g. 1 week) to avoid Wikipedia blocking your server's IP.


How do I set an entity base field as NOT NULL?

There is no API for that at the moment, every field that is specified as a key happens to be set to not null, but that's IMHO actually a bug and I would not rely on that.

Instead, the only thing you can do is provide a storage schema handler and customize the schema there.

See \Drupal\node\NodeStorageSchema::getSharedTableFieldSchema() for example.


What that I have done to fix it is obvious from the question
remove drupal/bootstrap from composer.lock and from composer.json
composer require drupal/bootstrap:3.16


Major differences between Drupal-6 and Pressflow-6?

Take a look at the wiki: "Comparison - Pressflow versus Drupal".


how to populate select list using hook_form_alter()?

For select field we can use as follows

$form['field_task']['und']['#options'] =$arr;
//array('black'=>'black')


How to send notification emails in a journal style "Newsletter"?

For sending notifications you can use the Notifications module.


How to show data of user that flagged a content(2 flag types)?

Add a filter for the whole view that checks username in both fields as not null,  and set the operator to 'And'.

In your view under 'Filter Criteria' do the following:

Add user name with the first relationship and set the operator to 'is not empty (NULL).
Do the same for the second username field.
Click the dropdown arrow next to add for 'Filter Criteria'. Select And/OR, Rearrange and add an 'AND' operator between the two filter.
Hide the second username from display.

That way you can filter for users with both flags.


Retrive $message variables in javascript file

In your page.tpl.php file:

$my_settings = array(
  'message' => $message,
);

drupal_add_js(array('my_settings' => $my_settings), 'setting');

Then in your JavaScript file you can access $message variable like this:

var message = Drupal.settings.my_settings.message;

Reference: The Drupal JavaScript API


different sort criteria depending on term ID

I accomplished what I wanted to do by using hook_views_pre_build() and hook_views_query_alter()

 /* Remove sorting by weight if viewing a category that should be alphabetized.*/
 function commerce_customizations_views_pre_build(&$view) {
   $alphabetize = array('3','58');

   if($view->name == 'taxonomy_term' && $view->current_display == 'page'
   && in_array($view->args[0], $alphabetize)) {
    unset($view->sort['weight']);
   }
 }

 /* Sort by title if viewing a category that should be alphabetized.*/
 function commerce_customizations_views_query_alter(&$view, &$query) {
   $alphabetize = array('3','58');

   if($view->name == 'taxonomy_term' && $view->current_display == 'page'
      && in_array($view->args[0], $alphabetize)) {
        $query->add_orderby('node','title','ASC');
   }
 }


Note, to avoid getting the 'pass by reference' error, assign the output to a variable before passing it in as an argument to the render() or drupal_render() functions

Partial Solution, without preserving display settings

For reference, I tried:
How do I render a field value including its format?

Which gave me something similar to:

<?php
$banner = field_view_field('bean', $bean, 'field_banner_image')
echo render($banner);
?>

The only problem being that it was ignoring my output display formatting I had set on the block type. You can specify one, but I couldn't find a source readily available with the values of the $display array which would be passed as 4th parameter to field_view_field.

Full solution, preserving display settings

Since I wanted to preserve the setting specified by the configuration of the field, and not rely on display defaults (ie: showing the label above an image) I looked back at the bean.tpl.php. Within the content they were building the $elements array, and using drupal_render. Giving this a shot and it worked:

<?php
$banner = $elements['field_banner_image'];
echo drupal_render($banner);
?>

This also preserved my removal of the field label.

This was all done within my bean--banner.tpl.php which should be a similar setup to what you're facing. Hope this helped!


First off, super fish module doesn't require the jquery update module so uninstall it. It's a PIA module if you don't need it. Second, in the superfish settings, set it to render 1 block. Go to the blocks and find the super fish block. Edit that block and set it for whatever menu you would like to use it for and place it in a region.


In Ubercart, can I make a "View Cart" link appear only when an item is in the user's cart?

Create a block with your "View Cart" html code then set block visisbility to "Pages on which this PHP code returns TRUE (experts only)" with the following:

<?php
$items = uc_cart_get_contents();
if (count($items) > 0) {
  return true;
}
return false;
?>


If you have the rest module enabled you have a new display type called "REST export". There you can configure to either return just the normal REST output for all entities, or you can even configure which fields you want to include.

Much like you enable REST support for entity types you also don't want to deal with unwanted REST access by default.


Image Style Issue Doesn't Work Every Time

My gut is that this is a file permissions issue. Check to make sure that the webserver has the appropriate permissions for the directory in question, and the one above it.


Apply CSS and Javascript affect to images

I have done a CSS only alternative for you.

http://jsfiddle.net/bk5h7/

EDIT: In answer to the JS not working in Drupal, you may need to wrap any document ready JS in behaviour tabs, and/or declare jQuery.

This will also help if you use it in a view that uses AJAX. Putting it in a behaviour instead of document ready, means the JS will load again even on every AJAX request.

(function($) {
Drupal.behaviors.myBehavior = {
  attach: function (context, settings) {

        // Put your jQuery Code Here

  }
};
})(jQuery);

EDIT 2: The demo uses jQuery 1.9.1, whereas Drupal 7 is shipped with 1.4.4. Maybe try using the jQuery Update module to update your version.

EDIT 3: What are you using to load the Modernizr.js script? That touch function you are talking about relies on device detection using Modernizr.js.

Copy the modernizr.js file to your themes JS folder, and in your themes template.php file, try adding...

drupal_add_js(drupal_get_path('theme', 'YOUR_THEME') . '/js/modernizr.js');


How to add specific field to article node twig template?

Rendered output of this field

{{ content.field_article_description }}


How to delete all data in one field of a particular content type?

If you only need to do this once you could use Views Bulk Operations https://www.drupal.org/project/views_bulk_operations

/admin/structure/views

Click "Add new view" link
Show "Content" of type "YOUR_CONTENT_TYPE"
Click "Continue & Edit" button

Under the FORMAT section change Show: click 'Content' change to 'Fields'

Click 'Apply' button
Click 'Apply' button again

Under FIELDS section click the 'Add' button

Checkmark 'Bulk operations: Content'
Under SELECTED BULK OPERATIONS choose 'Modify entity values' checkbox
Scroll down a little, you will see OPERATION SETTINGS choose that date Field you want to edit.
Click 'Apply' button
Click 'Save' to save that View

Go to the View Page you just created.

Under Operations choose 'Modify entity values'
Select one or all of them (I suggest you do one as a test).
Click the 'Execute' button.
This page will allow you to set the Date to anything you want, even nothing. TIP! for Date if you want no date you need to change all values to blank. You can't delete just the hours, you need to set all of them to blank, which gives you the result you requested.
Click the 'Next' button.
Click the 'Confirm' Button.

Congrats. Go back and run it on all of them, if it went as expected on the one test node.


Removing the #submit key fixed the submission issue for me:

$form['save'] = array(
    '#type' => 'submit',
    '#input' => TRUE,
    '#value' => 'save',
    //'#submit' => array('buildForm')
);

DB insert works correctly.

If you do return $form; in the buildForm() method, the radios form element is rendered correctly. Looks like your theme might be causing the issue.


Form elements removed during custom page render

How are you then using $output? Are you putting it into ['#markup'] in your build array?

If so markup content will strip all sorts out. So either you can put $form as a separate item in your build array and there's no need to run it through render()

Or you can use drupal's "inline_template" rather than #markup in the build array


How do I render a block programmatically with the standard template?

If you want to render blocks directly from twig you can use:

Twig tweak 8.x-1.9 https://www.drupal.org/project/twig_tweak

You just need to install it.
The block should be configured on "admin/structure/block" page.
Example how to use:

Block:

{{ drupal_block('system_powered_by_block') }}

Add this code directly in the twig template file.


If a Views Contextual Filter using PHP code doesn't resolve, can I make Views "Display all results"

when you want to show all then

return "all";

;)


How do I add a color hex code field to a product attribute using drupal commerce 2?

For anyone else grappling with this issue in future here is what I did:

****How to add a color hex code field to a product attribute using drupal commerce 2****

see also: https://drupalcommerce.org/blog/44310/enabling-fancy-attributes-commerce-2x

Use the Color Field module to add a color field to your Color attribute.
https://www.drupal.org/project/color_field

Install with Composer: $ composer require 'drupal/color_field:2.x-dev'

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Product Attributes  >>  Add Colour Attribute    >>  Manage Fields

Add:

Label:      Color Hex Code

Machine Name:   field_color_hex_code

Field type:     color

DEFAULT VALUE
The default value for this field, used when creating new content.

COLOR HEX CODE

Color       #D3D3D3

Opacity     1

Record Opacity  Ticked

FIELD SETTINGS TAB

Format storage  #123ABC
Choose how to store the color.

Allowed number of values:   Limited     1

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Product Attributes  >>  Add Colour Attribute    >>  Manage form display

FIELD   WIDGET

Name        Textfield       textfield size: 60

Color Hex Code  Color default       No placeholder

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Product Attributes  >>  Add Colour Attribute    >>  Manage display

FIELD           LABEL       FORMAT

Color Hex Code      Hidden      Color Swatch        Square Width: 40 Height: 40

Note:
Remember to change the attribute selection widget to use the rendered option for your attribute.


How can I run Drush 8 and Drush 9 together on same machine to test some module on it?

Install Drush 8 by downloading the phar file as recommended in the documentation. Rename the phar file to drush8, not drush.

Install Drush 9 as recommened in the documentation. I strongly recommend to install Drush Launcher globally using a phar file as documented and only install Drush site local. This is very easy if you are already using Composer to maintain your Drupal site. If you aren't using Composer to maintain your site, you can just as well install Drush 9 globally using Composer and forget about Drush Launcher.


Remove Admin Toolbar "Manage" item if User has No Access

TLTTP;

Is a core bug since 6.4 version (https://www.drupal.org/node/296693) you can use the latest version of admin_toolbar (https://drupal.org/project/admin_toolbar) which haves a submodule specific for that issue. Unfortunately this only works for 'admin_menu' menu but not the toolbar menu (the black bar on top). To hide specific toolbar elements or toolbar element tray links (toolbar element links) you can implement hook_toolbar_alter(&$items) hook (https://api.drupal.org/api/drupal/core!modules!toolbar!toolbar.api.php/8.5.x).

Hope it helps someone.


Is it possible to show password reset email success in user password page?

By default, drupal_set_message() is set and displayed on form submission when a new password is emailed. It's possible LoginToboggan is interfering with this but I haven't encountered that in my use of it.

Alternatively, if you cannot resolve the issue, you can use hook_form_alter() to create your own submission handler on the password reset form, and use drupal_set_message() to re-show the message (or any custom message you provide) on the form.

function MYMODULE_password_reset_form_alter(&$form, &$form_state, $form_id) {
  $form['#submit'][] = 'my_custom_handler';
}

function my_custom_handler($form, &$form_state) {
  drupal_set_message('An email has been sent with instructions to reset your password.');

}


How to make the Rules module perform a redirect to an URL that includes a query string?

You may want to try the "Rules URL argument" module to get this to work. Here is a quote about it (from its project page):

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

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

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

Refer to my answer to "How to use the Rules module to implement a custom redirect for an outdated URL?" for way more details about this module also.


Are there existing modules to group nodes and give sequential access to them in Drupal 7

I would recommend the following modules:

Views: Views is a powerfull query and report generator. You can filter and sort your nodes or show individual nodes based on any criteria.
Rules: Rules allows you to take action on a lot of ocations. Let's say you can change data, roles or access rights on nodes when a user sees a node or confirms to have read the contents.
Fields (built in core): Is a little bit like Access: Create your data structures without coding.

It's very likely that you can do 90%-100% of you requirements with this (and may be some more helper) modules. Sometimes some glue code in a custom module is necessary.


Have you already tried to use Organic Groups and Notifications ?
There is also Organic groups e-mail blast module I didn't try.


How does the Drupal template engine work?

The Theming Guide is a good place to start.  Also the Theming Drupal 6 and 7 pages should be of some help to you (more specifically, How the Drupal theme system works).

Theming guide:

  This handbook is about customizing the look and feel of a Drupal site.
  We'll show you how you can modify the appearance of your Drupal site
  without requiring expert knowledge of programming. And if you wish to
  go further, we cover that too.

  This guide assumes some knowledge of HTML and CSS but no PHP
  programming knowledge is necessary. It also assumes you have
  administrator's privileges to a Drupal site. You might also want to
  familiarize yourself with some of the terminology used in Drupal. We
  concentrate on Drupal 7 with notes for Drupal 6 where applicable.

How the Drupal theme system works:

  Pages in this section describe the way the Drupal theme system
  operates, theme components and settings, .info files and page
  templates. This section is a starting point for creating a new custom
  theme.


How to create webform according to user rules

you need to try this coding

function _form_edit_module_form_alter(&$form, &$form_state, $form_id) {
 if($form_id =='webform_form_id') {
  //check login user enter in site
  global $user;
  if ($user->uid) {
     $form['component_name']['#attributes']['disabled'] = true;
  }
 }
}

and also you need check  Webform Conditional module


How to insert data to webform via HTTP/Drupal REST module?

I used webform_service with services module to insert data in webform using REST and its working fine form me.


Inject variables only in teasers (template suggestions)

In a preprocess/process function for the node template file, you just need to check the following variables:

$variables['teaser'] must be TRUE
$variables['node']->type must be 'article'

$variables is the parameter passed to preprocess/process functions.


Making a block to show the status of the user account?

Pending User Notification Block

  This module is for sites that allow users to create an account, but
  require administrator approval for account activation. This module
  creates a block that shows a list of unactivated user accounts, with
  links to their account pages. This block is visible for anyone with
  'administer users' permission, and will not be shown to any other
  users.


never mind, menu_set_active_item('test/%user_uid_optional/test2') in test_whatever (last callback in example) seems to work.

Both item, 'test/%user_uid_optional' and 'test/%user_uid_optional/test2', are active and visible, and the drupal_get_form is executed, so who cares about beauty :)?


Single site vs Sub-sites vs Multi-site installation + Scalability

There are many possible ways to build out a site like this.  Right off the top, I would recommend against using a multi-site setup.  c.f. Drush pm-update and multisite.  If you did want to use multiple Drupal sites for this, I would use aliases in your vhost conf file to point /orgb, /orgc etc. to a separate Drupal root.

However, in this particular case I think you would be best off using a single Drupal site with Organic Groups and Organic Groups Theme.  Disclaimer: the latter module is minimally maintained, and I have not used it personally.   If you wanted to support orgb.site.com instead of orga.site.com/orgb, then you could use the Domain Access or Subdomain module instead, although if you use Domain Access you should be aware of the issue Domain Access and Organic Groups.  Try a couple of experiments and see how they fit your use case before diving in and doing the whole implementation; you should be able to set up something pleasing fairly easily.


How to bootstrap a custom script and retrieve the session object?

This is the code I came up with in the end. It works.

Feel free to suggest a more concise version :-)

<?php

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

$drupal_root = realpath(__DIR__ . '/../');
$autoloader = require_once $drupal_root . '/autoload.php';

// Make sure Drupal operates correct when handle request instead of internal server error and twig error
chdir($drupal_root);

$kernel = new DrupalKernel('prod', $autoloader);

// Note: The session_name is generated from the string "{domain}/{script basepath}".
// Need to override the script filename and script name before creating request.
$_SERVER['SCRIPT_FILENAME'] = $drupal_root . '/index.php';
$_SERVER['SCRIPT_NAME'] = '/index.php';
$request = Request::createFromGlobals();
// Note: may restore script_name and script_filename after this line.

// This handle process would chain up and initialize all services
// in container, include the session handler.
$kernel->handle($request);

// now we can use session normally
$session_handler = \Drupal::getContainer()->get('session_handler.storage');
$session_id = $session_handler->getId();
$logged_in = (bool) $session_handler->read($session_id);

// restore app
chdir(__DIR__);


You can add custom links that aim directly to your content type in the admin tool bar.

Take a look on this link: https://drupal.org/node/1664828


How to get values which changed during node edit in node api?

The $node argument to hook_node_update contains a $node->original object. With that you can identify the newly added user IDs by comparing $node->your_user_ref_field to $node->original->your_user_ref_field.


How can I theme the Responsive Image module in a specific Paragraph Type

I found a solution, but I'm honestly not happy with it.  I can use 'responsive_image_style_id' to identify this responsive image. The problem with this approach is that it relies on specific keywords ('_style') in 'responsive_image_style_id' and if a site admin changes that, it will break :

function paia_theme_suggestions_responsive_image_alter(&$suggestions, $vars, $hook) {

  $newHook = str_replace('_style', '', $vars['responsive_image_style_id']);

  if ($newHook != $vars['responsive_image_style_id']) {
    $suggestions[] = $hook . '__' . $newHook;
  }
}

It seems I am using entirely the wrong approach for this, and I should probably be rolling my own module or something totally different. But I have a deadline to meet and I need to move on.


Custom view single content wrapper css style

You can reduce the standard markup with these options in views:


Is there a way to render a node with view mode via token?

So the question is how to insert something like [node:5:teaser] into a formatted text area and get the teaser view of node 5.

This can be done with a combination of modules:

Token Filter (D7,D8)

  Token Filter is a very simple module to make token values available as an input filter.

So (after adding that filter to the text format), for the current node, we can use e.g. [node:title] in formatted text.

Token Entity Render (D7, D8 Issue)

  Provides tokens ([entity_type:render:view_mode_name]) that render full entities using view mode specified.

Advanced Entity Tokens (D7, D8 Issue)

  Through AET you can query the DB for entities using Tokens.
  Examples: [aet:node:1]

Putting it together

In the end you should be able to use [aet:node:5:render:teaser] in your formatted text.


301 redirecting broken links after moving Joomla! to subdomain and giving parent domain to Drupal7?

I would personally follow the steps described below:

1) Use this technique to detect the 404s and issue the redirect

2) Since you don't want to issue the redirect right away, but first check whether the URL exists in the Joomla! subdomain, you can use a function like this to determine whether the URL exists.

3) In order to determine what the URL of the incoming request was (so that you can use it to match it against the Joomla! subdomain), you can use this: $_SERVER['REDIRECT_URL']


There are a couple of ways to do this.

You need to look into the function user_authenticate.

In that function, you will see there is a call to variable_set() that sets the path to the variable password_inc. So, basically you could overide the path of this file, change it so it points to your custom password.inc, in a custom module out of core code.  In that file you would redefine the same functions with your own logic.

There could well be a simpler way of doing this.  I know single-sign on can also be easily done with Drupal 7 as there are functions that make this easily available out of the box. Maybe look at OpenID code or other contrib modules if you choose to use that path.

Good-luck!


Thanks to No Sssweat. His answer works. But I prefer to use sql so here it is.

Using Phpmyadmin navigate to node__body table (or just search it) then in SQL tab, write this:

UPDATE `node__body` SET `body_format`='full_html' WHERE `body_format`='full_html1';

Please notice the following:

in my case, I use different body format in my website so it is not good to change all body_format to full_html.
after the migration I got full_html1, but you may get different body_format.

After execution the SQL command, Clear Drupal cache


Custom CSS for title fields of Articles specified in content creation

For the simplest and quickest implementation I'd suggest you create a array in your THEME_preprocess_node(&$vars) in  template.php:

<?php
$vars['color_cls'] = array(
    'red',
    'blue',
    'yellow'
);
?>

Then you could simply randomly address those in your node.tpl.php and print them as a class in your node, something like this:

<div class="node <?= $color_cls[array_rand($color_cls)]; ?>">

You could also make the color_cls array associative and give them, for example, priorities:

<?php
$vars['color_cls'] = array(
    'critical' => 'red',
    'important' => 'blue',
    'normal' => 'yellow'
);
?>

And ofcourse, then you just style them with your CSS. I'm assuming you do know how to style the classes, so I'll leave out the CSS  bit.


Remote entities versus local entities for third party integration

Personally, I go usually with a caching system within Drupal. How this is implemented really depends on the external system, and how it works, but essentially I'll pull the data from the external source when first requested, and save it within Drupal somehow, whether that be into a node, or a custom entity, or some other data entity unrelated to Drupal entities.

The reasoning behind this is that pulling data from a 3rd party application into Drupal, then delivering it to the user, adds a lot of overhead and processing time. Essentially the browser makes a request, Drupal then starts to build it, makes it's own request (same as a browser) to the 3rd party app, gets the data back, finishes the Drupal page build, and sends it to the browser. This can make for some particularly long page builds. Whereas, if you pull it the first time from the 3rd party app and cache it, it takes longer for that first request, but subsequent requests will already find the data within Drupal, making for faster page loads.

Some things to consider however:

Will the data change every request? If so, then it should not be cached within Drupal.
Will the data never change on any request? If so, then it should be created as either a Drupal entity, or a non-Drupal entity, within Drupal, permanently
Will the data ever be deleted? If so, then it should be cached within Drupal, and periodically checked to see if it's been deleted. If however it must definitely not be accessed after it's been deleted, then it should not be cached within Drupal, else you risk showing the data to the user after it's been deleted.
Can you cache the data safely for a period of time? For example, maybe you can make the Drupal cache expire periodically.
Will you need the data to be accessible as fast as possible, when it's cached? You may want to create a cron mechanism that makes requests to the 3rd party for any new items, caching them immediately so they are ready right away when necessary.

Each 3rd party app is different, so there is not a one-size-fits-all solution to this. The various limitations and requirements need to be researched, with a solution created accordingly.


add block to front page as a new section

Do you have a section available to add the block to or do you need to add a section to put the block in? To add a new section you'll need to edit the .info file for your theme and add the new section definition there. Also you'll need to modify the active page template for your homepage adding a new section to the template file. Then you can define where the block will appear and in the block config you can define that it only appear on the <front> page if that's the desired result.


Add cutom body class when view is not return any results

Might be a little over-kill, but it's the first thing that comes to mind without having to build a custom view in code (which is cleaner imo). I am referencing Views 2 only, might be different in 3.

Create an empty view page, strip it of everything if you'd like, it just needs to exist.
In the view you are using, for the no results behavior, choose to include the empty view.
Using the Context module, add the condition that if the empty view is shown on the page to execute. In the reactions area, add Theme HTML which will allow you to enter in your custom css class to the body tag.


How do I get the current taxonomy term from the plug-in context?

Update 10.05.2019:

There is an unresolved issue about that on drupal.org:
Term route context.

It uses the same solution as in my answer below.

Original answer:

You can create a custom context provider "Taxonomy term from URL".

service definition in MYMODULE.services.yml:

  MYMODULE.taxonomy_term_context:
    class: Drupal\MYMODULE\ContextProvider\TaxonomyTermContext
    arguments: ['@current_route_match']
    tags:
      - { name: 'context_provider' }

The /src/ContextProvider/TaxonomyTermContext.php

<?php

namespace Drupal\MYMODULE\ContextProvider;

use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Plugin\Context\Context;
use Drupal\Core\Plugin\Context\ContextDefinition;
use Drupal\Core\Plugin\Context\ContextProviderInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;

/**
 * Sets the current taxonomy term as a context on taxonomy term routes.
 */
class TaxonomyTermContext implements ContextProviderInterface {

  use StringTranslationTrait;

  /**
   * The route match object.
   *
   * @var \Drupal\Core\Routing\RouteMatchInterface
   */
  protected $routeMatch;

  /**
   * Constructs a new object.
   *
   * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
   *   The route match object.
   */
  public function __construct(RouteMatchInterface $route_match) {
    $this->routeMatch = $route_match;
  }

  /**
   * {@inheritdoc}
   */
  public function getRuntimeContexts(array $unqualified_context_ids) {
    $result = [];
    $context_definition = new ContextDefinition('entity:taxonomy_term', $this->t('Taxonomy term from URL'));
    $value = NULL;
    if (
      ($route_object = $this->routeMatch->getRouteObject())
      && ($route_contexts = $route_object->getOption('parameters'))
      && isset($route_contexts['taxonomy_term'])
    ) {
      if ($term = $this->routeMatch->getParameter('taxonomy_term')) {
        $value = $term;
      }
    }

    $cacheability = new CacheableMetadata();
    $cacheability->setCacheContexts(['route']);

    $context = new Context($context_definition, $value);
    $context->addCacheableDependency($cacheability);
    $result['taxonomy_term'] = $context;

    return $result;
  }

  /**
   * {@inheritdoc}
   */
  public function getAvailableContexts() {
    $context = new Context(new ContextDefinition('entity:taxonomy_term', $this->t('Taxonomy term from URL')));
    return ['taxonomy_term' => $context];
  }

}

The ctools module provides already the condition plugin for entity bundles:ctools/src/Plugin/Condition/EntityBundle.php. You can use it together with the new service.

See also config block visibility by vocabulary, but it not show block access fail(miss context).


You invoke hook_preprocess_username() by rendering the template username. Since D8 has no longer a theme() function the only way to do this is by putting the template in #theme of a render array. In your case multiple times:

public function build() {
  $build = [];
  foreach ($usersFromQuery as $user) {
    $build[] = [
      '#theme' => 'username',
      '#account' => $user,
    ];
  }
  return $build;
}


How can I ensure I retain access to a Drupal site after handing it over to a client?

Yes, as the developer you can control this:

Make sure only you know the (strong) password to the admin (user 1) account.
Make sure Drupal core and modules are up-to-date to mitigate possibility of a security hole that may expose the user 1 login.
Make sure only you have access to the files/database for the site; that way your client can't change data manually that might give them access, or run PHP scripts to do the same.
If you have the PHP filter module enabled, disable it, or at the very least make sure your client can't use it.
Install User One to stop users with the "Administer Users" permission from editing user 1's password.
Make sure no other user has permission to "Administer Permissions" and "Administer Modules" so they can't grant permissions to them selves, disable User One or other critical modules.

There may be some more steps you can/should take, depending on the nature of your relationship/hosting/etc, but those should cover the basics from a Drupal perspective.

I'd strongly recommend being up-front with your client about this. Call it a 'policy' that you have, to ensure a smooth relationship, and position it that your having access to the site for maintenance/updates is actually the right move for them, not just you.


Setting a Variable in PHP for use in rules

The Rules module doesn't seem to provide this feature.

I also tried using a rule set with a variable, but the variable was reset between each action. I tried adding return $minimum_reached at the end of each rule executing PHP code, but it didn't help.

The only way seems to use drupal_static(), if you are using Drupal 7 (e.g. with drupal_static('mimimum_reached', 'default value used when the variable is not set')), or a global PHP variable, if you are using Drupal 6.


Grouping Content Panes in Views For Theming

In Views you can change this by giving the View a name, which will change the display name from views-view--view_id--page_1 to views-view--view_id--my_display_name. You can do this in the Advanced section of a view display config, and changing the 'Machine Name' value.


Node content versioning and compare tool

You can use Revisioning module for comparisons of different revisions:

  Revisioning is a module for the configuration of workflows to create,
  moderate and publish content revisions.

or you can use Diff module:

  This module adds a tab for sufficiently permissioned users. The tab
  shows all revisions like standard Drupal but it also allows pretty
  viewing of all added/changed/deleted words between revisions.


Commerce: how can I execute javascript after a product has been added to the cart?

You should better use Rules here and the related events. The hook you mention (hook_commerce_cart_product_add) is a rules event hook.

Commerce Cart: After adding/removing a product to the cart

Then on the action add with php the js (drupal_add_js()) but if you simply want to show a message there is an action to do this easily.

System: Show a message on the site


I've done something similar by using a template for the taxonomy term based on template suggestions. Personally I prefer writing theming functions though, and example for how to do this for a taxonomy field can be found in template.php of the default Bartik theme that comes with Drupal. Look for bartik_field__taxonomy_term_reference and here is the api documentation for theme_field().

You will need to install the devel module, which will give you a dump of the node object when you are viewing a node.

You will need to either theme the entire node with specific care taken to render the taxonomy how you want from the node object, alternatively you could just theme the actual term reference field (What I first mentioned and the best way imo.) These are instructions on using the devel module.

With that you will be able to dump the array or object relating to the taxonomy term and then create a template or function theming the field to your liking, as far as I know all the information is available there it's just getting it out of the object/array can be time consuming when you are doing it for the first time.

Overall the Drupal Theming Guide covers the finer details in a lot more detail than what can be kept to a reasonable answer here.


How to access commerce_product field of line-items using Rules to flag the Commerce Product?

Below is a possible approach you can use to solve your question. It provides the details about how I was able to have a set of Drupal messages being shown at checkout time, which look similar to this testcase I used (for a cart with 3 line items):

Current line item has label 'USB-BLU-08' and id '17'
Some details about this product: Product ID = 28, Product SKU = USB-BLU-08, Product Title = Storage 1, Product Creator = Hillary.Trump

Current line item has label 'TSH4-BLK-MD' and id '18'
Some details about this product: Product ID = 53, Product SKU = TSH4-BLK-MD, Product Title = Tshirt 4, Product Creator = Donald.Clinton

Current line item has label 'MES1-BLU-OS' and id '19'
Some details about this product: Product ID = 2, Product SKU = MES1-BLU-OS, Product Title = Messenger Bag 1, Product Creator = Pierre.Vriens

To get this to work, I created a custom rule, which also performs a custom Rules Component. Read on for details about them ...

Step 1: Create a Rules Component

Create a Rules Component which looks like so (use the Rules UI to import it in your own site):

{ "rules_perform_an_action_on_a_selected_line_item" : {
    "LABEL" : "Perform an action on a selected line item",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "selected_line_item" : { "label" : "Selected Line Item", "type" : "commerce_line_item" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "selected-line-item" ], "field" : "commerce_product" } }
    ],
    "DO" : [
      { "entity_fetch" : {
          "USING" : {
            "type" : "commerce_product",
            "id" : [ "selected-line-item:commerce-product:product-id" ]
          },
          "PROVIDE" : { "entity_fetched" : { "product_fetched" : "Fetched Product" } }
        }
      },
      { "drupal_message" : { "message" : "Some details about this product: Product ID = [product-fetched:product-id], Product SKU = [product-fetched:sku], Product Title = [product-fetched:title], Product Creator = [product-fetched:creator]" } }
    ]
  }
}

Some details about it:

Parameters: selected_line_item ( = the line item being processed).
Rules Condition: entity (= selected-line-item) has field (= commerce_product).
Rules Actions:

Fetch entity (= commerce_product) by ID (= selected-line-item:commerce-product:product-id).
Show a Drupal message, starting with "Some details about this product ..." (feel free to remove this Rules Action after you finish QA-testing).

Step 2: Create a rule that invokes the Rules Component from Step 1

Create a rule which looks like so (use the Rules UI to import it in your own site):

{ "rules_access_product_fields_at_checkout" : {
    "LABEL" : "Access product fields at checkout",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "commerce_checkout" ],
    "ON" : { "commerce_checkout_complete" : [] },
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
          "ITEM" : { "line_item" : "Current line item" },
          "DO" : [
            { "drupal_message" : { "message" : "Current line item has label \u0027[line-item:line-item-label]\u0027 and id \u0027[line-item:line-item-id]\u0027" } },
            { "component_rules_perform_an_action_on_a_selected_line_item" : { "selected_line_item" : [ "line-item" ] } }
          ]
        }
      }
    ]
  }
}

Some details about it:

Rules Event: After completing the checkout process.
Rules Condition: none.
Rules Action: Create a loop, to iterate over each line item. And for each line item, perform these Rules Actions:

Show a Drupal message, starting with "Current line item has ..." (feel free to remove this Rules Action after you finish QA-testing).
Perform the Rules Component from Step 1 for the current line item being processed.

Step 3: Homework (= your turn)

To actually answer your question, i.e. to flag the product of each line item, you should only adapt the Rules Action in the Rules Component from Step 1. Since you have all data from each line item available at that point, it should be straight forward to tune the Rules Component to fit your needs (i.e flag the product by the current user).


/**
* Implements hook_preprocess_comment
*/
function THEME_NAME_preprocess_comment(&$variables) {
  // Getting the node creation time stamp from the comment object.
  $date = $variables['comment']->getCreatedTime();
  // Here you can use drupal's format_date() function, or some custom php date formatting.
  $variables['created'] = \Drupal::service('date.formatter')->formatInterval(REQUEST_TIME - $date);
  $variables['submitted'] = t('@username commented !datetime', array('@username' => $variables['author'], '!datetime' => '<span class="comments-ago">' . $variables['created'] . ' ago </span>'));
}


There are two facts to keep in consideration about $form['#redirect']:

$form_state['#redirect'], set in a form submission handler, takes the precedence over $form['#redirect'].
$form['#redirect'] and $form_state['#redirect'] are ignored for forms where "#action" has been set by a module. That is what happen with the user login form.
$form['#redirect'] and $form_state['#redirect'] are ignored when $_REQUEST['destination'] is set; its value is instead used.

If you want to redirect a form, and be sure it gets redirected to the path you set, you should implement hook_form_alter() to add a form submission handler that alters $form_state['#redirect']. The module implementing that hook should be executed after other modules that alter $form_state['#redirect'] for that module.
This doesn't have any effect, though, in the last two cases I listed before.


How to display content where author matches connected user?

thanks to kevin

with contextual filters , selecting fixed value:

author == id of connected user


How to check a user's current userpoints balance with Rules?

I finally found a solution:
I created a rule set,where I add two rules:
1)Load the user points
2)Data comparison of user points

After creation of the Rule set,I created the main rule where I added as an action the Rule Set.Done!


Allowing node creation/editing inside other node creation form

If you're not opposed to using Entity Reference module as instead of node reference, there's the Inline Entity Form module that does what you want:

  Provides a widget for inline management (creation, modification, removal) of referenced entities. The primary use case is the parent -> children one (product display -> products, order -> line items, etc.), where the child entities are never managed outside the parent form.


Changing the image path after images were uploaded

If I change the File Directory setting under the Field Settings will this break the paths of the files uploaded prior?

Yes

As i think you need to go a two step process.

Move the images to the new folder.
Update the existing image path in database.

Before moving with any process keep all the backups.

Refer these links which may help you to move

seeking advice on changing file system path after files have been upload

Moving the files directory


How to Identify Fields from Field Collection?

This'll do it:

$entity_type = 'field_collection_item';
$bundle_name = 'field_profile_address';

$info = field_info_instances($entity_type, $bundle_name);

// $info at this point is an array of fields attached to the queried bundle.

From your last 2 questions I think you'd be very interested in the Field Info API docs.


User gets first x units of a product free, then has to pay per unit thereafter

You will probably want to look at the Userpoints API (http://drupal.org/documentation/modules/userpoints) and possibly utilized Rules in conjunction with an eCommerce solution like UberCart.

Or, if you don't need to actually take payment in money at all, there is a Userpoints Contrib module for facilitating points in conjunction with downloads.

userpoints-download
Users lose or gain points when the download attachments (requires site to be configured with private download method).


View test result of BrowserTestBase based test?

Figured it out. Before calling parent::setUp(), I set:

$this->htmlOutputEnabled = true;


How i can add new fancybox-style (theme) for display uploaded image in WYSIWYG / CKEditor with Media module?

Go to configuration, media, image,styles, add style, or directly

http://example.com/admin/config/media/image-styles/add

And add a custom image style.


You can set different themes using hook_custom_theme()

function HOOK_custom_theme() {
  if(arg(0, drupal_get_path_alias()) == 'compsci') {
    return 'theme_machine_name';
  }
}

When you create menus, they will create a block. You can enable the menu blocks on a per-theme basis.


How to override version of drupal-library (JavaScript library) included with composer merge-plugin?

But unsuccessful in that it does not have priority over the one defined in webform:

There is a way, just define custom repository before Drupal packages repository .
Change your composer.json to
   "repositories": {
        "jquery.inputmask": {
            "type": "package",
            "package": {
                "name": "jquery/inputmask",
                "version": "5.0.6-beta.45",
                "type": "drupal-library",
                "extra": {
                    "installer-name": "jquery.inputmask"
                },
                "dist": {
                    "url": "https://github.com/RobinHerbots/jquery.inputmask/archive/5.0.5.zip",
                    "type": "zip"
                },
                "require": {
                    "composer/installers": "~1.0"
                }
            }
        },
       "drupal": {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        }
    },


error Refused to execute script, because its MIME type ('text/html') is not executable

You are asking the wrong question....

When you look at your page's source code, you'll see this:

<link rel="stylesheet" href="/alex/lkch/?ojqox6" media="all" />
<link rel="stylesheet" href="/alex/lkch/?ojqox6" media="all" />
<link rel="stylesheet" href="/alex/lkch/sites/default/files/css/css_Z5jMg7P_bjcW9iUzujI7oaechMyxQTUqZhHJ_aYSq04.css?ojqox6" media="print" />

The last one is a real CSS file. The first two are not (those link to your front page). So your browser attempts to load a stylesheet, but is receiving your front page instead. That is what is triggering the error; The browser expects CSS and is instead served HTML.

The real question is, where do these 2 lines come from... And that is hard to tell, since everything in Drupal can do that.

Things you can try;

Disable CSS aggregation in Administration > Configuration > Development (you want to enable this once you go live)
Disable all non core modules (if any)
Try a different theme

It could be something coming from a custom template as well.


Drupal Commerce - Add to Cart form tweaks

You can add the rendered field into the add to cart form like this:

function mytheme_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state, $form_id) {
  $product = $form_state['default_product'];
  $view_mode = $form_state['context']['view_mode'];
  $form['price'] = field_view_field('commerce_product', $product, 'commerce_price', $view_mode);
}


Easiest way to export specific user-generated content?

Views module is the only solution which makes your task very easy.

1.Simply create a view and add the necessary fields you want to export.

2.Add a display (data export).

3.In DATA EXPORT SETTINGS name your path with .csv extension example data.csv

Finally call the path on your browser. That's it

Another difficult way is to write queries and then create a php code to export the result to csv


Using drupal login system for another platform

The Services module provides an HTTP REST API for authentication (amongst other things). So it should be easily usable to let a remote/separated site re-use your Drupal web site user authentication. The following code comes from its documentation and illustrate how to use it for user authentication. The returned user object will contain the session name and id to use in future REST request if more data from the Drupal are needed (for instance to retrieve user profile or content).

// REST Server URL
$request_url = 'http://your-drupal/rest_server_endpoint/user/login';

// User data
$user_data = array(
  'username' => 'user_name',
  'password' => 'user_password',
);
$user_data = http_build_query($user_data);

// cURL
$curl = curl_init($request_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/json')); // Accept JSON response
curl_setopt($curl, CURLOPT_POST, 1); // Do a regular HTTP POST
curl_setopt($curl, CURLOPT_POSTFIELDS, $user_data); // Set POST data
curl_setopt($curl, CURLOPT_HEADER, FALSE);  // Ask to not return Header
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_FAILONERROR, TRUE);

$response = curl_exec($curl);
$http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);

// Check if login was successful
if ($http_code == 200) {
  // Convert json response as array
  $logged_user = json_decode($response);
}
else {
  // Get error msg
  $http_message = curl_error($curl);
  die($http_message);
}


The last three arguments you are passing to db_query() are wrong; you should merge them in an array, and pass that instead of them.

block_list() contains the following code:

$result = db_query(db_rewrite_sql("SELECT DISTINCT b.* FROM {blocks} b LEFT JOIN {blocks_roles} r ON b.module = r.module AND b.delta = r.delta WHERE b.theme = '%s' AND b.status = 1 AND (r.rid IN (" . db_placeholders($rids) . ") OR r.rid IS NULL) ORDER BY b.region, b.weight, b.module", 'b', 'bid'), array_merge(array($theme_key), $rids));

Similarly, blogapi_mt_validate_terms() contains the following code:

  $term_list = array_unique($node->taxonomy);
  $params = $term_list;
  $params[] = $node->type;
  $result = db_query(db_rewrite_sql("SELECT t.tid, t.vid FROM {term_data} t INNER JOIN {vocabulary_node_types} n ON t.vid = n.vid WHERE t.tid IN (" . db_placeholders($term_list) . ") AND n.type = '%s'", 't', 'tid'), $params);

In your specific case, your code should be similar to the following one:

$tax_ids = array(134, 139);
$placeholders = db_placeholders($tax_ids);
$args = array_merge(array($user->uid), $tax_ids, array($displays_count));

/**
 * Alternatively the previous three lines could be replaced by the following ones:
 * $args = array(134, 139);
 * $placeholders = db_placeholders($args);
 * array_unshift($args, $user->uid);
 * $args[] = $displays_count;
 */

$images = db_query("SELECT n.nid, n.title, f.filepath,
  cti.field_iv_source_name_value AS source, bf.nid AS flagged
  FROM node n
  JOIN content_type_imagevault cti ON n.nid = cti.nid
  JOIN content_field_att_file cfaf ON cfaf.nid = n.nid
  JOIN files f ON cfaf.field_att_file_fid = f.fid
  JOIN term_node tn ON tn.nid = n.nid
  LEFT JOIN betterflag bf ON (n.nid = bf.nid AND bf.uid = %d)
  WHERE n.type = 'imagevault' AND tn.tid IN ($placeholders) AND n.status = 1
  ORDER BY n.created DESC LIMIT %d", $args);


Passing Information to Drupal Referenced Entities before Render

This works as designed. The referenced node can have multiple parents, but is only processed once and then cached.

A slighly different approach would be to use the context to check inside the referenced node, which parent node is displayed as page content.

Load the basic node with a route match in preprocess of the referenced node. See this question from today on blocks, which can be used in the node preprocess hook in the same way:

How to access field values from a custom block

You would also have to adjust the cache settings of the referenced node, see the comment in the linked answer.