About

  I realize that all the (working) pages are called with "/?q=node/somthing" instead of "/node/something"

To make your path aliases be human readable, pls check if Path module is enabled and then go to Administration » Configuration » Search and metadata  » Clean URLs and check "Enable clean URLs" checkbox. If it is not editable, you should ensure that PHP Rewrite mod is enabled.

To have your content displayed in diffrerent languages correctly you need:
1) Have Locale and Content transpation modules enabled. Both of them are Core modules.
2) Goto Home » Administration » Configuration » Regional and language » Languages and add the languages you need. Ensure that all required langs have ENABLE checkbox chacked. Also ensure that you have the correct Path prefix language codes (can change is edit Language) for each lanf, like "en" (without quotes) for English, "fr" for French etc.
3) Goto Administration » Structure » Content types » Your_content_type (that one you're using for creatinf translatable content) and ensure that in *Publishing options" tab "Multilingual support" is set for "Enabled, with translation".
4) Now create your piece of content and in creating content form set Language select box as "English" and set the URL alias as "policy-1" for example. Save it. Now you should see a "Translate" tab (near View/Edit tabs). Press it, select the lang you need and follow add translation link.

Tip: I don't know how your theme looks, so i'm not sure if you have a lang switcher for users or lang links displayed when viewing transled content. But if you use the same alias for all your translation, you can easily check if it works or not. For example if you set "policy-test" as Path alias for all transleted versions of your test node, you should be able to visit it via [yoursite]/[lang-prefix]/policy-test, i.e. via [yoursite]/en/policy-test or [yoursite]/fr/policy-test etc.

P.S. you don't need to use your lang prefix in path aliases for any language. Drupal will do it itself.


I've given this problem some thought (actually began writing code for a D7 live preview), and as it happens I simply don't think live preview is that simple in Drupal.

Live preview on SE.sites is efficient because there are no AJAX requests going on for rendering the preview. In a nutshell SE.sites merely clone the text from the editor textarea into the preview div, where CSS classes are applied to it. In reality there is more processing happening in the background as the text that you enter must be converted into real markup (ie, when using lists).

In Drupal however there can be a lot of pre-processing of text, depending on what modules you have enabled. For instance, take the <!--break--> control sequence (which is part of core behavior, btw). Does that really mean something in HTML? No, it must be preprocessed by Drupal into teaser and full body text snippets; take the CKEditor and the IMCE modules for example, they also depend on preprocessing text to translate special markup for images into actual <img> tags.

What that means is that in order to have a live preview that is faithful to it's final state, you must run whatever text you enter through a number of hooks, preprocessors, renderers and what have you. Else your live preview will not represent the final product. Therefore, having a faithful Live Preview in Drupal would mean sending an AJAX request to the back-end every time the editor in the front-end is updated. And then, you can ask yourself the question? Is this scalable? That would probably depend on your use case. If you want Live Preview for a site with a big editorial team (think www.nowpublic.com, a Drupal site), the answer would probably be no. But maybe if it is for a small site, with a few visitors or editors, then the answer would be maybe, but it still raises performance concerns.

So taking those points into consideration, what kind of preview would you be looking for? Slow & Faithful or Fast and Unfaithful?


Custom currency in Drupal Commerce Shopping cart summary views

I manage to do this using Views PHP module. The variable $results contains the array of all the data.

For "Shopping cart form" and "Shopping cart summary" view you have to add to footer this to the output value of Global: PHP:

<?php
$amount = 0;
foreach ($results  as $result) {
$amount = $result->field_commerce_total[0]['raw']['amount'] + $amount;
}
$converta = commerce_multicurrency_conversion($amount, 'HRK', 'GBP');
$formatcu = commerce_currency_format($converta, 'GBP');
echo $formatcu;
?>

To the "Commerce add to cart confirmation" you haw to ad to fields Global: PHP output code:

<?php
$amount = $data->field_commerce_total[0]['raw']['amount'];
$converta = commerce_multicurrency_conversion($amount, 'HRK', 'GBP');
$formatcu = commerce_currency_format($converta, 'GBP');
echo $formatcu;
?>


Add A Redirect Link In Webform Submit Button

This is duplicated question.

But here is the answer
If i had to redirect the users after submission than i would go to the already created webfrom, click on

Webform(on top of the form)->Form settings

After scrolling down a bit you will see Redirection location

Choose Custom URL and enter your Internal URL www.mysite.com/foo

Thats it you are done.


Have you tried theme_form_element ?

  Returns HTML for a form element.

This hook is used to alter the thme of form element in Drupal.

Check theme_field as well.

How to theme form element in Drupal 7


Taxonomy block in views which show the description of the children taxonomy, selected by two exposed filters

One way to do this is possible with contextual filters.

Add a contextual filter based on term name
Add a relationship to parent term.
Add another contextual filter on term name, but this time use the parent term from the relationship.
Tweak the settings (override number of items to show, probably remove the count from the item list, and switch to jump menu instead of regular list if you want a dropdown display.)


Kropot,

Have you tried views contextual filters?

Create a block view.
Add a Contextual filters with Content: Has taxonomy term ID.
defalt value: Taxonomy Term ID from URL
Add the fields to display.
Add the filters.

Deepak


I'm not sure if there's a shortcut for that, but if not the steps are still quite minimal:

Sub-class the \Drupal\user\Entity\User class in a custom module, and override its label() method:

mymodule/src/Entity/User.php

namespace Drupal\mymodule\Entity;

use Drupal\user\Entity\User as CoreUser;

class User extends CoreUser {

  public function label() {
    return 'something new';
  }

}

Implement hook_entity_type_alter() to set the class for the User entity type:

function MYMODULE_entity_type_alter(&$entity_types) {
  $entity_types['user']->setClass(\Drupal\mymodule\Entity\User::class);
}

Rebuild the cache


It's delta of block.
You can receive it via this code:

$delta = facetapi_hash_delta(facetapi_build_delta('SEARCHER@MACHINE_NAME_OF_SEARCH_INDEX', 'block', 'MACHINE_NAME_OF_FACET'));

Example:

$delta = facetapi_hash_delta(facetapi_build_delta('search_api@fr_node_index', 'block', 'field_price'));


How to remove h1 tag from Drupal Garland theme in the header

if ($logo || $site_title) {
        print '
';
        if ($logo) {
          print '';
        }
        print $site_html .'
';
      }

These are the lines 39-45 in Garland Themes page.tpl.php.
This is probably the h1 tag you're talking about. If you want to change it to div it should look like this afterwards:

if ($logo || $site_title) {
        print '
';
        if ($logo) {
          print '';
        }
        print $site_html .'
';
      }


How can I add variables from a preprocessor function to be used in an unformatted view template?

Your problem is that the output for the view is built up from the inside-out.  So, the views-view template already has the processed results from the views-view-unformatted template.

You should just be able to implement a template_preprocess_views_view_unformatted(), and do a manual check:

function mytheme_preprocess_views_view_unformatted(&$variables) {
  $view = $variables['view'];

  if ($view->name == 'viewname') {
    $variables['foo'] = 'bar';
  }
}

I don't typically use unformatted output, but I do it somewhat often at the field level.


I wrote a custom module to do this very thing. I use Pathauto to automatticly create aliases for my nodes, in the form of questions/123/title-of-node-here. The following code creates a /custom404 page. I configure my "Default 404 (not found) page" (in Site information) to custom404. The module picks the node id out of the url, checks for its existence, and then redirects to node/%nid. Finally, the Global Redirect module will take over and redirect the user to the canonical url.

/**
 * Implements hook_menu().
 */
function custommodule_menu() {
  $items = array();

  $items['custom404'] = array(
    'title' => 'Page not found',
    'access callback' => TRUE,
    'page callback' => 'custommodule_page',
    'type' => MENU_LOCAL_TASK
  );

  return $items;
}

function custommodule_page() {
  $path = _custommodule_request_path();
  $parts = explode('/', $path);

  // The following lines matche a path alias to a content type
  // map /questions/%nid/%title to the 'question' content type
  _custommodule_match_nid($parts, 'questions', 'question');
  // map /websites/%nid/%title to the 'website' content type
  _custommodule_match_nid($parts, 'websites', 'website');

  drupal_set_title(t('Page not found'));
  return ' ';
}

/**
 * custommodule_request_path() is copied from globalredirect_request_path
 */
function _custommodule_request_path() {
  if (isset($_SERVER['REQUEST_URI'])) {
    if (isset($_REQUEST['q'])) {
      $path = $_REQUEST['q'];
    }
    else {
      // This is a request using a clean URL. Extract the path from REQUEST_URI.
      $request_path = strtok($_SERVER['REQUEST_URI'], '?');
      $base_path_len = strlen(rtrim(dirname($_SERVER['SCRIPT_NAME']), '\/'));
      // Unescape and strip $base_path prefix, leaving q without a leading slash.
      $path = substr(urldecode($request_path), $base_path_len + 1);
    }
  }
  else {
    // This is the front page.
    $path = '';
  }

  // Under certain conditions Apache's RewriteRule directive prepends the value
  // assigned to $_GET['q'] with a slash. Moreover we can always have a trailing
  // slash in place, hence we need to normalize $_GET['q'].
  $path = ltrim($path, '/');

  return $path;
}

function _custommodule_match_nid($parts, $path_root, $node_type) {
  if (count($parts) >= 2 && $parts[0] == $path_root && ctype_digit($parts[1])) {
    $id = $parts[1];
    $args = array(
      ':nid' => $id,
      ':type' => $node_type,
    );
    if (db_query('SELECT count(nid) FROM {node} WHERE nid = :nid AND type = :type AND status = 1', $args)->fetchField()) {
      if ($alias = drupal_get_path_alias('node/'.$id)) {
        _custommodule_goto($alias);
      }
    }
  }
}

function _custommodule_goto($path) {
  $options = array(
    'fragment' => '',
    'query' => NULL,
    'absolute' => FALSE,
    'alias' => FALSE,
    'prefix' => '',
    'external' => FALSE,
  );
  unset($_GET['destination']);
  drupal_goto($path, $options, 301);
}


How can I prevent anonymous users from accessing taxonomy pages?

Don't need to force using panels.

Having better solution to set permission for your taxonomy pages by code.

Default taxonomy page permission is 'Access content'.

Override that permission in your own by custom module.

Using hook_menu_alter() to change permission

Sample:

function [MODULENAME]_menu_alter(&$items) {
  $items['taxonomy/term/%']['access arguments'] = array('custom permission');
}

Set that custom permission in your hook_perm().

sample :

function [MODULENAME]_perm() {
  return array('custom permission');
}

Clear your site cache once.

Then Goto admin/user/permissions

Set permission by role.


With debug tag (devel module is mandatory) we can print the raw sql.

$query = \Drupal::entityQuery('foo')->condition('bar', 'xyz')->addTag('debug');
$ids = $query->execute();


How to get a list of all Groups sorted according to latest comment created on any of the Group Content belonging to that Group?

I have not tested a query as I don't have data to test.But I hope the following query will work for you.I am matching comment created date with fetched latest comment by using sub query.

SELECT DISTINCT   group_view.nid AS group_nid,
                      group_view.created_date AS group_created_date,
                      discussion.nid AS discussion_nid,
                      comment.created AS comment_created_date,
                      comment.created_date AS comment_created_date
      FROM `node` AS group_view
          LEFT JOIN `og_membership` AS group_map
              ON group_view.nid = group_map.gid
          LEFT JOIN `node` AS discussion
              ON group_map.etid = discussion.nid
                 AND group_map.entity_type = 'node'
          LEFT JOIN `comment` AS comment
              ON discussion.nid = comment.nid
      WHERE group_view.type = 'group' and (comment.created=SELECT max(c.created) AS latest
      FROM comment c
      WHERE  (c.nid = node.nid)
      GROUP BY c.cid)


Remove the strict warnings from being shown

From the link :

  If you're going to hack core, a much better solution is to properly
  fix the error handler. Add this line to the top of the
  drupal_error_handler function in includes/common.inc:

  if ($errno == E_STRICT) { return; }


How can I render my output in a series of DIVs rather than an "item_list"?

As far I understood you want render the following code in multiple <divs>.

$page_array['photo_gallery_arguments'] = array(
  '#title' => t('All photos from ever'),
  '#items' => $items,
  // Theme hook with suggestion.
  '#theme' => 'item_list',
  '#type' => 'div',
);

Replace it with the following code.

   foreach($items as $item_key => $item) {
     $page_array['photo_gallery_arguments'][$item_key] = array(
       '#type' => 'container',
       '#attributes' => array(
         'class' => array(
           'my-class-' . $item_key,
         ),
       ),
     );

     $page_array['photo_gallery_arguments'][$item_key]['content'] = array(
       '#type' => 'markup',
       '#markup' => $item,
     );
   }

Or use the following code.

   foreach($items as $item_key => $item){
     $page_array['photo_gallery_arguments'][$item_key] = array(
       '#type' => 'markup',
       '#markup' => '
' . $item . '
',
     );
   }

Alternatively, you can use the following code.

   foreach($items as $item_key => $item){
     $page_array['photo_gallery_arguments'][$item_key] = array(
       '#type' => 'item',
       '#markup' => $item,
     );
   }

You can find more information about rendering arrays, and Form API.


Use Taxonomy CSV import/export module. I used it once, works great...


How can I ensure a referenced entity is cached separately per paragraph?

So the easiest option likely is to just disable caching completely for the embedded entities.

In hook_entity_view(), unset $build['cache']['keys']. They are then still cached as part of the paragraph render cache, but don't have their own cache entry anymore.

To avoid not caching them when they are shown somewhere else, you should use a special view mode when you integrate them in paragraphs and only disable caching for that.

Note that you could also set max-age = 0 but that means "this content must not be cached at all", that information would bubble up to the paragraph and host entity and none of those would be cached anymore. That's not what you want.

Or you could change your approach and apply that color through a class that is set on the paragraph level, without changing the HTML of the embedded entity. Doesn't work for everything, but for a simple color change, that is likely easier to implement.


removing menu block title causing problems

Please try to put in the block title

<none>

instead of space


You need to pull the node object out of the variables array.

$node = $variables['node'];

In certain preprocess functions this may not be available, so you can try the request service:

$node = \Drupal::request()->get('node');

The object must be of type Node. Therefore:

$node->getType() == 'events'

As Berdir mentioned, you should check and ensure that $node is a valid Node object to see if it is an instance of NodeInterface before operating on it. This will prevent fatal errors in the event that $variables['node'] is actually a node and not some ad-hoc variable created in code from which you can't call methods on:

Example 1 (using $variables array):

if (isset($variables['node']) && $variables['node'] instanceof NodeInterface) {
  $node = $variables['node'];
  $title = $node->getTitle();
  $type = $node->getType();
  // more code...
}

Example 2 (using the request):

$node = \Drupal::request()->get('node');

if (isset($node) && $node instanceof NodeInterface) {
  $title = $node->getTitle();
  $type = $node->getType();
  // more code...
}


how to use Views Datasource to export view in JSON

You can achieve this by combination of two modules. Views data export and Views data export - JSON support. Once you install these two modules create a view as data export and select format as JSON.


There might be other ways, but I have found that mailsystem and mimemail modules have to be installed to send email with attachment. So install these two modules first.

Then implement hook_mail to pass attachment to $message

/**
 * Implements hook_mail().
 */
function mymodule_mail($key, &$message, $params) {
  $message['subject'] = $params['subject'];
  $message['body'][] = $params['body'];

  // Add attachment when available.
  if (isset($params['attachment'])) {
    $message['params']['attachments'][] = $params['attachment'];
  }
}

There are two ways to add attachment, you can either pass filecontent or filepath when adding an unmanaged file as attachment (not recorded in DB) or pass file object when adding an managed file.

When adding unmanaged file:

$attachment = array(
  'filepath' => $filepath, // or $uri
);

or

$attachment = array(
  'filecontent' => file_get_contents($uri),
  'filename' => $filename,
  'filemime' => 'application/pdf'
);

By using filecontent way, you probably will get two php errors by Jan 08, 2015 including

Warning: is_file() expects a valid path
Warning: realpath() expects parameter 1 to be a valid path

When adding managed file:

$attachment = file_load($fid);

Then send email by:

$params = array(
  'key' => 'my_email_template',
  'to' => 'test@example.com',
  'from' => 'test@example.com',
  'subject' => 'Test email',
  'body' => 'test',
  'attachment' => $attachment
);

drupal_mail('mymodule', $key, $to, $language, $params, $from);


Composer download Drush 9 - But conflict errors

When you request composer require drush/drush:9.*, you are telling Composer that you want the latest stable release of Drush on the 9.x branch.  However, Composer considers dev, alpha, beta and even RC releases to be unstable.  These releases can be downloaded in one of two two ways:

Create a composer.json file, manually add the release designation you want (e.g. 9.*), set the minimum stability to dev or alpha, or some other applicable value, and then run composer install (or composer update, if you already have a composer.lock file).
Explicitly request the version you want -- e.g. composer require drush/drush:9.0.0-alpha1, or ``composer require drush/drush:dev-master`.


You can apply css styles from php. Use the drupal_add_css() function

<?php
drupal_add_css('#banner { background: url("../images/banner.jpg") no-repeat fixed }',$option['type'] = 'inline');
?>


Newly created field not being added to entity

You can't add this dependency, it's bundle configuration which you don't have and don't need in a bundleless entity. For testing better add a user instead of a node field or check the already pre-installed field.field.user.user.user_picture.yml
To create the field config you only need to specifiy the field storage and the bundle (for a bundleless entity this is the entity id). The other values are then extracted from the storage config:
$storage = $this->entityTypeManager->getStorage('field_storage_config')->create($field_storage_values);
$storage->save();

$field = $this->entityTypeManager->getStorage('field_config')->create([
  'field_storage' => $storage,
  'bundle' => 'my_entity_id',
]);
$field->save();

BTW part of the field UI is also the configuration of display modes. You need to add the new field as component at least to the default view and form mode, so that the new field is visible. See How to change the entity view display configuration programmatically?


How to grant permissions for some role to execute custom Rules Components?

If you've enabled "Action permissions" check the role has permission to "Execute [action]" in Admin > People > Permissions


Why does entity_metadata_wrapper does not preserve node's custom URL while updating other fields?

In case someone else face the same issue, I come across the following

  Pathauto uses the following logic (listed by priority) to determine if
  the Pathauto checkbox should be checked when editing a node:

  If the node is a new node, it defaults to having an automatic alias.
  If the node is not a new node: If the node does not currently have an
  alias, it assumes that the node was manually un-aliased, so it will
  default to not have an automatic alias. If the node's current alias
  matches the alias that Pathauto would generate based on the pattern,
  then it will default to checked. Otherwise, the checkbox will default
  to be unchecked. If you are using the Pathauto persistent state
  module, then once you save a node, the checkbox will remain checked or
  unchecked regardless of the logic above until you check or uncheck it
  later.

  If you have content you've created before installing Pathauto that you
  would like to ensure that the checkbox is checked whenever you edit
  them, then you should use the 'Update URL alias' bulk action on your
  content listing admin page (admin/content/node).

  If you are saving changes to nodes automatically using node_save, you
  need to specify $node->path['pathauto'] = FALSE; in Drupal 7 or
  $node->pathauto_perform_alias = FALSE; in Drupal 6 (see
  http://drupal.org/node/1179988) in order to stop pathauto overwriting
  any custom paths you might already have for the node.

In Drupal 6

$node->path['pathauto'] = FALSE;

in Drupal 7

$node->pathauto_perform_alias = FALSE;


How to properly inject services into other services

Alright, I think I figured it out. It should look something like this:

I couldn't find the service name anywhere for MenuTreeParameters so it's omitted in the examples for now.

I setup my menu service in rest_api.services.yml

services:
  rest_api.menu_service:
    class: Drupal\rest_api\Services\MenuService
    arguments: ['@path.alias_manager', '@menu.link_tree']

And created my service:

namespace Drupal\rest_api\Services;

use \Drupal\Core\Menu\MenuLinkTree;
use \Drupal\Core\Path\AliasManager;
use \Drupal\Core\Menu\MenuTreeParameters;

class MenuService {

  protected $aliasManager;

  public function __construct(AliasManager $aliasManager, MenuLinkTree $menuTree) {
    $this->aliasManager = $aliasManager;
    $this->menuTree = $menuTree;
    $this->items = array();
  }


Add an item to a list for Rules and References

The "add an action" form says: "To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')."

My field was in the data selector but the item was not added by the action.

I changed the action to a rule with a condition "entity has field" as requested, the field being the one I wanted to add a value to. Then I recreated the action in the actions area.

This was the solution for me. Hope this helps.


How to fix the PDOException shown after upgrading to Drupal 7

If you manually edited the schema_version column, you practically avoided Drupal would execute the necessary updates, and add the necessary fields in the database tables. That is why you get that error message.
How many updates you blocked depends on the number you set for schema_version; if you set it (for example) to 8000, then you avoided Drupal would execute all the updates.

To fix it, you can only restore the values schema_version had and run again update.php. This is not 100% error free: In some cases, executing the same update twice could cause an error that would stop the update process. It would be much better if you would restore the database from a backup you have from before manually editing the system table; in that way, you would be sure that executing update.php would not cause any runtime exception that would interrupt the update process.
The only alternative I see is executing the updates that were not executed, but you should have to track which updates were not executed or were executed but stopped because some error. It is also difficult because some updates need to be executed in a specific order; see system_update_dependencies() that defines the order for some of the updates for the System module, or node_update_dependencies() that does the same for the Node module. In short, you should write code similar to the one used by Drupal to update modules, adapting it to your case.


Best practice: needs private and public contents of same type

Perhaps the deciding factor is to determine if the private users need to see the private content seamlessly integrated into the public content.  If they do solutions 1 & 2 seem like they might work.  If, on the other hand, private content can or should be viewed separately from the public materials, separating into two subdomains (or even subsites) with different access rules would be much easier.


I just tested this and got the same problem as you.

I found the solution you need to check mark limit to selected items.

If you don't have the Limit list option, check marking the expose operator also fixes it. You would then have to use css to hide the expose operator if you don't want it.


Address field tokens and country display

The addressfield_tokens module extends the addressfield module by adding full token support. It also adds some convenient addressfield formatters and provides a webform addressfield integration.

Addressfield Token Module


When is it appropriate to create an entity instead of a new content type?

It's not so much about what the benefits are but more about what's appropriate for a particular situation like you've said. You can represent pretty much anything with a node and for 99% of situations (as I've found at least) you won't need to implement custom entity types.

I always think of the taxonomy_term entity type as a good example of why not everything should be a node/content type:

A taxonomy term is essentially for grouping together different entities and as such doesn't require the same functionality as a node. While you could theoretically use a content type to perform this functionality (with perhaps a node reference field), a taxonomy term doesn't need to do the same thing as a node so it doesn't really make sense to do so. The same can be said for the user and taxonomy_vocabulary entity types.

So a taxonomy term is created as a separate entity and is programmed to do only what it needs to, while still getting the benefits of being able to have fields attached, etc.

I think the simple answer is that when a node/content type doesn't do what you need it to, or it's just a massive amount of overkill/overhead for very little benefit, then you should choose to write a custom entity.

This is only based on my personal experience; I'd be interested to hear what someone directly involved with Drupal core development had to say about this.


I want to do something after users voted

You're most probably after VoteAPI integration with Rules: Voting Rules

It enables you to configure actions to occur when a user submits a vote, when a user deletes a vote, and when the results of a vote are calculated. Currently, Voting Rules supports votes on nodes, users, and comments.


What would be the reason for a registration page to hangs after submit?

Check memory_limit for your Drupal instance.

On settings.php add this line

ini_set('memory_limit', '128M');


Running a function before a View executes

You might be interested in a similiar kind of question I answered here:

How do you customize the title of an RSS feed created by Views RSS?

I would just set the view size to 10 always. And then use array_unshift() as I did in that reply to "prepend" the new item Object to the front of the view results array, if your Twitter call return its 1 item of content. Or else you just let the original 10 come from Views.


Body classes still showing 'page-node-#' instead of title or menu word

I noticed that your function is named THEMENAME_preprocess_html(). If you don't have THEMENAME replaced with the name of your theme, the function won't be called and your classes won't get added.


Getting the error "No active batch." when running any batch

If you are using the Secure Pages module, you have apply the patches provided for that module.

As I am using the Secure Pages module, that fixed my problem.

  Steps to install Secure Pages 7.x-dev

  Set $conf['https'] = TRUE; in settings.php.
  Apply these two patches:

  #961508-21: Dual http/https session cookies interfere with drupal_valid_token()
  #471970-13: DrupalWebTestCase->getAbsoluteUrl should use internal browser's base URL


You need to clear drush cache.  I have seen this same thing before, where I try to do a drush action from a module and am told the action is not available.  Then a drush pm-list | grep "module" shows me it is enabled.

drush cc drush
drush en sar

As we say around my office daily, "When in doubt, clear cache."  If this is not working, then take a step back and verify your assumptions.

We assume the download succeeded, so we should be able to find the module in a "not installed" state.  Verify with drush:

drush pm-list | grep "sar"

We assume drush handled the download properly, try again with another folder.  Verify with drush:

drush dl sar --destination="sites/all/modules"

Solution:

I assumed, since you were asking about enabling, that this was a site module.  After downloading it on my local system I see that this is a drush command package, and that [user]/.drush/sar is correct.  Verify the module does not need enabled and is already working with:

drush help sar


Adding 'lang' attribute to language links in template.php

I found the solution:

function MYTHEME_links__locale_block(&$vars) {

  foreach($vars['links'] as $language => $langInfo) {
    $name = $langInfo['language']->native;
    $lang = $langInfo['language']->language;
    $vars['links'][$language]['title'] = $name;
    $vars['links'][$language]['attributes']['xml:lang'] = $lang;
    $vars['links'][$language]['attributes']['lang'] = $lang;
    $vars['links'][$language]['html'] = TRUE;
  }
  $content = theme_links($vars);
 return $content;
}


Why does Drupal 7 prefer CSS @import rules to  tags?

Don't use @import to import css files:

  @import is used only in non-CSS aggregation mode. This is done to workaround IE limitation with the number of  tags.

This should explain the reason and how to get rid of it. Any production site should use CSS aggregation, and not have @import.


In Drupal 8 and 9, use t ( or trans) filter in twig element in your Global: Custom text”.
for example, create a Global: custom text field and paste
 {{ 'this text will be available in translate interface'|t }}

Ref for reading more: https://www.drupal.org/docs/theming-drupal/twig-in-drupal/filters-modifying-variables-in-twig-templates


/user/login exists by default; you could use that.


<?php
$datetime1 = date('d-M-Y', strtotime(value1));
$datetime2 = date('d-M-Y', strtotime(Value2));
$interval = date_diff($datetime1, $datetime2);
$result = $datetime1 . ' ' . $interval;

result will be
1-Jan-2013 +5d


Prevent clubbing of server side error messages on top

You can disable that module to return to the more traditional line-by-line error output globally, or hook into it programatically form-by-form:

function MODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'foo_form') {
    $form['#disable_inline_form_errors'] = TRUE;
  }
}


Have Views based Taxonomy Term page use term description for title

There is an incompatibility to use Description as Title, at least if you use the default settings. Description is a long text field and it possibly contains HTML. Titles are supposed to be plain text only, they are usually "cleaned" against HTML in them.

That said, if you think you have a case where this makes sense, you can try to use the field tokens for the Taxonomy term Description field. But you'll have to make a lot of changes to the Views if you want to do it through the interface and not custom code.

"Taxonomy term" Views is of the "Content" type, not "Taxonomy term" type, so you don't get taxonomy term info out-of-box in there. You have to add a Relationship towards the term in order to get the term info to be available in Views.

So first add the Relationship for your Taxonomy reference field, it will be under "Content" Category, named something like "Taxonomy term referenced from field_tags". You'll probably want to Require it, to exclude all nodes that don't have that taxonomy tag.

Once you have the Relationship you will be able to add the Field "Description" to your views (change the Format to "Fields" if it's "Content"). You can Exclude it from display if you don't want it in the Views results. And recreate the "Content" Format with Fields, add the node Title field etc.

The Title in the "Taxonomy term" Views isn't coming from the Views Title field, it's coming from the Contextual filter "Override title" option. There is also the Header option rendering the Taxonomy term which shows the linked term name and its description below it.

So if you want to change how that behaves, that's where you'll have to make the changes. I don't think you'll be able to have the Description token work in the default "Has taxonomy term" Contextual. You'll have to remove it and add the Contextual for your tags field, possibly for the Description field (I haven't tried it). Then set the title override on that Contextual and adjust the Views Header option.

Since your Contextual is limited to one field, and no longer covers entire site's Taxonomy, you have to be careful to recreate other Taxonomy pages (for other Vocabularies) if you need them. It's always a good practice not to work on the original "Taxonomy term" Views, instead keep it intact and disabled for future reference, and Duplicate into a new Views and work on the Duplicate.


Easiest way to hack Drupal 6.22 installation for security audit

The question you're asking is pretty impossible to answer. If you know Drupal and/or web security then you'll know the answer already. If you don't then the answer is too long to put into a Stack Exchange comment.

Here are some articles about how I have gained knowledge of web application security and how I perform a security audit of a Drupal site:

How to become a Drupal security expert
Steps to a Drupal Security Review

I agree with Ivan Alfaro that the security_review module is a good start. Many of the elements that the security_review module audits can be audited from outside a site, so you could look at what it does and see if you can do similar things.


Hide the number of products on the shopping cart when it is empty

Could you not add an if around the  tag containing the {{ count }}?

since you are using Drupal 8, you can use Twig filters. One way could be like below.

{% if count > 0 %}
    {{ count }}
{% endif %}


Programmatically created nodes are not appearing under table 'nodes'

The $node object you pass to node_save() wouldn't get it's nid member populated unless the node has been successfully saved to the node table in the database.

The auto-increment ID actually comes from the database table so if the $node object has a nid, you can pretty much guarantee the record has been successfully inserted into the table.

Make sure that the software you're using to view the table doesn't have some sort of paging turned on, meaning that only the first x number of records are actually showing in your results. Most MySQL UI software (PHPMyAdmin, Navicat, etc.) limit the number of results you see in a table by default; if you want to see more you need to change the setting.

If you want to do a quick check run the following query on your database:

SELECT MAX(nid) FROM node

Note down that number, then run your code again. Finally run the above query one more time. If the nid you get the second time around is greater than the one from the first time round, you know the record has definitely been added to the database.


colorbox custom caption via field collection

One needs to enable the entity API / entity token (included in Entity API) modules. The field collection text fields become available to tokens and can thus be used as captions.


How do I display the domain owner of a node in a view?

I believe that's relatively straight forward to achieve directly in your view without having to touch templates.

All you need to do is in your view, add a relationship of "Domain Source: Domain Node". This will then provide domain information against your nodes. Then in your fields you will be able to add relevant domain information against the node (using the relationship). So in your case I believe you would want to add the field "Domains: Site Name" and select the relationship in the dropdown. You should then have your site name displayed against your events which would link to the domain.

hope thats helps.
Cheers


You could use webfm module upload images and then display them using img tag in the blocks.


Is there a good way to inspect objects whose type is derived from the EntityDrupalWrapper class?

Use dpm($wrapper->getPropertyInfo());

It's in the docs.


Can't access module settings (Devel module)

I Think I figured out the culprit, if not the exact reason- I was getting “Allowed memory size” errors on common tasks like enabling modules, and once I remedied that my config screen showed up.

The memory error issue was addressed here.


PHP fatal error on server after deactivating modules

Finally the problem is solved thanks to this thread.
The database update wasn't possible for the Field collection module (but it could have been any number of modules), but with the help of all the people that contributed to the solution in the thread above, I was able to get the db update to run as expected. After that everything seems to work.


String Override limited to certain pages?

The 'votes' text seems to be hard-coded into the theme_fivestar_summary() function (around line 264 of 'includes/fivestar.theme.inc'). It is run through format_plural() (so will eventually make itself available to string overrides), but I don't know of a way of defining complex conditions/contexts for string overrides.

The only (easy) way I can see to solve this is to re-implement that theme function in your own theme, copying the full function code from theme_fivestar_summary() to MYTHEME_fivestar_summary(), and introducing a contextual condition to alter the specific text that you want to change.

You'd be basically looking at changing these lines:

if (isset($votes) && !(isset($user_rating) || isset($average_rating))) {
  $output .= ' '. format_plural($votes, '@count vote', '@count votes') .'';
  $div_class = 'count';
}
elseif (isset($votes)) {
  $output .= ' ('. format_plural($votes, '@count vote', '@count votes') .')';
}

to:

$context = MYTHEME_get_fivestar_context();
if ($context == 'something') {
  $metric = 'review';
}
else if ($context == 'something_else') {
  $metric = 'vote';
}

if (isset($votes) && !(isset($user_rating) || isset($average_rating))) {
  $output .= ' '. format_plural($votes, '@count ' . $metric, '@count ' . $metric . 's') .'';
  $div_class = 'count';
}
elseif (isset($votes)) {
  $output .= ' ('. format_plural($votes, '@count ' . $metric, '@count ' . $metric . 's') .')';
}

It's not particularly pretty, but I think it's about the most efficient way to do it.


The Representative node relationship will show you a single representative node for your term, so that's not what you need in this case. Instead, try this:

Relationship: Taxonomy term: Content with term

Your results will now look like this:

Term A

Node 1

Term A

Node 2

Term B

Node 3 etc

Assuming this is not what you want, you can next add some grouping like this:

Under Format: settings set Grouping field Nr. 1 to Taxonomy term: Name.
Finally, in Fields, set the Taxonomy term: Name field to Exclude from display. Now you should have a list of node titles grouped by taxonomy term.


I cannot comment, but some remarks

remove the files[] = pasture.jpg line, it isn't needed
you may enable your base theme, but it isn't necessary
put your own themes (modules) under /sites/all/themes or /sites/default/themes, don not put them inside /themes (/modules), if this directory doesn't exist, just create them

Question, does your site works when using the Bartik theme?


You can write try custom Twig_Extention

In yourmodule create service

yourmodule.service.yml

services:
  custom_replace:
    class: Drupal\yourmodule\TwigExtension\Custom_Replace
    arguments: ['@renderer']
    tags:
      - { name: twig.extension }

src/TwigExtension/Custom_Replace.php

<?php

namespace Drupal\yourmodule\TwigExtension;

/**
 * Class Custom_Replace.
 */
class Custom_Replace extends \Twig_Extension {

  /**
   * {@inheritdoc}
   */
  public function getName() {
    return 'custom_replace';
  }

  public function getFunctions() {
    return [
      new \Twig_SimpleFunction(
        'custom_replace',
        [$this, 'custom_replace'],
        ['is_safe' => ['html']]
      ),
    ];
  }

  /**
   * {@inheritdoc}
   * @param $search can a array [`word1`,`work2`] or string `word`
   */
  public function custom_replace($string, $search, $replace = '') {
    return str_ireplace($search, $replace, $string);
  }
}

In template yourpage.html.twig

{{ custom_replace('word','',string) }}


I had a similar problem and tried:

{% include 'my-template.html.twig' %}
{% include directory ~ '/templates/my-template.html.twig' %}

but ThemeRegistryLoader wouldn't recognize 'my-template'. This syntax worked:

{% include 'modules/custom/my_module/templates/my-template.html.twig' %}


What modules are required to make a seating chart website?

Closest things I was able to find are Wysiwyg Image Map and jQuery Map Hilight modules.

Wysiwyg Image Map is image Map editor for tinymce provided by the Wysiwyg module.

jQuery Map Hilight enables the simple addition of mouseover highlighting of hotspots to HTML image maps without requiring the editing of theme files or knowledge of javascript/jquery.

Together they should give you roughly what you need - but if I were in your situation, I would prefer to code this myself.


Simple calculator with predefined coeficient

Yes - this is possible, but its not really related to Drupal (at least the way you define it). Its either going to be a javascript calculator that you embed in a page (where the result wouldn't get saved) or a PHP function that processes the results from a form and returns the result on the next page.

Either way, both are beyond the scope of this site but tutorials like this one should give you a start on writing your calculator embed.


after migrating to D7 all images are missing

The storage of user pictures changed from D6 to D7. I think the answer for your problem might be found at Picture Migration on drupal.org.


Surely you can easily do it by using roles.

Create a role for the users you want to be able to access the node type.
in /admin/people/permissions set the permissions for the roles - disallow access to the node type for roles apart from your specific role that should be able to access it.

For the menu simply create a copy of your menu with the link you wish to hide for other roles and show it only for your specific role and hide the other menu instead. Since you usually assign menus as blocks this can be easily done.


Your question has two different topics:

  How can I get the dynamic page cache to cache the product info
  section?

Set cache keys:

'productinfo' => [
    // ...
    '#cache' => [
        'keys' => ['mymodule', 'product', '1234'],
        'tags' => ['product:1234'],
    ],
],

Sections of a render array are only cached, if they have cache keys. The keys are used to build the unique cid for the cache render table.

  However, if a session has not yet been started (i.e. first page view),
  the entire html page is cached

Anonymous traffic is cached by the Internal Page Cache. If you start a session, the next request will be able to pass the Internal Page Cache and is handled by the Dynamic Page Cache.


How to gets analyts and generate visual reports from sessions?

I don't know of any modules that build this functionality inside Drupal itself. However, there are several tools out there, for which there are Drupal modules, that allow you to visualize the arc that you speak of. Two of my favorites are:
MixPanel: Mixpanel can allow you to create funnels that will help you see how the user is progressing through your website. For example, how many logged in users clicked on a product, how many of those went on to the payment page, and how many of those actually ending up paying. Mixpanel also has a Drupal module for easy integration. Or you could easily integrate this using a custom Mixpanel module with minimal effort. This is how a funnel in MixPanel would look like:

(source: wordpress.com)
Google Analytics: It has a fantastic Visitors flow functionality that will allow you set flows, goals, and track against those too. Again, Google Analytics has a readymade Drupal module. Here's what a flow in GA would look like:


How to set a menu link to user/edit in Drupalgap?

When the settings.js file is loaded in DrupalGap, the framework isn't yet aware of who the current user is, so it is not possible to place this type of dynamic link into traditional DrupalGap menus. Instead you can use a block to simulate a dynamic menu.

http://docs.drupalgap.org/7/Menus/Menus_with_Dynamic_Links

/**
 * Implements hook_block_info().
 */
function my_module_block_info() {
  try {
    var blocks = {};
    blocks['my_module_user_menu'] = {
      delta: 'my_module_user_menu',
      module: 'my_module'
    }
    return blocks;
  }
  catch (error) { console.log('my_module_block_info - ' + error); }
}

/**
 * Implements hook_block_view().
 */
function my_module_block_view(delta, region) {
  try {
    var content = '';
    switch (delta) {
      case 'my_module_user_menu':
        var uid = Drupal.user.uid;
        var html = theme('popup', {
            content: theme('jqm_item_list', {
                items: [
                  l('View profile', 'user'),
                  l('Edit account', 'user/' + uid + '/edit'),
                  l('Logout', 'user/logout')
                ]
            }),
            attributes: {
              id: drupalgap_get_page_id() + '_my_module_user_menu'
            },
            button_attributes: {
              'data-icon': 'bars',
              'data-iconpos': 'notext',
              'class': 'ui-btn-left'
            }
        });
        return html;
        break;
    }
    return content;
  }
  catch (error) { console.log('my_module_block_view - ' + error); }
}


Change CKEditor config.js without modifying module code?

Can you add the setting inside the Custom JavaScript configuration field of the Advanced Options for a particular profile?

There's also the ability to load your own custom config.js file in the 'Load ckeditor.config.js from the theme path' setting under the 'Advanced' section in the CKEditor profile settings.


Entity Reference and Views to allow a nested structure

You should be fine with a content type called person and then have an entity reference field called "children" that points at the content type person.

Then in Views create two relationships using your entity reference field. The second relationship should use the first as relationship setting.

Call the first relationship, child and the second grandchild.

Then output Content Title three times, the second should use the relationship child the second grandchild.

Under row settings set it to group by Content: Title (the first).

Set a filter that the entity reference field can't be empty.

This should list all persons that have children.


Calendar Multiple URL's Output Specific Block/Menu Dead Links

Block visibility settings accept wildcard characters. If the calendar URL's are of the form, say:

/calendar/april/....
/calendar/may/....

all you have to do is to enter calendar/* in the block visibility settings, and all the pages will be identified. (Adjust according to the actual path of your calendar.)


URL & Geomap Lat/Lon fields are not showing in Target List during mapping in Feed?

Finally I was able to import the data for lat/lon values from CSV file to geoField field lat/lon.

I required to use a patch in "geofield.feeds.inc" file in GeoField module which solves this issue.

You can get this patch from under mentioned URL:

GeoFiled Feed Patch File

Hope this patch will help more developers as it does for me too.


Programmatically search nodes according to the value of fields in their bundle

Personally I would stick to writing your query manually instead of using Views.

This way you have much more control over the final query, and in most scenarios you should be able to make it much smaller (and thus much faster) than that created by Views - by joining only with tables you really need to join in a specific situation, while Views will always do all the joins required by all possible scenarios.

Also, this way you could return the result formatted whichever way you want, without the need of installing additional modules, which is just unnecessary overhead.

IMHO. :)


How to log user in when in the middle of Drupal Commerce Checkout

I ended up simply using commerce_cart_order_convert($order, $user); I was able to assign the order to the correct user, and I decided not to log him in at point in time. If I really need to log him in, I will do so after checkout is over when I don't need to access the checkout review page anymore.


Form in custom template does not submit data

Check the html your template outputs - I am pretty sure it is missing the <form> tag around your fields - without that element your form wont submit however as it contains necessary data (post methode and action to name two).

drupal_get_form() retrieves the entire render array for a functional form, but you only pick two form elements to print to screen. It does display the elements because they are themselves valid render arrays, but the functionality of the form is lost that way.

If you really want to ommit fields in the template try to unset the fields you do not want to display. E.g. unset($form['field_to_hide']). This leave the render array of the form intact.

That said, hidding fields is commonly done in a preprocess function and not in the template itself. Since it is a custom form you can do it directly in your form declaration.

$form['field_to_hide']['#access'] = 0;
$form['field_to_hide']['und']['#disabled'] = TRUE;

You can use this approach to set custom data you want to save with the form and the user isn't supposed to see. It's basically a hidden field.

If you just want to seperate the fields to add additional wrapper elements or classes you can do that in the form as well:

$form['your_field'] = array(
  //[...]
  '#prefix' => '
',
  '#suffix' => '
',
  '#attributes ' => array('class' => array('element-class'));
);

Check the Form API page to see for which element the two options are available for: FAPI


I would recommend you to just add it to your theme info file.
That is the easiest way really, since you need them on every  page.

PS: dont forget to clear caches after you added it to your themes info file.


Upload Image browser widget for drupal 6

Try FileField Sources module

  FileField Sources is an extension to the FileField module. The
  FileField module lets you upload files from your computer through a
  CCK field. The FileField Sources module expands on this ability by
  allowing you to select new or existing files through additional means,
  including:

  Re-use files by an auto-complete textfield
  Attach server-side files uploaded via FTP
  Transfer files from a remote server (cURL required)
  Paste a file directly from the clipboard (Drupal 7 only)
  Select existing files through the IMCE file browser

the first one is what youre looking for.


How to add menu links to a node created within a test?

Yes, you have just to provide an uri that identifies the node, for example entity:node/1

Use

'link' => ['uri' => 'entity:node/' . $nid],


Access denied: 'view published content' permission

A quick look at node_permissions makes me think you should be using 'access content' as your argument, not view published content', as the latter is the proper machine name for the permission.


Boost
  Boost provides static page caching for Drupal enabling a very
  significant performance and scalability boost for sites that receive
  mostly anonymous traffic.

I am not sure if Boost can be used for authenticated users as well. Boost will capture rendered HTML pages and store them and when a request comes for same page instead of overloading the server with PHP execution it will send the already compiled HTML pages which will greatly increase performance.
Auth cache is an alternate that allows caching for both authenticated and anonymous.


That's not what drupal_get_path() is for; it's for getting the internal router path for a URL given a path alias, and vice versa. It also allows you to wipe aliases, but it's not a good way to try to get the current page's node ID.

What you're looking for is the arg() function, which simply splits the current router path (the value contained in $_GET['q'], which for a node page will be, for example, node/1).

// With a router path of node/123
$entity_type = arg(0); // $entity_type is equal to 'node'

$nid = arg(1); // $nid is equal to 123


How can I programmatically alter a view query?

I would approach this from a different angle. You can create a new Datetime argument type (a views plugin) and then add an association for your desired field to your new argument. This means we aren't modifying a query in an unpredictable way, and you can see in configuration that the argument is different. You can set this up to use any date format you wish, but keep in mind that time zones may affect the values.

First, we'll create the new argument type. We're extending the existing base Date argument and only changing the date format. The @ViewsArgument value will need to match the argument id value in the field assignment later on.

mymodule/src/Plugin/views/argument/FullDatetime.php:

<?php

namespace Drupal\mymodule\Plugin\views\argument;

use Drupal\datetime\Plugin\views\argument\Date;

/**
 * Argument handler for a full datetime (CCYYMMDD-HHMM).
 *
 * @ViewsArgument("mymodule_full_datetime")
 */
class FullDatetime extends Date {

  /**
   * {@inheritdoc}
   */
  protected $argFormat = 'Ymd-Hi';

}

And now we'll create a new argument assignment for the Session Date field.

mymodule/mymodule.module:

/**
 * Implements hook_views_data_alter().
 *
 * @param array $data
 */
function mymodule_views_data_alter(array &$data) {
  $data['node__field_session_date']['field_session_date_full_datetime'] = array(
    'argument' => array(
      'field' => 'field_session_date_value',
      'field_name' => 'field_session_date',
      'id' => 'mymodule_full_datetime',
      'table' => 'node__field_session_date',
    ),
    'group' => $this->t('Content'),
    'help' => $this->t('Date in the form of %format.', array('%format' => 'YYYYMMDD-HHMM')),
    'title' => $this->t('@field', array('@field' => 'Session Date (Full Datetime)')),
    'title short' => $this->t('@field (@format)', array('@field' => 'Session Date', '@format' => 'YYYYMMDD-HHMM')),
  );
}

Now you just need to add the Session Date (Full Datetime) argument to your view in place of the argument you were trying to override.


What are dependencies in the context of a user role in Drupal 8?

As Ivan Jaros said, all config entities can have dependencies on modules and other config entities, both automatically derived based on code (e.g, a field depends on its field storage and entity bundle it is added) and manually set (in an enforced sub-array with the same structure)

Dependencies ensure that the required dependencies are installed and they are installed in the right order. Which is important if you import a new node type with fields, display configurations, views that list them and so on.

User roles currently don't have automatically derived dependencies, but they actually should have. They should depend on the modules that provide the used permissions, which is a bit tricky since permissions don't give you that information especially not for dynamic ones that depend on node types, filter formats and so on. That's why the key is always empty for them.

We should open a core issue to try and track this better, that would allow roles to clean up permissions when e.g. a node type is deleted or a module is installed. But it's not a major problem since nothing happens if those permissions don't exist anymore.. it's just a string and if nothing asks for it, then nothing happens with it. The only problematic thing is that you a) end up with cruft in those config objects and b) the permissions could get active again when you e.g. delete a node type and add again with the same name. You might not expect your permissions configurations to survive that.


Is it possible to use an image style with a path rather than a URI?

I'll expand a bit on what acrosman answered, only because I needed this exact same thing so hopefully this will help the next person who comes across this.

I'm working from preprocess_page and using a view to grab my images.

Like his answer make sure you add the ImageStyle:

use Drupal\image\Entity\ImageStyle;

Once I grabbed the view entity I was able to narrow down my image field and then work my way to the styled image.

$image = $entity->get('field_images')->getValue();
$image_entity = File::load($image[0]['target_id']);
$image_uri = $image_entity->get('uri')->value;
$style = ImageStyle::load('my_image_style');
$image_url = $style->buildUrl($image_uri);

So overall my whole function to grab the image from a View and apply a custom image style looked like.

function _mytheme_preprocess_page_front_projects(array &$variables) {
  $projects = array();
  $view = Views::getView('projects');

  if (is_object($view)) {
    $view->setDisplay('page_1');
    $view->preExecute();
    $view->execute();

    foreach ($view->result as $k => $v) {
      $entity = $v->_entity;

      // Grab image entity.
      $image = $entity->get('field_images')->getValue();

      // Load the first value for preview image.
      $image_entity = File::load($image[0]['target_id']);

      // Grab the uri of that first image.
      $image_uri = $image_entity->get('uri')->value;

      // Using ImageStyle you then load your style.
      $style = ImageStyle::load('my_image_style');

      // Use buildUrl to create the path to your styled image.
      $image_url = $style->buildUrl($image_uri);

      // Then I return the url as an image variable to grab in page template.
      $projects[$k]['image'] = $image_url;
    }

    return $projects;
  }
}


Field collection: Can I make a field mandatory depending on another field's value?

The Conditional Fields module can help you to achieve this.

You will probably need to create an explicit list of taxonomy terms for the case when you want the plain text field to appear and to be required instead of checking the existence of the aforementioned placeholder.


Try this one, add class as array.

$form['keys']['#attributes'] = array('class' => array('custom_search-keys','form-search','form-control'));


Inserting field or field collection into body field

You might be able to use the EVA: Entity Views Attachment module to attach the data to the node, but I'm not sure.

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


Form API, drupal_add_js() and setting a JS variable

I never tried, but I guess you can do it like that :

$form['#attached']['js'] = array(
  array(
    'data' => drupal_get_path('module', 'radio86_media') . '/select_media.js',
    'type' => 'file'
  ),
  array(
    'data' => array('radio86_media' => array('barfoo' => 'booboo')),
    'type' => 'setting'
  )
);

According the documentation you should be able to add settings and files.


How can I hide field labels without using any CSS style?

Go to "Admin > Content Type > Manage Display" and hide the labels as shown in the screenshot.


How to disable/enable a context programmatically

Use the context_status to enable/disable contexts.

This variable is an array with context names as key and TRUE as value: each of this context is disabled.

To disable a context: add a new pair to the array like this:

$contexts = variable_get('context_status', array());
$contexts['context_name'] = TRUE;
variable_set('context_status', $contexts);

To enable a context: unset the context name from context_status.

$contexts = variable_get('context_status', array());
unset($contexts['context_name']);
variable_set('context_status', $contexts);

Also you can use Features, exporting the context_status to a feature.


$block = module_invoke('views', 'block_view', 'ViewName-DisplayId');
     echo $block['content']['#markup'];

Parameters in module_invoke:

module to call: 'views'
hook to call, in this case 'block_view'
View name and display id of the block, separated by an hyphen. For example 'testview-block_1'

The display id of the block it will show only when hovering the mouse over the "Block" word in the Views page of the Block. You will see an url like this: http:///admin/structure/views/nojs/display/testview/block_1
The block_1 is the display id in this case.


How to combine content from two different environments?

Node Export
The Node Export module might be used for this. Here is an excerpt from its project page:

This module allows users to export nodes and then import it into another Drupal installation, or on the same site.
Using this module you can save yourself a lot of time setting up new websites that have similar nodes to websites you've already made, migrating nodes to new Drupal versions, or between development/staging/production sites.
You will need the same content types for the imports to work (unless using Feeds to import), and ideally relevant compatibility with fields, and modules.

Feeds
Another option that might work is to use the Feeds module. Here is an excerpt from its project page:

Import or aggregate data as nodes, users, taxonomy terms or simple database records.

Bundle copy
Yet another approach is to use the Bundle copy module. Here is an excerpt from its project page:

Has export/import support for:

Node types
Taxonomy
User
Field API fields
Field groups

You can find the export/import links for the supported entities on following paths:

Nodes: admin/structure/types
Taxonomy: admin/structure/taxonomy
Users: admin/config/people/accounts


How to hide product in drupal commerce with rules

I believe there is not out of the box or ready to use solution. You should create a custom rule and trigger it when the product is being viewed.


How do I set the path to a custom view style template?

I think instead of path = "sites/default/modules/mymodule/templates" you should have theme path = "sites/default/modules/mymodule/templates".


You do not need to use $field, $entity_type and $entity in your implementation of hook_file_download_access_alter(), if you do not want to.

You should use theses arguments if you need to handle files differently depending on which field of which entity they belong to.

For example, node_file_download_access() restricts access on files to people that can view the node. If you want to remove this restriction for nodes of a specific type foo, you would have to check whether $entity_type == 'node'and whether $entity->type == 'foo' and grant access if this is the case.


How can I keep logs of all outgoing emails?

Try to use https://www.drupal.org/project/mail_safety I using it with swiftmailer module (configured with SMTP) and it works. You can configure it for store all outgoing emails.


how to create new image size with new image style with php code in drupal 7?

You have to go to Configuration => Image Styles. Create the Image Style with the name front_video_thumnail and once it's configuration is saved your code should work.


Is there a required format for table name prefix?

There is no requirement for the prefix to end in an underscore for any type of database but it can be beneficial for readability.

It is just a string of characters that Drupal prepends to table names in queries so it can contain any characters that are legal to use in table names in your chosen type of database.

Database prefixes are also not necessary at all unless you are using a single database for multiple purposes, for example you have all your drupal tables prefixed with drupal_ and then have other non-drupal tables without a prefix or with a different prefix.

That way you can easily tell which tables are for what.

This is usually only necessary if your hosting provider limits the number of databases you are allowed or sometimes in some more advanced Drupal configurations.

The way Drupal uses it is that if you use one of the db functions like db_select(), db_insert(), db_update(), db_delete() it automatically appends any prefix value you have configured.

When using db_query() it will also do this for any table name wrapped in braces, eg:

db_query("SELECT * FROM {node}");


As the comment states, it looks at the defined entity (Contact) and checks the value of the annotation in Contact.php which is Drupal\content_entity_example\Entity\Controller\ContactListBuilder to see what its entity list builder class is. It knows this because content_entity_example_contact resolves to the class, because it has an id annotation defining it as such.

See: https://cgit.drupalcode.org/examples/tree/content_entity_example/src/Entity/Contact.php


How to check in Rules if a text field has changed?

First things first: your node:field-sucurity-audit token might contain a typo ... It could well be that you intended to use node:field-security-audit instead (see the difference?). If that is not the solution (yet), just keep reading ...

Also make sure to always (repeat: always) add an Entity has field condition BEFORE any other Rules Conditions in which you might want to refer to some field. So in your case you should add 2 such extra Rules Conditions (since you're checking the value of 2 different fields). That's also what is mentioned in the Rules UI, e.g. when you're adding a "data comparison" condition: somewhere it says:

  The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type').

For a video tutorial that illustrates the importance of this Entity has field condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in it.

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


Is it possible to redirect a user to avoid showing an AJAX batch processing error?

I found the cause of the error-- I had a custom rule that sent an e-mail to the admin when the account was cancelled.  By deleting this rule, the error disappears and the user is logged out properly.


Hope my below answer helps you.

if you are using Image field, then Image field provides an option to insert "Alt" and "Title" tags. When enabled, you can insert the values in the fields.
When you are saving if yourself, custom save, then the image field array needs to look something like below.

[field_image] => Array
    (
        [und] => Array
            (
                [0] => Array
                    (
                        [alt] => alt text
                        [title] => title text
                        [fid] => 12
                        [display] => 1
                        [width] => 220
                        [height] => 169
                        [description] =>
                        [upload_button] => Upload
                        [remove_button] => Remove
                        [upload] =>
                    )

            )

    )

However, the above is from the node presave, but when tested for empty values, and changing values in node presave, this worked flawless.
Try that out, curious to know why It wont work, Should be simple (If I understand this correctly :) )

Now, you also need to see at what point you want to implement it.
Node presave, node view or any other point in time.


using xhprof in drupal 6 to monitor a cron task and display in the XHProf runs page

I haven't used the D6 version before but rummaging through the code I think something like this will work:

1st bit (taken from xhprof_shutdown_xhprof())

$namespace = variable_get('site_name', '');  // namespace for your application
$xhprof_data = xhprof_disable();

// Path to save file. Leave empty to use a default
$xhprof_data['path'] = isset($_GET['q'])?$_GET['q'] : '';
$class = variable_get('xhprof_default_class', 'XHProfRunsFile');
$xhprof_runs = new $class();
$run_id = $xhprof_runs->save_run($xhprof_data, $namespace);

2nd bit (taken from xhprof_display_page())

drupal_add_css(drupal_get_path('module', 'xhprof') . '/xhprof.css');
$html = xhprof_display_run(array($run_id), NULL);

// Do what you need to with $html to get it out to the screen


How to add a node field to a database table in a custom module

Most of the time you will probably want to use the field API (CCK module in D6) rather than adding custom tables or modifying node by yourself.

Adding custom tables was a very D5 way of doing thing.

If you want to do this you will need to define your tables using hook_schema() and then in your mymodule_install() hook you can call drupal_install_schema() this should create a new table which represents your module.

It is worth mentioning that your schema should always represent your current schema. If you add a column you should alter the schema so that someone who installs your module will get the correct schema, but also write an update function to alter the table so that existing users get the correct new schema.

It is possible to alter other modules' tables, but I think that should be covered in another question.


Display custom URLs for individual tabs of quick tab

Add jquery in external : This is used for you

jQuery(document).ready(function(){
  var quicktab = jQuery('ul.quicktabs-tabs.quicktabs-style-excel li  a').each(function() {
      var url  = 'test-quicktab-page?qt-test_quicktab=2';
      var href = jQuery(this).attr('href');
      var arr = href.split('/');
      alert(arr['2']);  /* rechange the index value as your url path */
      if(url == arr['2']) {
        jQuery(this).removeAttr('href');
        jQuery(this).attr('href','/test-quicktab-page/world');
      }
    });
});


Feeds tamper to find element in text and replace it with part of the element or 0

You can add a Tamper plugin of type "Set value or default value". Set "Value" to "0" and enable the "Only if empty" option (see image below). This way, the value "0" will be set only if the "Find replace REGEX" returned an empty result.

I tested with your example data if this would work and in my case it did.
Birth 1869 Location Merthyr Tydfil, Glamorgan, WalesG resulted into 51.7479 and Marriage Calculated 1894 resulted into 0.


Building the sidebar content on each node

There probably is a better solution, but this is what I thought of.

Make two new content type of 'sidebar-block-text' and 'sidebar-block-image'. And in those content types add a node (or entity) reference field. (Make sure to use the same field, so create it once, and for the other content type choose it from existing fields!)
Build a view-block.

Let it display the whole rendered node.
Add a contextual filter of the current node id and link it to the reference field.

Place the block in the template sidebar region.

All the administrator will have to do is to add a new piece of content (sidebar-block-text or -image) and reference it to the 'parent node'.


How to display multiple PDF files in a node

Check maybe the Field Settings (/admin/structure/types/manage/page/fields/...) of your page if the displayed "Number of values" is set to "Unlimited" instead of 1.


How to docreate a function to do if conditions dependign on content type name

You can set a variable in hook_preprocess_Hook function which has the content type and then use that variable in twig file.

$node = \Drupal::routeMatch()->getParameter('node');
  $nids = $node->nid->value;
  if($nids){
    $variables['content_type'] = $node->bundle();
  }


When creating a 'status' entry with the statuses module, stop it from creating a double post

Gosh, never posted here before, but the rules seem kind of draconian. I don't have a fix for this, but I thought I could relate that I've had the exact same problem and note some of the things I've tried.

I notice than when I look at the View under "Preview" and specify a user_id, it works perfectly. My hope is that IceCreamYou (the main contributor, who is particularly arrogant, when you read his responses to questions) will stumble upon this and a lightbulb will go off in his head.

Otherwise, my suggestion would be to intercept the SQL (you can see it with the Devel module), try to roll your own (with the inclusion of the DISTINCT keyword, which when I add it to the query generated removes the duplicates).

Note that the code for the "statuses" view is embedded in the Statuses module, so you'll have to extract it from there first.

If this sort of post is against the rules, feel free to delete it :-)


How to make block with list of terms from blog postings

It sounds as if you have created a view of nodes, and using the Taxonomy: All terms field to display the terms of those nodes. That approach will indeed produce duplicate results.

Instead, you need to create a view of Taxonomy Terms. I don't know which versions you are using, but here is the export of such a View made with Drupal 7  & Views 7.x-3.0-rc1.

$view = new view;
$view->name = 'tags';
$view->description = '';
$view->tag = '';
$view->base_table = 'taxonomy_term_data';
$view->human_name = 'Tags';
$view->core = 7;
$view->api_version = '3.0-alpha1';
$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'] = 'Tags';
$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['query']['options']['query_comment'] = FALSE;
$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['row_plugin'] = 'fields';
/* 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']['alter_text'] = 0;
$handler->display->display_options['fields']['name']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['name']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = 0;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = 0;
$handler->display->display_options['fields']['name']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['name']['alter']['trim'] = 0;
$handler->display->display_options['fields']['name']['alter']['html'] = 0;
$handler->display->display_options['fields']['name']['hide_empty'] = 0;
$handler->display->display_options['fields']['name']['empty_zero'] = 0;
$handler->display->display_options['fields']['name']['link_to_taxonomy'] = 1;
/* 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(
  'tags' => 'tags',
);

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


How do you allow logged in users to comment via Disqus without extra login?

This question is old, but for the sake of the completeness: you have to use Single Sign-On from DISQUS API. In the comment section, logged in users will see themselves connected to the DISQUS system with the cretentials from their Drupal account and will be able to comment directly with no additionnal login. The anonymous users will have to previously connect to DISQUS, Facebook, Twitter or Google before sending their comment.
Note that this question has already bee answered here.


If you download Drupal from here, there is the .htaccess file in main directory.

How do you downloaded Drupal source code?


how to use parent field in child view in views field View

You will have to send a contextual filter from your parent view and catch it in your embedded view. There are plenty of tutorials on contextual filters, but this one should get you started:
http://www.metaltoad.com/blog/using-drupal-contextual-filters-views

UPDATE
you can set a contextual filter from your parentview by editing the embedded view in 'fields' and define it in the view-settings drop-down.


How to add classes to h2 block title tags in sidebar region

template_preprocess_block()

Inspect the block object in this preprocess function. You could use either the 'module' and 'delta' properties to target a specific block or the 'region' property to target all blocks in a certain region.

H2 css-classes are listed in the title_attributes_array. The code below shows how to add a new class. This example is based on a block generated by Views:

function MYTHEME_preprocess_block(&$variables) {
  $block = $variables['block'];
  if ($block->module == 'views' && $block->delta == 'name_of_my_view-block') {
    $variables['title_attributes_array']['class'][] = 'my-new-class';
  }
}

Sidenote: dpm() by the Devel module is a handy tool for printing out the available data in variables:

function MYTHEME_preprocess_block(&$variables) {
  dpm($variables);
}


Using Entity Reference field, get the parent NID in referenced entity (node)

With the logical structure that is mentioned, it is possible that a node may have more than one parent. Wouldn't it be wiser to make a reference upwards than downwards? You would end up with an entityreference field of granularity 1. Unless there is some other reason for which to keep this structure.

There is no explanation on the specifics of this calculation that takes place. Is it in a custom module, is it rules, is it some other contrib module?

In any case, you can use an EntityFieldQuery in order to get a list of all nodes that reference the particular node. More details about how to use here. There is a particular reference for entityreference fields:

  Likewise an image field would use 'fid', 'alt', and 'title' as column names; an entity reference field would use 'target_id' and 'target_type' as column names.

Example (in CAPS the variables that you need to handle):

<?php
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'MY_CONTENT_TYPE')
  ->propertyCondition('status', 1) // published? yes
  ->fieldCondition('field_MY_ENTITYREFERENCE', 'target_id', $MY_CURRENT_NODE_ID)
  ->range(0, 10); //do not forget the semicolon at the end of the query conditions
$result = $query->execute();
if (isset($result['node'])) {
  $items_nids = array_keys($result['node']);
  $items = entity_load('node', $items_nids);
}
?>


Statistics per node only visible to node author

The Google Analytics Reports modules offers blocks that will report on individual pages. Wouldn't this off-load the stat works to Google?


How to allow filtering by only date parts selected by user and make not selected work as "Any"?

It validated, because by default it set to AND operator in your exposed setting. You can do it easily, but I have done it in Drupal 6, I don't have D7 setup. Check the below screenshots. Just select the Method as OR in the exposed filter setting.

Click the setting icon and then select the OR under method.


The general solution for cases like this, where you want to export an input format, a role, and a permission associated to that role is using the Features module. Selecting what you want to export on admin/structure/features/create, the module will create a feature: a module that (once installed) will make available what exported.

If you don't want to use the Features module, you can create a module that:

Creates the Developer role if it doesn't exist
Creates the input format if it doesn't exist
Creates the permission to use that input format if it doesn't exists
Assigns the permission to use that input format to the Developer role

Assuming that the role and the input format already exist in the site, the code is simply the following.

if ($format = filter_format_load('developer_html')) {
  if ($permission = filter_permission_name($format)) {
    if ($role = user_role_load_by_name('developer')) {
      user_role_grant_permissions($role->rid, $permission);
    }
  }
}

As to where to use this code, you have two possibilities:

hook_install()
hook_enable()

hook_enable() is what the Forum module uses to create the forum vocabulary and the "taxonomy_forums" field it uses (see forum_enable()). I would use this hook if the module requires something to be set/present before it runs; differently from hook_install(), it has also the pro of not requiring a hook_update_N() to be added for those users who update the module, since hook_install() runs only during installation, while hook_enable() runs every time the module is enabled.


Modify the visibility of a form field label with #label_display attribute

I know this is over a year old, but completely removing the form labels in this way is probably not a good idea in terms of accessibility.

Instead, take a look at #title_display defined by the FormAPI. FieldAPI has something very similar called #label_display.


I was able to use a snippet from dropbucket to lock and unlock fields. I used the snippet in the devel execute php window but it could certainly be coded into a function instead:

/*
# You can use Devel Module to unlock/lock a existing field where you would otherwise get an error like "The field xxxx is locked and cannot be edited."
# Change the 'xxx' on line 1 with the machine readable name of your field.
*/
$field_name = 'xxx';
$field = field_read_field($field_name);
$field['locked'] = 1; //change this to 0 to unlock a field
field_update_field($field);


After some desperate digging I found the solution (come on Drupal guys, don't be shy, give us some documentation!): Go to /admin/structure/block and click the 'configure' button of the block named 'Site branding'. There you can choose which parts of site branding are shown.


You should check out Context module, can solve your needs listed above.

One way you can do is to create different menus for different roles.

For example, you create a menu called 'menu for anonymous' , add links for anonymous in the menu; create another menu called 'menu for member', add particular links in the menu. and so forth.

With Context module, you can set 'menu for anonymous' to display for anonymous user; set 'menu for member' to display only for user has whatever role.

For changing 'You' to username, I am thinking that you can use hook_block_view_alter, loop to all menu items in the menu block, replace 'you' to user's name.

Again, with context module, you can add a section variable to the theme for the context of user logged in.

then you can customize your template in page--user.tpl.php

if (!empty($section_title)):
        ... theming for logged in user  ...
else:
    ... theming for general ...
endif;

Hope my answer make sense.


Unexplained change in module weight in registry table caused site error

An easy way to solve this problem is to set the status of that module to 0 in the system table. Then try to uninstall them completely and then try to install and set them again.

I know this is not the best way (there are other ways), but sometimes short and not optimal method is better that spend more time on debugging.


How to prevent a node from listing programmatically?

Have you tried simply unpublishing the node with Rules? Rules will allow you to programmatically unpublish content based on a variety of factors. Once unpublished, Drupal will not list the node in content with the exception of Views that are not set to only display published content.

What are you using to determine which nodes should be processed by your code?


How to data compare the price or, subtotal in Ubercart flat rate shipping quotes

Never mind... I had negate checked!
This is how I did it...

Data comparison
Parameter: Data to compare: [order:delivery-address..., Data value: United States

AND

Data comparison
Parameter: Data to compare: [order:order-total], Operator: is greater than, Data value: 34

Data comparison
Parameter: Data to compare: [order:delivery-address..., Data value: United States

AND

Data comparison
Parameter: Data to compare: [order:order-total], Operator: is less than, Data value: 34


Remove link to terms page when printing taxonomy term on node--content_type.tpl.php?

To print the raw value you can use this code:

<?php

if(!empty($node->field_p_status['und'][0]['value'])) {
  print $node->field_p_status['und'][0]['value'];
}
?>


How can I set a default value for date field using hook_form_alter

Please see below code to set a default value for date field using hook_form_alter

$form["your_date_field"]["und"][0]['#default_value']['value'] = '2016-11-16 00:00:00';


How to translate variable containing html with the i18n_variable module?

A solution I used when I faced a similar problem in a different context is to preventively replace tag-markers by the corresponding entity in the content before it is processed.

Adapated to your case, it might look like this:

/**
 * Implements hook_variable_info().
 */
function MY_MODULE_variable_info($options) {
  $my_variable_content = preg_replace_all(
    '/<([^>]*)>/', '&lt;$1&gt;',
    'A good default value with some <tags> inside'
  );
  $variables['pm_email_notify_subject'] = array(
    'title' => t('My variable title'),
    'description' => t('The description', array(), $options),
    'default' => t($my_variable_content, array(), $options),
    'type' => 'string',
    'localize' => TRUE,
    'access' => 'administer checkout',
    'group' => 'my_variable_group',
  );
  return $variables;
}

This way, the finally rendered text keeps its "<" and ">" intacts.

But caution: it might be not appropriate to your case, so try it carefully.


How to send a user an email when a content is published by somebody else?

The Workflow module can do it exactly what you want. By using this module you can trigger different action at each flow of content.

  Workflows are made up of workflow states. Transitions between states can be allowed per role. For example, a workflow with the states Draft, Review, and Published could be assigned to the Story node type. Only users with role 'chief editor' can set Stories to the published state.
  You can set up the Workflow to alter states from form, page, comment and a special workflow tab.


Yes, that is expected, since the Minimal profile creates less entities than the Standard profile. You can see that by comparing the config/install directory in the first profile with the config/install directory in the latter profile.

As per creating the role from the user interface, that would be possible, but the created role would be a role like the others, while the Administrator role created from the Standard profile automatically gets all the permissions defined in a Drupal site. In fact, Role::hasPermission() uses the following code.

  if ($this->isAdmin()) {
    return TRUE;
  }
  return in_array($permission, $this->permissions);

For the Administrator role, $this->isAdmin() always return TRUE; for every role you create from the user interface, $this->isAdmin() would return FALSE.

If you need that role, and you cannot reinstall Drupal using the Standard profile, you can create a custom module, for which you create a config/optional/user.role.administrator.yml file with the following content.

langcode: en
status: true
dependencies:
  enforced:
    module:
      - yourmodule
id: administrator
label: Administrator
weight: 2
is_admin: true
permissions: {  }

(Replace yourmodule with the module name.)

When the module is installed, the role will be created. Since the file contains is_admin: true, the role will have all the permissions, automatically, like the Administrator role created by the Standard profile.

The alternative method that doesn't involve writing modules is importing the user.role.administrator.yml file in the site. The content of the file is similar to the content of the file I previously suggested, with the exception that there aren't dependencies.

langcode: en
status: true
dependencies: {  }
id: administrator
label: Administrator
weight: 2
is_admin: true
permissions: {  }

I would use the custom module method if there are other entities/bundles that you normally create when installing Drupal for a new site.
If instead you don't have the need to create other entities/bundles, importing a single file is quicker.

If you installed Drush, with drush config-edit user.role.administrator you can edit that file and set is_admin to true.


Yes, that is the correct and expected behaviour. Loading every entity referenced by a node every time it loads, could potentially get very heavy on the server very quickly. That's why referenced entities are lazy-loaded (albeit manually as far as core is concerned).

To load taxonomy term entities from the tid, you can use taxonomy_term_load(). If you want an (arguably) slightly more pleasant experience when working with entities/fields on code, check out the EntityMetadataWrapper class, which is part of the Entity API module.


You can modify your theme's CSS to give every File Field a specific background image.  You would add this to your theme's stylesheet, looking for a "style.css" file in your theme folder.  The generic code for the background image would be:

.node-your-node-type .field-type-file {
  background: url("/sites/all/themes/yourtheme/yourbackgroundimage.png") no-repeat scroll 0 0 transparent;
}


Will Drupal 8 Twig have template inheritance like Drupal 7?

I think you might be confusing inheritance with granularity. Twig actually does have the concept of template inheritance (see extends), while Drupal 7's theme engine doesn't.

The short answer is yes, you can expect the same from Drupal 8 as you did from Drupal 7. Specifically for fields, the example in the docs for field.html.twig will give you some insight:

  For example, for a field named 'body' displayed on the 'article' content type, any of the following templates will override this default implementation. The first of these templates that exists is used:

  field--node--field-foo--article.html.twig

  field--node--field-foo.html.twig

  field--node--article.html.twig

  field--field-foo.html.twig

  field--text-with-summary.html.twig

  field.html.twig

These can be altered/added to using hook_theme_suggestions_alter(), or the more specific hook_theme_suggestions_HOOK_alter().


You could just pass the stdout from Drush as the stdin to grep.

Example:

drush wd-show | grep 'Undefined offset'

As a bonus - If you want the errors in a file, try the following:

drush wd-show | grep 'Undefined offset' > ~/Undefined-errors.txt

This'll put the errors into a text file in your home directory :-)


You need to process the payment. In your case you could mark that the invoice has been paid, maybe in storm or a custom table.  $payment should hold all the info about the payment that you need. I guess some of the info depends on your module as well.

Anyways when you have processed the payment you should return TRUE which will make the simple payment module mark that payment as being processed. I imagine that there is an interface that will allow you to see if a payment hasn't been processed, which would happen if an error occurred while processing.


Get node in custom token to be used in Pathauto url alias pattern

You get the node from $data:

  if (!empty($data['node'])) {
    /* @var \Drupal\node\NodeInterface $node */
    $node = $data['node'];
  }

It is the responsibility of the code which calls replace() to provide the correct context (in case of Pathauto the node for which it's building the alias).


Conditionally output by content type using Twig

Probably because {{ fields.type.content }} =
blog

so try

{% if fields.type.content|striptags == {{ 'blog'|t }} %}

If you do not want to have to use |striptags you could strip the markup from the Views UI.

Also, do not check mark Exclude from display in configure field, because if you do this your template file will not have access to that field.

Side note: you forgot to close the div in line 3.

Alternatively

{% if row._entity.gettype == 'content_type_machine_name' %}

 alternate method credit: 4K4


Update database with update module disabled

Doh. Update wasn't working for me because I didn't exist on the system. Silly mistake


How do I add a simple form to the node edit page?

It sounds like you want to let the author notify your module of significant changes to a node.  Another approach you could take is to add a field to your node type, such as "field_change_notification" (boolean/checkbox) ... then look to check if the author selected the checkbox in hook_node_presave.  You can even set it back to unchecked so they can again notify your module on the next update.

function HOOK_node_presave($node){
  if ($node->type == 'article'){
    if ($node->field_change_notification['und'][0]['value']){
      drupal_set_message('A change has been made...');
      $node->field_change_notification['und'][0]['value'] = 0;
    }
  }
}


Authentication page before loading the main website

You can use this module

The LoginToboggan module offers several modifications of the Drupal login system in an external module by offering the following features and usability improvements:

Allow users to login using either their username OR their e-mail address.
Allow users to login immediately.
Provide a login form on Access Denied pages for non-logged-in (anonymous) users.
The module provides two login block options: One uses JavaScript to display the form within the block immediately upon clicking "log in". The other brings the user to a separate page, but returns the user to their original page upon login.
Customize the registration form with two e-mail fields to ensure accuracy.
Optionally redirect the user to a specific page when using the 'immediate login' feature.
Optionally redirect the user to a specific page upon validation of their e-mail address.
Optionally display a user message indicating a successful login.
Optionally combine both the login and registration form on one page.
Optionally have unvalidated users purged from the system at a pre-defined interval.
Integrates with the Rules module to do various tasks when a user validates via email validation process (see http://drupal.org/node/880904 for an example).

Or you can add this code as well:
    global $user
    if ($user->uid  == 0  && $_GET['q'] == 'node') {
      drupal_set_message("Access Denied: Please Login");
      drupal_goto('user/login', drupal_get_destination());
    }