You should be using migrate for this: https://www.drupal.org/project/migrate, it covers many of the pitfalls you are currently encountering when creating or importing content from a CSV, database or XML file. Don't recreate the wheel when someone has already created it for you.

It's not like the feeds module or other "import" type modules, it's an entirely  code based OOP solution. You just extend the main migration class and map your data. It comes with a number of built in PHP functions to process the data further and it literally covers almost every scenario you could possibly encounter when mass creating or transferring content.

As someone who's been down this path many times, it will save you a lot of time and hair pulling. I recommend looking at the code examples migrate provides.


Attaching a view page display to a tab in a content type?

In the Page settings section of the Page display of your view:

Path: node/%/export
Menu: Menu tab, Title: Export

You'll probably have an argument in your view already. In that argument's configuration:

Validator: Node
Node type: projectsheet (or whatever node types to display tab for)


"Route "ctf.content" does not exist" when installing custom module

You do need to clear the caches any time you edit routes. The simplest way is from the performance settings page: /admin/config/development/performance.

To change the module's name you'll need to replace every instance of the original name throughout every file in the module.


Custom facets return no results on search page

I have found the solution.

if you wrote this hook hook_apachesolr_index_document_build_node then
you have to delete the indexed data from apache solr search index and
then reindex all the data. if you only reindex data then it will not
work.
and 2nd point. you have to keep care of the prefixes of the field. if it is a single string then use ss if multivalue field then use sm
3rd point is you have to call hook_apachesolr_query_alter.

function myModule_apachesolr_query_alter($query){
   $query->addParams(array('fl' => array('ss_custom_field')));

}


Error is as stated..

Warning: in_array() expects parameter 2 to be array, string given in goodnex_item_list() (line 212 of /home/biltrite/public_html/sites/all/themes/goodnex/template.php)

Whatever is calling in_array in goodnex_item_list is not passing an array as the second argument and instead is passing a string. You'll have to backtrack from there to figure out what and why.

See: in_array


Drush update for commerce kickstart is not just update drush pm-update, but rather:

drush dl commerce_kickstart
drush updatedb

Check here


Adding extra field on Main menu, similar to Amazon.com

Your best option is to use the TB mega menu module add your html content to a block and add the block to the menu

  TB Mega Menu is developed following Drupal standards and best
  practices. Along with those must-have functions of a mega menu:
  display not just menu items but image, slideshow, video, article and
  customize any of them upon your favour...


Since the fields were attached via Field API, I have to do this way

$form['field_member_last_name'][LANGUAGE_NONE][0]['value']['#ajax'] = array(
    'event' => 'blur',
    'callback' => 'get_suggestion_by_name',
    'wrapper' => 'suggestions_by_name',
    'method' => 'html',
);


Block visibily condition programatically

In the block ::build() method, return an empty array() if the condition is false.


How to show results in entityreference autocomplete only after the user enters 5 characters

One way to do it is create your own custom autocomplete (a good example is here) in your custom module. Then within your custom autocomplete function check if the submitted autocomplete string is 5-6 chars long then execute the search, like so (using the example from the tutorial above):

function demo_autocomplete($text) {
  if (strlen($text) > 5) {
  // execute your code here:
    $results = array();
    ... etc
    drupal_json_output($results);
  }
}


Factors regarding menu visibility (menu is missing on access denied)

So if you're ever missing something in your site, consider these factors when diagnosing:

check the raw markup itself (HTML) ensure it's not a CSS issue.
a permissions problem, does the role have access?
can you narrow the problem to the theme... this will determine further courses of action


There are a few different ways you could do this, but the way you asked for would utilize hook_form_alter():

<?php
function custom_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'mynodetype_node_form') {
    drupal_set_title('My new title');
  }
}
?>

This would be in a custom module named custom.module... drupal_set_title(), when called anywhere in the page load, will set the title appropriately. You're basically hooking into the node form rendering process, and saying 'set the title to what I want' at that point.

If you'd like to further differentiate what the title would be depending on whether the user's creating a new node or editing an existing node, use Devel module's dpm() function to print out the $form_state array, and check to see if there's a node ID already or not—if there is, you are editing a node; if not, you're creating a new node. Set the title appropriately.

While hook_form_alter() would probably be the most robust page (in case someone was viewing the node add form from somewhere other than node/add/[type]), you could also check the path in hook_init() and set the title there, or from a variety of other places (in Drupal 7, hook_page_alter() perhaps).


There is a problem in Drupal core. I made an issue for it here and a patch has been supplied, but it didn't work properly for me: https://www.drupal.org/node/1912458

I did get it to work by only doing part of what the patch does.

Find line 504 of modules/file/file.field.inc and change it from this:

if (($field['cardinality'] == FIELD_CARDINALITY_UNLIMITED || $delta < $field['cardinality']) && empty($form_state['programmed'])) {

To this:

if (($field['cardinality'] == FIELD_CARDINALITY_UNLIMITED || $delta < $field['cardinality'])) {

I don't know if this produces adverse side effects anywhere else, but it does allow services to be used in the way you are using it.


What is the "right" way to track a custom patch to a contributed module?

I keep all of those in the projects make file, which makes it easy to apply the patch again should the module be updated without it commited, and remove it when it's no longer necessary.

This answer makes the most sense in context of my answer to the question Should I source control contribed modules in my project?.


Module requires Composer install of third-party library

For anyone else facing a similar problem, I just wanted to add that, as of Aegir 3.18, it seems possible to configure Composer to download and install third party libraries for Drupal modules from https://asset-packagist.org. Of course, those libraries should exist as Composer packages on the asset-packagist site.

I was able to get this going yesterday by following the instructions at the link below, but after a lot of trial and error as the docs are not always accurate, especially in terms of the line endings, JSON syntax etc.:
https://www.drupal.org/docs/develop/using-composer/using-composer-to-install-drupal-and-manage-dependencies#third-party-libraries

The composer.json file to edit is at the Aegir path /platforms/drupal-x.x.x/composer.json


As reported in Accesslog removed from the Statistics module, the module with that functionality is the Better Statistics module, which (at the moment I am writing this answer) doesn't have a Drupal 8 version.

  The accesslog and all associated reports have been removed from the core Statistics module. This functionality exists in contrib at http://drupal.org/project/better_statistics.

There is a issue open for porting the module to Drupal 8, Port Better Statistics to Drupal 8, which was created after the change record.

The History module in Drupal core doesn't keep a log for the access to all the pages, but it keeps a log for the access to nodes. If you are interesting just to the users who accessed a node, that could help you.


You are looking to integrate your MTA's (mail transfer agent = mail server's) virtual user table with something that can be managed through code running through Drupal. There are multiple ways to do that and the exact mechanics will depend heavily on the particular MTA you are using, but the general idea will be the same. As for specific instructions for your particular MTA, I'd try Google or ServerFault.

That said, if I can be allowed to use Postfix as an example, what you are looking for seems to be configured primarily through the virtual_mailbox_maps configuration setting. Official documentation, Postfix and MySQL howto, quick guide to get you started and Virtual mailhosting guide with Postfix on Gentoo.

Once the MTA looks to a database table for address translation, adding a forwarding address becomes a simple INSERT SQL query with appropriate values. If everything is set up correctly it should then take the e-mail that was received and redirect it to the user's real e-mail address.

Oh, and one more thing; make very sure you properly validate the user's provided e-mail address, so you don't become a source of spam for others. Send them a short e-mail with either a link to click on or a code that needs to be entered to activate the forwarder.


Views-based search not returning expected results

May depend on your version of Views, as there appear to be some known issues, depending on the Drupal Views version.

Drupal 7: Views search not returning correct results for multiple term searches
https://www.drupal.org/node/1615438
https://www.drupal.org/node/1948510


Is there a module that can list all the views on a system?

I don't think a module already exists for that.

To build it yourself, you'll need to implement hook_views_data(), and describe the views_view, and views_display tables.

These are the columns you'll have available from the views_view table:

name
description
tag
base_table
human_name
core

And from views_display:

vid (view id)
id
display_title
display_plugin
position
display_options

display_options is a serialised PHP array of data (containing the path and other specific information), so unless you implement some pretty advanced field/filters/etc handlers you won't be able to filter on those specific elements, or use them as fields.


Support for memberships was just added in version 4 of Webform-CiviCRM integration. If you upgrade to that version then membership types will become available.


instant upload after select file in a file or image field (quit upload button)

You can also use Drag & Drop Upload

Here you just browse the file.

select the file and it will be automatically upload.


Write this function in your template.php file, which is located in your theme (untested):

function MYTHEME_preprocess_page(&$vars) {
  $alias_parts = explode('/', drupal_get_path_alias());

  if (count($alias_parts) && $alias_parts[0] == 'booking' && $alias_parts[2] == 'reschedule') {
    $vars['theme_hook_suggestions'][] = 'page__bookingtemplate';
  }
}

Then you can create a new template file which is called page--bookingtemplate.tpl.php and after clearing the cache, it should work.

Credits to Clive for this post.


Multisites placed inside sub site folder?

Good question. It is possible to run drupal multisites as a subdirectory even if your Drupal installation is in a subdirectory itself.

  Side note: the /sites/ directory in your examples is not necessary.

Given that your main Drupal install is accesible at domain.com/drupal the solution is to use symlinks to tell your webserver that the document root for domain.com/drupal/multisite is the same as your main drupal install (domain.com/drupal).

The first step is to create a directory for the multisite. The syntax is a little different for subdirectory multisites: domain.com.multisite. So, inside your /sites directory, you will have something like this:

-|/sites
--|----/all
--|----/default
--|----/domains.com.multisite

Place a copy of default.settings.php in domains.com.multisite and rename it to settings.php.
Then create the symlink described above by running the following command from your main website's docroot (not Drupal's docroot, the main website's docroot - usually public_html or something similar):

ln -s [drupal-directory-name] [multisite-directory-name]

Or, using the names in our example above:

ln -s drupal multisite

See Drupal's multisite documentation for more information.


How do I programmatically create a list of new users?

If you are having trouble with drush_invoke, try drush_invoke_process, which has two advantages over drush_invoke:

It is executed in a separate process, so you can set options explicitly, and do not need to worry about option "pollution" from previous calls to drush_set_option()
The results of the operation, including all log messages, is returned as structured php data, so you have a better idea of what was done.

Example:

$values = drush_invoke_process("@self", "user-add-role", array("Premium members"), array('mail' => $val));

You will find the output of the command in $values['output'], and structured results (if available) in $values['object'].

Note that in general, there is nothing wrong with calling drush_invoke as you are doing above; you may use that technique if it works for your use case. It is likely to be faster, but may sometimes be fragile.


How to make my blocks switch to another block when session was set?

You can do this in code:

if (\Drupal::currentUser()->isAnonymous()) {}

Or in block layout by configuring the visibility of roles:

When the user has the following roles

Anonymous user
Authenticated user
Administrator

The first block for anonymous users and the second block for authenticated users.


Site stuck on maintenance mode only for a single page

I came across this scenario a few days back. In my case, the site was displaying maintenance page only on registration related pages in dev server.

After several hours of struggle, it was identified to be a huge secondary database (from PROD) which was connected only on enrollment related pages. I emptied the huge tables and the pages started loading seamlessly.

Hope this might help someone.


Selecting correct entities and fields in Rules

Rules Module

Rules has a built-in debugger that can be fairly useful to see what was passed to your rule.  It can be found and enabled at admin/config/workflow/rules/settings

Devel Module

The Devel module is another tool that is very valuable when debugging Rules. If you are working with custom code there are two functions in particular that will save you tons of time.

dd() and dpm().

dd() will write debugging data to file.  Generally to /tmp/drupal_debug.txt on *nix based systems.

dpm() will display debugging data to screen, but may be a little less useful when debugging rules as redirects at times can cause issues while viewing.

Usage Examples

dpm($form);
dd($form_state);

Rules is an incredible module, but debugging can be a pain for sure.  I would be happy to clarify if the above doesn't answer your question.


Your code contains two errors:

You are using a variable which has not been initialized
You are passing the wrong arguments to format_interval()

The required arguments are:

$interval
It's not a timestamp, but the number of seconds until now. In your case, you should use time() - $node->changed.
$granularity
It's the number of units that are shown; if you pass 2 as value for $granularity and the interval is for 1 year, 3 months, and 2 weeks, format_interval() will return "1 year 3 months".
$langcode
It's the language code for the language to use. If you are hard-coding the language to be Arabic, you should use "ar".


Can you display a variable in a Drupal webform component label?

You can alter form elements, including labels with hook_form_alter(). Use dpm() (from the Devel module) to inspect the $form array to find the value you want to change.


Is the tags section valid in the info.yml file?

I do not think it is valid yet. There is an issue on this

https://www.drupal.org/project/drupal/issues/1868444


I don't see a way to get a list of all core templates, but if you want to override them here is a perfect guide, Drupal core template naming


Is EntityFieldQuery as sophisticated as the Database API?

I was wondering if EntityFieldQuery is just a layer of abstraction on top of the database query builder.

Yes, that's exactly what it is. It's not subclass of SelectQuery or anything higher up the chain, though.

  For example can I use addExpression and isNotNull in an EntityFieldQuery, for example?

No, EFQ doesn't implement those methods. You can see what methods are available by looking at the source.

  Or, is it separate and not as sophisticated.

Yes it's separate, "not as sophisticated" can't really apply since the functional differences between EFQ and a SelectQuery are intentional. They're not supposed to do the same thing, an EFQ is intentionally limited to functionality that makes sense for entities only.

However, an EFQ will eventually run a SelectQuery anyway, which you can alter just like any other query. So you can make it as "sophisticated" as you need to.


How do I add custom meta tags to a view page?

Current version of Metatag module includes a submodule "Metatag: Views".
Enabling this, you get a new section in your views editor to set all metatags available (specific tags are available in other submodules in a very drupal way).


theme_hook_suggestions for string wildcard

What you'd need to do use the theme suggestions. So you'd have 1 template file e.g. page--fixed.tpl.php

Then in template.php you could have an if statement e.g.:

function THEME_preprocess_page(&$variables) {
 $arg1 = arg(1);
 $arg0 = arg(0);
 if($arg0 == 'models' && ($arg1 = 'model-names' || $arg1 = 'anothermodel')){
  $variables['theme_hook_suggestions'][] = 'page__fixed';
 }
}


You can control access to nodes with

hook_node_access

For example, to restrict node viewing on node/[nid] pages:

/**
 * Implements hook_node_access
 */
function MYMODULE_node_access($node, $op, $account) {

  // If viewing node and URL path is node/[nid]
  // where [nid] is current $node->nid
  if($op == 'view' && arg(0) == 'node' && arg(1) == $node->nid){
    // Deny access to view current node page
    return NODE_ACCESS_DENY;
  }

}

You can add your own conditions to get more specific about access control there.

If you want to deny access to all node/%node/view pages, you can do it quite simply with:

hook_menu_alter

For example, set the access callback to FALSE

/**
 * Implements hook_menu_alter
 */
function MYMODULE_menu_alter(&$items) {
  // Disable the node view page at node/%node
  $items['node/%node']['access callback'] = FALSE;
}


How can I print e-mail messages sent by Drupal to the screen for debugging purposes?

The way I debug email is by using the TestingMailSystem class:

// Use testing mail system.
variable_set('mail_system', array('default-system' => 'TestingMailSystem'));

You can then capture and print the mail contents with the following statement:

$mails = $this->drupalGetMails();
debug($mails); // $mails is an array holding all mails sent.

Here $this is the current testing class (instance of DrupalWebTestCase).

This is very simple to use as part of automated testing (using the Testing framework that is part of the Drupal core).

If you don't want to be troubled by setting up the full Testing framework, an alternative method for debugging email is to hijack drupal_mail.

To do this you need to install the Devel module and
edit the core mail.inc by replacing the standard drupal_mail with the following function:

/**
 * Function to debug mail.
 */
 function drupal_mail($module, $key, $to, $language, $params = array(), $from = NULL, $send = TRUE) {
  dpm('Using hacked version of drupal_mail.');
  dpm($params, 'mailbody');
  // Print out more arguments if required.
  return TRUE;
}

And yes, this is hacking core, so:  1) Don't do this on a production site; and 2) Remember to restore mail.inc with a pristine version when done debugging.

Note: The latter method is a rather nasty hack (but I've found it useful a few times).  Using the Testing framework to debug mail is the recommended method.


Get number of items in cart of current anonymous user

To load the current anonymous user cart, you can use commerce_cart_order_load something like this should suffice:

It gets the product count as separate line items and the product quantity including number of items per line item.

// Can leave blank or provide UID
$uid = 0; // anon
$product_count = 0;
$product_quantity_count = 0;

// Load cart order
if ($order = commerce_cart_order_load($uid)) {
  // Let's use the wrapper because it rocks
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);

  // Loop over line items and increment product counter
  foreach ($order_wrapper->commerce_line_items as $delta => $line_item_wrapper) {
    // If line item is a commerce product type
    if (in_array($line_item_wrapper->type->value(), commerce_product_line_item_types())) {
      // Increment counters
      // Individual product line item
      $product_count++;
      // Number of items of product line item (quantity)
      $product_quantity_count += $line_item_wrapper->quantity->value();
    }
  }

  // Debug output
  drupal_set_message(t('User %uid has %count products in cart with a total of %quantity items',
    array('%uid' => $uid, '%count' => $product_count, '%quantity' => $product_quantity_count)));
}


How to create a view of nodes *without* comments from currently logged in user

REVISED ANSWER

This can be accomplished in two step process.

Create a very plain view to only show node titles. Do not filter it except by type if you wish, and do not place any contextual filters on it. For this answer I created a view called 'not_commented' with a page display of 'page_1'.
Create a custom module. We will use it to alter the views query. For this answer I created a module called 'custom'.

Add this code to custom.module:

function custom_views_api(){
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'custom') . '/includes/views',
  );
}

Now create a folder 'includes' in the module folder, and then a folder 'views' inside the includes folder so that the folder structure is : sites/all/modules/custom/includes/views

Create a file custom.view.inc within folder views. Place this code in the file:

<?php

function custom_views_query_alter(&$view, &$query){
  if ($view->name == "not_commented" && $view->current_display == "page_1"){
    // get all nodes commented on by this author
    $sql = "SELECT n.nid, COUNT(n.nid) " .
      "FROM {node} n LEFT JOIN {comment} c ON n.nid = c.nid " .
      "WHERE (c.uid = :uid AND n.status = '1') GROUP BY n.nid";
    global $user;
    $query_2_result = db_query($sql, array(':uid' => $user->uid))->fetchAllKeyed(0,0);

    $query->where[1]['conditions'][] = array(
      'field' => 'node.nid',
      'value' => $query_2_result,
      'operator' => 'not in',
    );
  }
}

Clear you cache.

Please replace module and views/display names etc. as applicable. If there are any problems please inspect the $query object to see if you have the right where array key etc.


I would probably suggest to use Workbench Moderation instead of using the Workflow module. I don't know your exact use case, but I've had a lot of luck with the Workbench suite.


Altering a query like this is really not recommended.

First of all, you should use SelectQuery methods provided by "$query" variable.
You can get an array of query conditions by using "SelectQuery::conditions()" method.

Be careful, if you want to alter this array get the array like the following snippet :

$conditions =& $query->conditions();
//Now you can use and alter your query conditions.

Some others tips related to your code :

1) You can tag your query in Views UI

Add a tag to your Views Query :

With this trick you can define a special hook for altering all query who use this tag. This hook is "hook_query_TAG_alter"

Now you can use this code :

function YOUR_MODULE_query_my_tag_alter($query) {
  $conditions =& $query->conditions();
  //This condition is useless now
  //if ($view->vid == 7) {
  //Check conditions and do your updates

  //}
}

2) Careful to the module weight

When you alter something, other modules can do it too...
This order is determined by the module weight saved in the "system" table.

By using your own tags on your query, other modules should not know about this tag and should not alter your query.

You can change your module weight but this is not the thread of this post

Links

SelectQuery Api

SelectQuery::conditions() method

Query Alteration recommandations by Drupal

hook_query_TAG_alter

Change Module Weight


Panels view settings - how to preprocess the 'more' link

Change the text of the link in the views module. On your views block admin page. Click on more link and change text there


adding a phone field in out of stock form of commerce stock notifications drupal commerce

Ash joshmiller noted, you can add a field using a form alter and then add another custom submit handler to take the submitted values and do something with that data. You'll have to provide your own DB or come up with some method to store that data on the customer or product.


$ournewtype = 'voucher';
$sql = 'SELECT nid FROM {node} n WHERE n.type = :type';
$result = db_query($sql, array(':type' => $ournewtype));
$nodeids = array();
foreach ($result as $row) {
  $nodeids[] = $row->nid;
}
node_delete_multiple($nodeids);
node_type_delete($ournewtype);


How can I add a view to the front page news feed?

You can create a View block and display this block in any region like other blocks. Then make this block to show only listed pages, which is <front>.


Drupal 7 how to programmatically display resent comment from all article with author image and comment content?

comment_load($cid) should load the entire comment object based on the comment id ($cid).

What you do with it then is up to you.


What may cause Undefined index in drupal_retrieve_form when uploading an image?

You need to either move hero_block_search_box_edit_form() from hero_block_search_box.inc to your .module file, or at the top of your form definition (or hook_form_alter() if that's what you are using), you need to add the following:

form_load_include($form_state, 'inc', MODULENAME, 'hero_block_search_box');

where MODULENAME is the module key (machine name) of your module. Make sure you don't include the .inc in the last parameter - I didn't forget it, I left it out on purpose.


Disable an option for the select form field

Disabling an option may be tricky to achieve (Using form_alter to disable ONE option of a select field) so I'll recommend you to look at optgroups as an alternative. The Drupal form API documentation doesn't explain it but the API allows nested array for the options, have a look at form_select_options() and the <optgroup> part.
You can write this code:

$form['feed'] = array(
    '#type' => 'select',
    '#title' => t('Display of XML feed items'),
    '#options' => array(
        'Titles only' => array(,
          'teaser' => t('Titles plus teaser'),
          'fulltext' => t('Full text'),
        ),
        'Titles only 2' => array(,
          'teaser2' => t('Titles plus teaser 2'),
          'fulltext2' => t('Full text 2'),
        ),
    ),
    '#description' => t('Global setting for the length of XML feed items that are output by default.'),
);

Have a look at Drupal 6 forms and optgroup arrays.

Edit: to clarify this is an alternative and not a direct answer.


I put this towards the end of settings.php (Drupal 7). It worked for me:

$conf['x_frame_options'] = 'ALLOW-FROM .facebook.com';

(I also use SSL/https (Let's Encrypt) on this site.)

x_frame_options don't allow for multiple values, i think. So 'allow-from domain.com' might disallow SAMEORIGIN. From this post it looks like the module Security Kit allow for setting Allow-From dynamically based on the current page request. I haven't tested it myself.


How do I create a View filter by a parent taxonomy term?

Please follow such steps for getting your result (Child Items)

1)Add Taxonomy term: Term ID in CONTEXTUAL FILTERS.
2)Add Taxonomy term: Parent term in RELATIONSHIPS. (leave Require this relationship unchecked.)
3)Add Taxonomy term: Parent term in filter section. select great than 0.
4)Do not forget to filter your taxnonmy term in mycase Taxonomy vocabulary: Machine name (= airports).
5)Add Taxonomy term: Rendered Taxonomy term to your fields , select relationship to parent , check the Exclude from display.
6)In setting, under FORMAT section. In grouping field 1, select (Parent) Taxonomy term: Rendered Taxonomy term.

You should good to go. you can use view tpl to add more class base on the group.
 I have enclose my screenshot for references.


How do I unset hook_field_storage_load()?

TL;DR hook_module_implements_alter() is not invoked when mongodb_field_storage_field_storage_load() is needed. You cannot achieve what you are trying.

The function that invokes hook_field_storage_load() is field_attach_load(), which contains the following code.

// Invoke hook_field_storage_load() on the relevant storage backends.
foreach ($storages as $storage => $fields) {
  $storage_info = field_info_storage_types($storage);
  module_invoke($storage_info['module'], 'field_storage_load', $entity_type, $queried_entities, $age, $fields, $options);
}

module_invoke() calls module_hook(), which contains the following code.

  $function = $module . '_' . $hook;
  if (function_exists($function)) {
    return TRUE;
  }
  // A
  // If the hook implementation does not exist, check whether it may live in an
  // optional include file registered via hook_hook_info().
  $hook_info = module_hook_info();
  if (isset($hook_info[$hook]['group'])) {
    module_load_include('inc', $module, $module . '.' . $hook_info[$hook]['group']);
    if (function_exists($function)) {
      return TRUE;
    }
  }

Since mongodb_field_storage_field_storage_load() is contained in mongodb_field_storage.module, your implementation of hook_module_implements_alter() will not be called. In fact function_exists($function) returns TRUE when $function is equal to 'mongodb_field_storage_field_storage_load', and the part of the code after the line marked with // A will not be executed.


Are you sure you want to empty the cart? Or do you just want to limit the quantity of any product to one?

I recently had a similar situation. I added a hook_form_alter to hide the quantity so it can't be readily changed. There's not a specific FORM_ID you can use for an add to cart form because they get a hash added to them, so it looks like this:

function my_module_form_alter(array &$form, FormStateInterface $form_state, string $form_id){
  if (strpos($form_id, 'commerce_order_item_add_to_cart_form_') === 0) {
    ... plus any other logic specific to your use case

    _my_module_specific_add_to_cart_form_alter($form, $form_state, $form_id);
  }
}

function _my_module_specific_add_to_cart_form_alter(array &$form, FormStateInterface $form_state, string $form_id){
  // Doesn't make sense to buy more than one, so hide it.
  $form['quantity']['#type'] = 'hidden';

  ... plus any additional changes, e.g., I have this:
  // There's only one variation, so hide it. (
  $form['purchased_entity']['#type'] = 'hidden';
}


First off if the content is only text and its size is not very big I recommend you strongly not to use Ajax , unless you can do it using views in the following way:

Be sure to enable the Ajax in views:

now this code will load the view.

$("links_click").click(function(){
            $.ajax({
                url: Drupal.settings.basePath + 'views/ajax',
                type: 'POST',
                dataType: 'json',
                data: 'view_name='+your_view&'view_display_id='+view_display_id,
                success: function(response) {
                  var output = response[1].data;
                  $(".your_container").html(output);
                },
                error: function(data) {
                    alert('An error occured!');
                }
              });
        });

for more detail visit this link.


How can I add text into ckeditor textarea in drupal 7?

Assuming you want to set some value at the beginning -

Get the id of the form. https://www.drupal.org/project/get_form_id

Get the id of the field you want to alter.

Make a small custom module, with hook_form_alter() and set #default_value to that :

function YOURCUSTOMMODULENAME_form_alter(&$form, &$form_state, $form_id) {
  if ( YOUR_FORM_ID == $form_id) {
    $form['YOUR_FORM_ID']['YOUR_FIELD_ID']['#default_value'] = 'some default text'
  }
}

For adding some text after taht that, use jQuery.

$('#input-field-id').val('some text');


I was able to find a solution by using two separate filters.

The first filter will be a relative for the current day.  It should have an operator that is greater than or equal to today.

The second filter will be a relative day as well.  It will have an operator that is less than +7 days.

This will allow you to filter views by the current day plus seven days.


How to integrate the Fusioncharts library with Drupal 7?

There's a couple of problems in your code:

include($path.'/Code/PHP/Includes/FusionCharts.php'); you have to use ./ to include files.
include($path.'/Code/FusionCharts/FusionCharts.js'); you should use drupal_add_js() to include javascript in your code.
FusionCharts documentation seems a little old as Column3D.swf is now FCF_Column3D.swf

Here is a working example, I haven't used the librarie module but you should be able to adapt it easily. I put this code in a node with PHP filter activated.

<?php
$file = './sites/all/libraries/FusionChartsFree/Code/PHP/Includes/FusionCharts.php';
if (is_file($file)) {
  require_once $file;
}
drupal_add_js('sites/all/libraries/FusionChartsFree/Code/FusionCharts/FusionCharts.js');

//Create the chart - Column 3D Chart with data from Data/Data.xml
echo renderChart("/sites/all/libraries/FusionChartsFree/Code/FusionCharts/FCF_Column3D.swf", "/sites/all/libraries/FusionChartsFree/Code/PHP/BasicExample/Data/Data.xml", "", "myFirst", 600, 300, false, true);

?>


How to print external html output in form_submit

You might try using the drupal api function drupal_set_message()

https://api.drupal.org/api/drupal/includes!bootstrap.inc/function/drupal_set_message/7

so in your case:

drupal_set_message($some_var); // will display the rendered html as a status message


You are able to create a single block or page in views with different sort criteria using attachments in views

So create a view with some criteria and add an attachment like above and override the sort criteria as you need
Then add your attachment to your page or block as below

Here is a post which explains this in detail.


this looks like a collation issue in your database tables. Perhaps you copy and pasted some text from a Word file or other file that had a weird character set encoding and when it was saved to the database the proper text was lost in the transition.

I recommend looking at where the text in your footer is coming from originally, a foreign webpage, an MS Word file, an XML file -- and what encoding it has.

Then I would recommend you look at the Collation Fixer module which is designed to help with this issue. It will properly set your set tables to 1 Collation -- you must then provide the correct text/prose/verbiage into your footer so that its in the same character set the database expects.

  A 'runtime' requirements checker (admin/reports/status) for checking
  all database tables have the right database collation (probably very
  MySQL centric).

  Offers the ability to fix tables with wrong database collation.

  The collation is either specified in your database settings or in
  hook_schema() or hook_schema_alter().

  This can be useful when developing non-english sites.

  Example of specifying in database settings in settings.php (will
  affect all tables - it's probably better to do it in hook_schema() or
  hook_schema_alter()):

<?php
$databases = array(
  'default' => array(
    'default' => array(
      'database' => 'my-db',
      'username' => 'my-user',
      'password' => 'my-password',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
      'collation' => 'utf8_danish_ci',
    ),
  ),
);
?>


How to add cursor to text field on page load?

You can actually do it with html autofocus now - no need for JS.

You should be able to do it with this:

<?php
  // inside a hook_form_alter()

  $form['field'] = [
    '#type' => 'textfield',
    '#attributes' => array('autofocus' => TRUE)),
  ];


Change the images URI values within an array

I think you will have success with

file_create_url("public://pizapuck.png");

so

for ( $i = 0; $i < count($resultados); $i++){
  $resultados[$i]['uri'] = file_create_url($resultados[$i]['uri']);
}

would loop through your results and change them. (untested code typed directly in here).


Can I set "$conf["image_allow_insecure_derivatives"] = TRUE" in settings.php file?

It is not a critical security issue perse. But it can expose your site to DDOS attacks. So you can fairly enable this setting and you can disable it if you face any DDOS attacks that targets your site.

You can find more about this issue on https://www.drupal.org/SA-CORE-2013-002

  Drupal core's Image module allows for the on-demand generation of
  image derivatives. This capability can be abused by requesting a large
  number of new derivatives which can fill up the server disk space, and
  which can cause a very high CPU load. Either of these effects may lead
  to the site becoming unavailable or unresponsive.


You can wrap all the entity save calls in a further transaction with Connection::startTransaction for a given database connection. Inject the database service into the form using FormBase::create

Catch using DatabaseExceptionWrapper and rollback :-). This is similar to Drupal 7 behavior as well.

It would be best to provide a unique name for the transaction as the transaction stack is fairly basic.


QR Barcode automatic creation from Nodes new or previously created

Since my original posting, a new module appeared. So I ultimately chose this module: drupal.org/project/page_url_qr_code_block does the job spot on and creates Node QR Codes on the fly via a Block. There maybe other ways, but for now, this is it.
Thanks all.


Unauthorised users to view homepage without menu

Create a new template for your front page name it page--front.tpl.php

Create a variable which assign a role to a temporary variable in your template_preprocess_page(&$vars) like

function THEMENAME_preprocess_page(&$vars) {
  global $user
  if(drupal_is_front_page()) {
   if(in_array('anonymous', $user->roles)) {
      $vars['navigation'] = false;
    }
  }
}

then in you page--front.tpl.php just check if($vavigation) ..


Create a custom function to convert a field data

In Drupal 7, I can create a custom function in the template.php file

To cut a very long story short, in Drupal 7 you should ideally have been  calling that function in a preprocess function, to prepare variables for the template, rather than calling it from the template directly.

In Drupal 8 it's now Fine™ to call functions directly in the template. But now you can't use PHP directly, so you need to write a Twig extension.

It's very easy, core even has its own that you can copy from. The important thing is to register the service class with a twig.extension tag, so the system picks it up.

See this blog post for a full example.


How to use views to make queries on the webform (or entityform) results and show in a node?

The newest version of webform (7.x-4.0-alpha10) allows views to display webform submissions right out of the box. Although you cannot revert to an older version after upgrading to 4.x, so it's important to back up your database. But after you have 4.x installed, you will see an option when you create a new view to show content of type "webform submissions". You can also read up on how to accomplish the task in older versions of webform here: https://drupal.org/node/1658784


A couple places to start looking:

Block configuration

Is the menu placed as a block with specific logic that prevents it from appearing on certain pages. Go to 'Structure >> Blocks' and see if there is a block placed for your menu. Then under 'Visibility Settings'.
Context

Is the menu placed via Context? 'Structure >> Context', look for something that has to do with the menu.
Page Manager

Is the menu part of the page template or is it specifically placed in the content section of each page?  Check out a page that shows the menu and a page that doesn't in the page manager, go to 'content' of the applicable variant and see if you can spot any differences.

With out some more information it is hard to determine what method is being used to place the menu.


What I think you are trying to do is delete a record from the database, someones 'favorite', like a bookmark on content, perhaps.

Anyway, what you need is an argument in the URL, the best being an ID - even better if it is an entity id that could be provided as a loaded argument for you (like node/%node - the %node argument provides the loaded node instead of just node id).

Assuming the argument is simply an integer of a database record, you could do:

function delete_favourites_menu () {
  $items = array();
  $items['delete_favourites/%'] = array(
    'page callback' => 'delete_favourites_page',
    'access arguments' => array('delete_favourites_permission'),
    'page arguments' => array(1),
    'access callback' => TRUE,
    'delivery callback' => 'ajax_deliver',
  );

  return $items;
}

function delete_favourites_page($favorite_id) {
    // code to delete the favorite_id record
    $commands = array();
    $commands[] = ajax_command_alert('Favorite has been deleted.');
  return array('#type' => 'ajax', '#commands' => $commands);
}

However, your access callback should not be TRUE, that means anyone can hit this URL and there is no upfront access checking. I hope you are handling that in your callback, but ideally you should use permissions or a callback to perform more complex checking.

The ID will always be passed to the page callback function now, and you could perform the delete operation there.

The delivery callback has been set as ajax deliver, which tells Drupal the page will return ajax commands. The above code contains a very simple alert, which will fire when the callback is performed.

There is a decent amount more that can go into this when wanting to implement AJAX interactions via menu items and callbacks. But first you need to figure out / fix your URL structure so you can pass arguments and not strings / query strings, and you'll also want to implement access checking so only the user who owns that record (or admin) can delete it.


How do you combine exposed filter string text searches into one input field for Drupal 7 Views?

If you want to be super-flexible in your search, essentially searching through the whole listing rather than just a particular field or two, I'd suggest you simply add the 'Search Terms' filter.

If you go to add another filter to your view, you can narrow the options by the 'Search' related ones and select the 'Search Terms' one:

You can name it anything you want, but it will essentially search through your entries the way a regular search does - so, by default, it will search through all fields that are displayed on your node, not just the ones you're displaying in your view at the moment.  Hope that makes sense - just another option to consider in the mix.  :-)


How to re-upload an image but not removing it

It's not really clear what you're trying to achieve, but basically there are two ways to go:

Don't use an image field, but use an "entity relation" to a media entity instead. (Media is a core module >= Drupal 8.4, or a contrib module <= Drupal 8.3)
User revisions: Create a new revision of your node every time you update the image field. You then can view older versions of the image in the version history of your page.


Installing Drupal with existing Pantheon site?

To install Drupal on an existing Pantheon site you don't need to install or copy anything to your local computer; you can just work on the Pantheon development environment in the cloud using the dashboard workflow. Pantheon hosts three distinct environments for each site: development, testing, and the live production site. You can install Drupal plus modules and themes on your development site. Once you're satisfied with the results, you can push your site code to the test environment for user testing and then to the live environment to serve the site from your domain, once you've launched with a paid site. The workflow tools let you push code from dev->test->live, and also clone your database and files between environments. Typically you'll install Drupal and configure the modules on the development environment before launching the site, then clone that database up to live to retain all the content changes. However, post-launch you would only want to copy the live database and files down to development and testing environments, as the live production environment is the canonical source of site content. You'll want to review Pantheon docs for how to use the workflow, both pre-launch and post-launch:

https://pantheon.io/docs/articles/getting-started/


How to configure Compass module with Basic theme?

Well the only real answer i can give is set up a real webserver on Unix system with ruby (rails or without rails) and use whatever you want. I did not managed to get it running on windows. But ---- windows, lads


Is there a module for automatic menu translation?

Short answer: no

Long answer: I wouldn't recommend to try to 'automatically translate' any of your content – especially not translating the navigation while keeping the content in the original language. You will probably rather quickly have lots of frustrated users (or no users at all) that don't find content in their language, even when they are 'clicking the right link'.

Additionally you will probably be penalized by search engines for duplicate content.

Maybe you should ask over at the ux forum what people think of the idea? I suppose hardly anybody would recommend to have that type of mis-leading navigation structure on a website.

There are however various modules to tranlate menues (and fields and taxonomies etc.) on the fly, while you are creating new content items – but that you probably already know – and that's probably not what you were looking for.


Print #field_suffix with drupal_render($form['field_custom_text_field'])

Try

$form['field_url']['#field_suffix']='text goes here';

Also, in your example, the suffix is being set on field_url but you are printing field_reg_site_url. That could be causing some confusion.


Update order status with administrator comment

In Commerce this is not provided as a part of core.
It is provided by the Commerce Message module.
In addition to that, the Commerce Backoffice module provides an improved view that allows you to view a summary of an order (and send a message) directly from the order view.

Both are included in Commerce Kickstart, in case you want a quick demo.


How to allow anonymous user register Civicrm event without create drupal account

Edit the profile that you are using for the event registration and under advanced settings (at the bottom)

select "No account create option" radio and "save"

Good luck!


To specify the path match for node/[nid]/edit pages, you can use

node/*/edit

as the page match string there.


How to get rid of Deadlocks and Lock time out type issues?

Read and follow this post; it assumes InnoDB.

In particular, see the part saying to add the following to the settings.php file.

$databases['default']['default']['init_commands'] = array('isolation' => "SET SESSION tx_isolation='READ-COMMITTED'");


Oh - it is quite simple :)

{{ drupal_view('testview', 'block_1', node.id() ) }}

sorry still learning basics :D


What is the purpose and differences between drupal_goto(),drupal_redirect_form() and $form_state['redirect']?

First off, drupal_redirect_form() is not a function that a third-party module should use; it's a function used by Drupal code, and it is only used from two Drupal functions. In your code you should use drupal_goto(), or $form_state['redirect'].

The difference between drupal_goto(), and $form_state['redirect'] is that a form submission handler should never use drupal_goto(), which should be used, for example, from a page callback for a page without forms. The main reason not to use drupal_goto() in a form submission handler is that calling it would stop the other form submission handlers to be invoked. drupal_goto() contains the following code:

  // Drupal 6.
  // Even though session_write_close() is registered as a shutdown function, we
  // need all session data written to the database before redirecting.
  session_write_close();

  header('Location: ' . $url, TRUE, $http_response_code);

  // The "Location" header sends a redirect status code to the HTTP daemon. In
  // some cases this can be wrong, so we make sure none of the code below the
  // drupal_goto() call gets executed upon redirection.
  exit();

  // Drupal 7.
  header('Location: ' . $url, TRUE, $http_response_code);

  // The "Location" header sends a redirect status code to the HTTP daemon. In
  // some cases this can be wrong, so we make sure none of the code below the
  // drupal_goto() call gets executed upon redirection.
  drupal_exit($url);

Both exit() and drupal_exit() cause Drupal to stop running, and the output be returned to the browser; this means that other form submission handlers are not executed. Even if the form submission handler is for a form you use in your own module, you cannot know for sure how many form submission handlers need to be executed, and if your form submission handler is effectively the last one to be executed; other modules can add any form submission handler to your form. Using drupal_goto(), you are also avoiding that other Drupal code is executed; this could have any collateral effect, in the case of forms.

As per passing values to the page where the user is redirected, you can use code similar to the following one.

$form_state['redirect'] = array(
  $redirect_path,
  array(
    'query' => array(
      'foo' => $form_state['values']['foo'],
    ),
  ),
);

This snippet would cause the user to be redirect to http://your.site.domain/$redirect_path?foo=$form_state['values']['foo']. That page will get the value of $form_state['values']['foo'] in $_GET['foo'].

Consider also that, in the case you need to pass to the page where you are redirecting the user all the values submitted by the user in the form, you probably need to rewrite the code you wrote. If the page to which you are redirecting the user needs those values to, e.g., save them in the database, then that code should be in the form submission handler, and not in the other page callback. If the page needs those values to output HTML, then the form submission handler could render the output, and save it in a session variable, which is then used from the new page handler to show its own output.
In any case, all the values submitted from users in the form should not be passed to another page handler through $_GET or $_POST. Passing some of the submitted values is fine, though.


Drupal 7 and Views 3: Page Display and Random Appended Arguments in URL

5898 is just an extra URL argument in View's point of view. Views doesn't have the ability to throw 404 pages because there are "extra" arguments in the URL. Views does throw 404s when there is no argument in the URL (if configured that way). In any case, you can implement something like hook_views_pre_view() and redirect the user to a separate 404 page if you see that extra arguments are found in the URL. This should take like 15 minutes for a Drupal developer to do.


How can classes be removed from panel panes?

By admin panel. When you edit a panel page, click on a cog of the pane that does not need styles. Check styles. Choose no styles. There few options. I do not remember exactly how it is called. It exists there. Check it ...


Recommendations for security testing a Drupal site?

Here's some slides on automated security reviews using Drupal tools
Here are some manual steps for a review
You can try to improve password strength
And to make all passwords stronger, Two Factor Authentication is helpful
Security Review is a good call
As is Paranoia
And Cracking Drupal is a good resource (disclosure, I wrote it)


How to add a button that jumps to an external link in the content type?

nofollow: Links to an unendorsed document, like a paid link. ("nofollow" is used by Google, to specify that the Google search
  spider should not follow that link)

  source: HTML  rel Attribute

All you have to do is write your link like this:

Buy Now


When you create the view exposed filter you can give it a name. You use the default name it gives you, or whatever you choose it to be. See attached image.


The fully loaded node object should be available as a variable.  You then need to know the field name that it is attached as (ie, the machine name from the manage fields tab on the content type).  Once you have that, you should be able to use field_get_items() to check for actual values on that field

function THEMENAME_preprocess_node(&$variables) {
  $node = $variables['node'];

  if (field_get_items('node', $node, 'field_foo') !== FALSE) {
    // do something
  }
}

Just note that this checks for an actual value in the field, not that the field is on the particular content type.  For that, you need to use field_info_instances().

function THEMENAME_preprocess_node(&$variables) {
  $node = $variables['node'];
  $fields_info = field_info_instances('node', $node->type);

  if (isset($fields_info['field_foo']) {
    // do something
  }
}


Once you get the event working, all you have to do is create an instance of the Logger Class in the Logger folder inside your module.

In here:
 /drupal_root/web/module/custom/my_module/src/Logger

And the class will be something like:

namespace Drupal\my_module\Logger;

use Drupal\Core\Logger\RfcLoggerTrait;
use Psr\Log\LoggerInterface;

class SendToEmail implements LoggerInterface {

  use RfcLoggerTrait;

  /**
   * Logs with an arbitrary level.
   *
   * @param mixed $level
   * @param string $message
   * @param array $context
   *
   * @return void
   */
  public function log($level, $message, array $context = []) {
    //Building the parameters for the email
    $params['level'] = $level;
    $params['message'] = $message;
    $params['context'] = $context;
    $this->sendEmail($params);
  }

  /**
   * @param array $params
   *
   * @return null
   */
  public function sendEmail($params = array()){
    //Variable declaration
    $module = 'my_module';
    $key = 'my_module_message';
    $to = "email@email.com";
    $from = "email@email.com";
    $language_code = \Drupal::service('language_manager')->getDefaultLanguage()->getId();
    $send_now = TRUE;

   $mail = \Drupal::service('plugin.manager.mail')->mail($module, $key, $to, $language_code, $params, $from, $send_now);
    return $mail;
  }
}


How to use nodereference_select in custom form (set default value) D6

I've managed to use such a field widget in a custom form in the following manner

  $field = content_fields('<field name on a node type>', '<node type that uses this field>');
  $form['#field_info']['<field name on a node type>'] = $field;
  $form += content_field_form($form, $form_state, $field);

I don't know if it would work without a node type actually having such a field.
I had a node type with that reference so I could "invoke" that.

The resulting form element does not look like a simple select element, it does not have '#options' and '#default_value' is fancy too.


function ftf_product_form_node_form_alter(&$form, $form_state) {

  if($form['#node']->type == 'YOUR_NODE_TYPE'){
    $products = db_select('ftf_product')->fields(NULL, array('pid', 'nid', 'name', 'font_ref', 'description', 'app', 'web', 'desktop',  'avangate_desktop', 'avangate_web', 'avangate_app'))->condition('nid', $form['nid']['#value'], '=');
    $result = $products->execute();
    foreach ($result as $record) {
      $defaults[] = $record;
    }

    if(empty($form_state['num_products'])) {
      $results = $products->countQuery()->execute()->fetchField();
      $form_state['num_products'] = $results;

      if($form_state['num_products']  == 0) {
        $form_state['num_products'] = 1;
      }
    }

    $form['products'] = array(
      '#type' => 'fieldset',
      '#title' => t('Typeface products'),
      '#collapsible' => TRUE,
      '#collapsed' => (($defaults[$form_state['num_products']-1]->name && !$_SESSION["collapse_typeface_product"])?TRUE:FALSE),
      '#weight' => 5,
      '#tree' => TRUE,
      '#attributes' => array('class' => array('container-inline')),
      '#prefix' => '

&nbsp;
',
      '#suffix' => '

&nbsp;
',
      '#description' => t('
Create, edit and delete products here. To add or edit Typeface Price Factors please visit the admin section.

'),
    );
  }
}


Drupal 8 Webform : Regular expression in conditions to check specific day of the week

I doubt that you can achieve this without some JS involved.

You can use JS RegExp.

You could try Form API #states and try to hide the desired select field if some other field's value matches your conditions.

$form['my_select_element'] = [
  '#type' => 'select',
  '#states' => [
    // Hide this field when the 'weekday' radio has 'tuesday' or 'thursday' selected.
    'invisible' => [
      ':input[name="field_weekday[und]"]' => ['value' => 'tuesday'],
      'or',
      ':input[name="field_weekday[und]"]' => ['value' => 'thursday'],
    ],
  ],
];

(#states with multiple conditions, Source.)


'You must declare "ids" as a unique array of fields in your source settings'

The way you're currently doing it doesn't look familiar, with keys and the way the fields are mapped; might just be it's a method I haven't come across though.
Either way I've always had success processing CSVs like this:
ids:
  - image_file
fields:
  0:
    name: image_file
    label: Image file

That assumes the first column in the CSV contains the unique image file name.


Hide title in Inline Entity Form with Automatic Nodetitles module?

You can use hook form alter in your custom module. For example

function my_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'node_form') {
    $form['title']['#access'] = FALSE;
   }
 }

Or better use hook_form_FORM_ID_alter. For example

function my_module_form_node_form_alter(&$form, &$form_state, $form_id) {
    $form['title']['#access'] = FALSE;

 }


You should be able to get that with:

$container_id = $variables['element']['#id'];


In Drupal 8.4 you have to set the null cache backend for an additional cache bin, so now there are three:

settings.local.php:

$settings['cache']['bins']['render'] = 'cache.backend.null';
$settings['cache']['bins']['page'] = 'cache.backend.null';
$settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';

This is because the cached pages for anonymous users moved to a separate cache bin, see the change record The internal page cache now has a dedicated cache bin.


Cron error message. table or view not found: 1146

I Had this issue sometimes ago, I deleted a field table from DB manually and this error started to showing up, A way to get rid of it is to create a table for a field, so you can use a mysql code like that :

CREATE TABLE `field_deleted_data_38d3088921` (
    `bundle` varchar(128) CHARACTER SET ascii NOT NULL DEFAULT '' COMMENT 'test',
    `deleted` tinyint(4) NOT NULL DEFAULT '0' COMMENT 'A boolean indicating whether this data item has been deleted',
    `entity_id` int(10) unsigned NOT NULL COMMENT 'The entity id this data is attached to',
    `revision_id` int(10) unsigned NOT NULL COMMENT 'The entity revision id this data is attached to',
    `langcode` varchar(32) CHARACTER SET ascii NOT NULL DEFAULT '' COMMENT 'The language code for this data item.',
    `delta` int(10) unsigned NOT NULL COMMENT 'The sequence number for this data item, used for multi-value fields',
    `test` varchar(2048) DEFAULT NULL COMMENT 'test',
    PRIMARY KEY(`entity_id`,`deleted`,`delta`,`langcode`),
    KEY `bundle` (`bundle`),
    KEY `revision_id` (`revision_id`)
)


How to create a View that shows other nodes that have the same entity reference as the current page

Here is a solution using the Entity Reference module to display other nodes that reference the same node that the current node references. No need for relationships, just follow these steps:

Make sure you're filtering the view by the content type you want to view a list of, not the one you're trying to reference.
Add a contextual filter using the entity reference field.
For the entity reference field, choose to provide a default value in PHP ¹.
Adapt the following code to your field names ² and save the contextual filter:

$node = menu_get_object();
$referenced_node = $node->field_YOUR_FIELD_NAME['und'][0]['target_id'];
return $referenced_node;
Save the view and check it out.

¹Disclaimer: PHP should never be used in the UI due to concerns with security, performance, & lack of version control. As a result, the proper way to implement this solution involves writing your own simple module that creates a block that passes the argument into the view as you render it in the block. I'm still including this because whether people ignore this warning or use it to write a module, hopefully it helped.

EDIT: If you also want to exclude the current node, you'll need to add an additional contextual filter for NID and make sure to select the "exclude" option.

² Not sure what your field names are? Install and enable the Devel module and visit a node. Click the 'devel' tab and navigate through the list to find your desired entity reference field.


How can I add extra information for each term reference?

There are two options:

Create own module based on taxonomy. Most flexible, but also most complicated. That's what I would do, if I had time and motivation to play.
Use Field collection - create a collection of term and percentage fields, and make this collection (not individual fields in it) multivalue. Warning: I know of no easy way to make sure your percentages adds up to 100%. I know how to do it easily in custom module.... see point 1.


To add a value entered in a field to select list

Not exactly the workflow you're looking for but one of these two modules can help you:

Select or Other

  Provides a new Forms API element which is a select/radios/checkboxes
  element that has an 'other' option. When 'other' is selected a
  textfield appears for the user to provide a custom value.

Multiple Selects

  Rather than having a multi-select field, this modules allows you to
  have multiple select fields with the traditional FieldAPI 'Add another
  item' button.


Just tried your code (trimmed down) and it worked without any problems. I simply overwrote the "title callback", like you did. I tried it with admin and anonymous account, see the screenshots for the end result below:

I also added, as an extra precaution, a module_implements_alter implementation. With that hook, you can push your menu_alter implementation to the end of the hook_menu_alter list. That way you can make sure it gets executed after every other menu_alter, in case there was some competing implementation there.

<?php

/**
 * Implements hook_menu_alter().
 */
function mymodule_menu_alter(&$items) {
  $items['node/add']['title callback'] = 'mymodule_title_callback';
}

function mymodule_title_callback($arg1) {
  global $user;
  $title = 'New Title';
  if( $user->uid == 0 ) {
    $title = 'New Title for anonymous';
  }
  return $title;
}

/**
 * Implements hook_module_implements_alter().
 */
function mymodule_module_implements_alter(&$implementations, $hook) {
  if ($hook != 'menu_alter') {
    return;
  }

  $module = 'mymodule';
  $group = array($module => $implementations[$module]);
  unset($implementations[$module]);
  $implementations = $implementations + $group;
}

Hope you can get this to work!


Override Access Permissions from View in Drupal 6

In CCK there is a sub module named content_permissions, With this you can set role wise permissions for fields


Drupal http get Request for external URL?

this actually because of the second argument ['headers' => ['Accept' => 'text/html'] it tells the server to serve a plain text instead of html so your browser will end up print the text instead of parsing it as HTML,so just remove the second argument ['headers' => ['Accept' => 'text/html']

so you code will become like this one :

Code :

$url = 'xyz';

try {
  $response = \Drupal::httpClient()->get($url);
  $data = (string) $response->getBody();
  if (empty($data)) {
    return FALSE;
  }else{
    return $data;
  }
} catch (RequestException $e) {
  return FALSE;
}


Filter module won't let me add nested values to my configuration

I figured out how to declare the filter settings schema by comparing with modules/filter/config/schema/filter.schema.yml and using the Schema docs.

Apparently my schema file simply needs to declare

filter_settings.xbbcode:
  type: filter
  label: 'XBBCode filter'
  mapping:
    [...]


Create a menu programmatically in Drupal 7

If you are trying to do this in an update script, this should work:

$menus = array(
  array(
    'menu_name' => 'menu_test_one',
    'title' => 'My Menu One',
    'description' => 'Lorem Ipsum',
  ),
  array(
    'menu_name' => 'menu_test_two',
    'title' => 'My Menu Two',
    'description' => 'Lorem Ipsum',
  ),
  array(
    'menu_name' => 'menu_test_three',
    'title' => 'My Menu Three',
    'description' => 'Lorem Ipsum',
  ),
);

$links = array(
  array(
    array(
      'link_title' => 'Link1',
      'link_path' => 'http://yourdomain.com/link1',
      'menu_name' => 'menu_test_one',
      'weight' => 0,
      'expanded' => 0,
    ),
    array(
      'link_title' => 'Link2',
      'link_path' => 'http://yourdomain.com/link2',
      'menu_name' => 'menu_test_one',
      'weight' => 1,
      'expanded' => 0,
    ),
  ),
  array(
    array(
      'link_title' => 'Link3',
      'link_path' => 'http://yourdomain.com/link3',
      'menu_name' => 'menu_test_two',
      'weight' => 0,
      'expanded' => 0,
    ),
    array(
      'link_title' => 'Link4',
      'link_path' => 'http://yourdomain.com/link4',
      'menu_name' => 'menu_test_two',
      'weight' => 1,
      'expanded' => 0,
    ),
  ),
  array(
    array(
      'link_title' => 'Link5',
      'link_path' => 'http://yourdomain.com/link5',
      'menu_name' => 'menu_test_three',
      'weight' => 0,
      'expanded' => 0,
    ),
    array(
      'link_title' => 'Link6',
      'link_path' => 'http://yourdomain.com/link6',
      'menu_name' => 'menu_test_three',
      'weight' => 1,
      'expanded' => 0,
    ),
  ),
);

// Save menu group into menu_custom table
foreach ($menus as $menu) {
  // Look the table first if the data does exist
  $exists = db_query("SELECT title FROM {menu_custom} WHERE menu_name=:menu_name", array(':menu_name' => $menu['menu_name']))->fetchField();
  // Save the record if the data does not exist
  if (!$exists) {
    menu_save($menu);
  }
}

$item = '';
foreach ($links as $layer1) {
  foreach ($layer1 as $link) {
    // Build an array of menu link
    $item = array(
      'link_path' => $link['link_path'],
      'link_title' => $link['link_title'],
      'menu_name' => $link['menu_name'],
      'weight' => $link['weight'],
      'expanded' => $link['expanded'],
    );
    // Look the table first if the data does exist
    $exists = db_query("SELECT mlid from {menu_links} WHERE link_title=:link_title AND link_path=:link_path", array(':link_title' =>  $link['link_title'], ':link_path' => $link['link_path']))->fetchField();
    // Save the record if the data does not exist
    if (!$exists) {
      menu_link_save($item);
    }
  }
}

Comments are welcome if my approach is wrong. Thanks.


Drupal says "e-mail sent" but I don't receive

Have you used a devel php input to do a sendmail test?
there is a question already answered here.
How to programmatically send an email?

Also here is a great article on debugging emails...
http://www.drupalcoder.com/blog/how-to-debug-outgoing-mails-in-drupal


I can't filter the child view based on a value from the parent view

You should be able to accomplish this with one view.  I don't think views field view is necessary.
Add a view that shows Users
In the Filter Criteria section filter it by role (trucker).
Under Advanced use the Relationships dropdown to add the relationship Content Authored.
In the Fields section add a field to show whatever field of the trucks content type you want to show for each trucker (e.g. truck name).  You could also use title.  This field setting will use the "node" relationship which is available as a result of adding Content Authored in the relationships dropdown in the advanced section.
If you do use title instead of something like truck name, or any field that appears in multiple content types, in the Filter Criteria section be sure to add a "content type" filter in order to restrict results to the trucks content type.
Format the results as you like (e.g. table, etc.).


How to implement a "switch" in a rule set?

Declare a variable called "done".

First rule in the set checks for role A, sets done and redirects.
Second rule in the set checks if done is true, and role is B, sets done and
redirects.
Third rule in the set checks if done is true, and role is
C, sets done and redirects.
Fourth rule checks if done is true,
redirects.


add field to bundle through hook_entity_bundle_field_info

This code example would set up a basic storage definition:

function mymodule_entity_field_storage_info(\Drupal\Core\Entity\EntityTypeInterface $entity_type) {
  if ($entity_type->id() == 'node') {
    $definitions['my_bundle_field'] = \Drupal\Core\Field\BaseFieldDefinition::create('string')
      ->setName('my_bundle_field')
      ->setLabel(t('My new bundle field'))
      ->setTargetEntityTypeId($entity_type->id());
    return $definitions;
  }
}

You can look up examples in field.storage.*.yml files from a config export.

If you don't find the right examples there, you can configure a field in UI and then export the storage of this field to get a blueprint for the storage definition you need in this hook.


Change content color based on Date Range

In your theme, you can implement hook_preprocess_page(&$variables) were you can retrieve the currently displayed content (if any) as $variables['node']. From there, you can retrieve the value of a date field using field_get_items() and use that value to assign classes to the <body> of the page in $variables['classes_array'].

function THEME_preprocess_page(&$variables) {
  if (($node = $variables['node']) && ($node->type == 'report')) {
    if ($items = field_get_items('node', $node, 'field_report_date')) {
      $variables['classes_array'][] = drupal_clean_css_identifier('report-month-' . format_date($items[0], 'custom', 'F'));
    }
  }
}


How to get the path to theme in Views for linking an Image

I will encourage you to rethink your hardcoding approach and instead implement your icons as CSS background images, using views to apply the desired classes to your field elements. This approach will allow you to avoid the options I am about to suggest :)

Option 1: Copy one of the following files found in the views module theme folder into your theme's templates folder: views-view-field.tpl.php, views-view-fields.tpl.php and rename it according to your needs using the Views template files documentation - and in your case you may want to look at views-view-list.tpl.php. Then code your img tag into this field template logic, constructing your img src with PHP using the $base_url variable. Clear the cache.

Option 2: Install Views PHP and add a Global:PHP field and construct your img src with PHP using the $base_url variable.


Conditional Fields module not working when OR operator is used

The dependency should be like below:

 field_total_rooms  field_category     field_total_rooms  is visible when field_category has at least one of the values: a, c.


How to redirect my content type form after submitting in module

You can use Node Save Redirect module.

  This module provides a method of specifying a location to take the user after saving a piece of content.
  A set of radios buttons are added to the submission vertical tab on the content type edit form.

The available options are:

Default - Default behaviour

Return to Edit page after saving

Return to content overview page (assuming the user has access permissions

Re-redirect to another location. (any valid drupal path)

Or you may try to add submit function to 'Save' button

function mymodule_form_alter (&$form, &$form_state, $form_id) {
  if ($form_id == 'my_node_form_id') {
    $form['actions']['submit']['#submit'][] = 'mymodule_node_form_redirect_submit';
  }
}

function mymodule_node_form_redirect_submit ($form, &$form_state) {
  $form_state['redirect'] = 'node/add/article';
}


Creating account type where email not required to be unique

This answer is untested and it should serve as a guidance. Use it at your risk.

mymodule_entity_base_field_info_alter(&$fields, EntityTypeInterface $entity_type) {
  if ($entity_type->id() == 'user' {
    unset($fields['mail']['constraints']['UserMailUnique']);
  }
}

If it doesn't work, try the following code.

$email_definition = &$fields['mail']['constraints'];
unset($email_definition['UserMailUnique']);

As DataDefinition::&offsetGet returns a reference, both should work.

Note that accessing the definition as an array is deprecated, but as long as https://www.drupal.org/node/2346329 is unresolved there's hardly anything else you could do.


Do not place the <script> tag in node.tpl.php because it will repeat if multiple nodes are arranged to appear in a single page.

Use following code to add js in page and call this function in hook_init() or in your page's callback function.

drupal_add_js('<script>...</script>',array(
  'type' => 'inline',
  'scope' => 'footer'
));


Have you noticed that the help text says

  Only content types enabled in the settings tab of the ddblock module will show up here

?

As far as I can tell from your question, you haven't enabled your content type, and thus that's likely your problem.


How can I best display code examples on my site?

I would set up an input format for code and set the field_php to use that. The code input format could use a filter like this http://drupal.org/project/codefilter


How do you remove or hide the 'Permalink' in comments?

Copy the default comment comment.tpl.php into your theme directory:

cp /your_drupal_path/modules/comment/comment.tpl.php /your_drupal_path/sites/all/themes/mytheme/comment.tpl.php

Search and change the following lines into your theme's path comment.tpl.php:

From:

<?php print $permalink; ?>
<?php print $submitted; ?>

To:

<?php print $submitted; ?>

This will do the magic!


In Drupal, only the users with the permission to administer blocks can change the block settings, including which region the block is assigned.

As far as I know, there aren't modules that allow to assign to users a more granular permission. You should write your own custom module that shows only the fields that a user is allowed to edit.

For example, the following code would alter the form build from block_admin_configure(), the function that build the configuration form for any block, to permit to users with the "edit block titles" permission to edit the block title.

function mymodule_form_block_admin_configure_alter(&$form, &$form_state, $form_id) {
  if (isset($form['settings']['title'])) {
    $form['settings']['title']['#access'] = user_access('edit block titles');
  }
}

The function is the implementation of hook_form_FORM_ID_alter() made for a module named mymodule.module.

The fields for the region settings (the theme regions a block is output) are contained in $form['regions']; The field set contains a select field for each enabled them.
To show the field set only to users with the "edit block regions" permission, you can use the following code, for example.

function mymodule_form_block_admin_configure_alter(&$form, &$form_state, $form_id) {
  if (isset($form['regions'])) {
    $form['regions']['#access'] = user_access('edit block regions');
  }
}

Users with the permission to administer blocks could alter the region assigned to blocks from http://example.com/admin/structure/block. To not allow the user without the "edit block regions" permission to access that page, you should alter the access handler of that menu, and replace the default access handler with a custom one that would return FALSE when users don't have that permission.
For more information, see hook_menu and hook_menu_alter().


How to create user programatically if not exist?

The user_validate_name function from Drupal only verifies the syntax of the given name.

It does not validate whether the username exists or not.

You could replace the function call, like so:

$uids = \Drupal::entityQuery('user')
  ->condition('name', 'czxc')
  ->execute();
if (count($uids) > 0) {
  $user = User::create([
    'name' =>'czxc',
    'mail' => 'user@gmail.comgczxcdfa',
    'pass' => 'password',
    'status' => 1
  ]);
  $user->save();
  drupal_set_message($user->id());

} else {
  drupal_set_message('Already exist user');
}


How do I override the vocabulary template but only on a specific content type

I think you can make that with views :)

You have to create your views with the fields  you need. After that you will be able to theme them globally and locally.
check views's theme suggestion

i hope it helped you


Why are new users having their role deleted on signup?

The problem was caused by the module 'Civigroup Roles Sync'.  Adding the new user with a role that was synced to CiviCRM caused the user's role to be dropped because in CiviCRM they weren't in that group.


Adding a target='blank' attribute in D7 module for Nice Menus

Consider using the menu attributes module to add additional attributes with your particular menu item:

  This simple module allows you to specify some additional attributes
  for menu items such as id, name, class, style, and rel.

Unfortunately, I'm not sure if it integrates with nice menu. You'll have to give it a try nonetheless.


Create a zip file from a list of selected files and make the zipped file downloadable

Make sure you include the class

module_load_include('inc', 'zip_archive', 'zip_archive.class');

Also check permissions for archive.zip file. Create one if its not there.


What are the changes I should make to the .htaccess file to enable clean URLs?

You do not need to do any edits in the Drupal default .htaccess file to have Drupal 7 enable clean URLs.  Instead, navigate to Home » Administration » Configuration » Search and metadata (its the link named "Clean URLs" on the Admin's Configuration page, and press the button "Run the clean URL test".

If the test is successful, Drupal will make use of its default .htaccess to do the rewrites.  If the test fails, then you need to review your configuration.

Some suggestions:

Make sure that the Drupal default .htaccess is present in your webroot (/var/www).

Make sure that you've actually enabled mod_rewrite for Apache, e.g.:

 sudo a2enmod rewrite

You must also restart Apache after changing defaults, e.g.:

 sudo service apache2 restart

(The example shell commands above are for Ubuntu.  If you run a different dialect of GNU/Linux, you may need to use slightly different shell commands.)


MySQL query for getting blog records/content Drupal7?

The limit is controlled through a variable called default_nodes_main. You can change it by executing the following code:

// This would increase the number of nodes on the blog page to 20.
variable_set('default_nodes_main', 20);

If you have Devel module installed, you can do this at /devel/php.


You could just use the Fast404 module (if I'm understanding your question correctly).

  Drupal has expensive 404 errors. On an 'average' site with an
  'average' module load, you can be looking at 60-100MB of memory being
  consumed on your server to deliver a 404. Consider a page with a bad
  .gif link and a missing .css file. That page will generate 2 404s
  along with the actual load of the page. You are most likely looking at
  180MB of memory to server that page rather than the 60MB it should
  take.

  That's where Fast 404 comes in. This module combines a very common
  method of handling missing image/file 404 errors (discussed here and
  planned for Drupal 8) with a method created by dpardo (a co-maintainer
  of this project) to deliver super fast 404 error pages for both
  missing images and bad paths. Depending on which method of
  implementation you choose (aggressive or super aggressive) you can
  deliver 404 errors using less than 1MB of memory on your server.


Request a new password mail without any content inside of the mail.

admin/config/people/accounts
Check this section make sure this is not empty.


You can export blocks with the Features Extra module, or better yet, use the Boxes module, which is designed to be exportable.

Using MySQL dumps is an advanced trick that gets harder with each version of Drupal as the API becomes more complex. It's not recommended and definitely not for the faint of heart.


How can I increase my hit ratio in Memcache?

I would interpret the numbers in a way that 70% of the traffic to your site are pages that are currently contained in the cache. The other 30% did go stale because the weren't visited frequently enough to stay fresh.

This is a more common problem about "How to cache?". The base Drupal cache is time based. If you don't use more complex methods like Drupal 8 tries to do for you there will always the problem that from time to time hits can't be cached. So probably 99% of you home page are cache hits. The 1% are the hits while the page is refresh. But any other page that is older than your settings on the "performance" settings page will be immediately stale. Means that if you cache for 5 minutes and the page is visited every 6 minutes it will never get a cache hit.

Your cache is currently more or less a protection against traffic spikes or (D)DOS attacks. But not something that really eases the web server in all occasions.

Real solutions for this go above this question and the easiest thing would be to go to Drupal 8. It really tries hard to cache your stuff for ever.
http://buytaert.net/making-drupal-8-fly

All in all 70% is not that bad. You could try a module like boost:
https://www.drupal.org/project/boost

And than find a way how to cache things until they are updated. But if you use a sidebar with views this will be a big problem if you don't go using asynchronous (AJAX / AHAH) calls by javascript or things like edge side includes (ESI)


How to create a multisite from an existing Drupal site

with Acquia dev desktop , you can click on "More" at the bottom and create a multisite from an existing site.  Other wise I also found this https://www.drupal.org/project/multisite_wizard


Setting a new users profile fields based on a form

Do you think you could just make the select dropdown and postcode input box parts of the user_form? Looks like you've got the functionality working already, so it would be a matter of a simple module implementing the following hook:

hook_user(register) to alter the registration form and add your custom fields. You'll want to use a profile or profile_taxonomy functionality to insert the form element
hook_user(validate) to validate the user input (incorrect postcode etc.)
hook_user(submit) to convert the postcode to region and to save that information in the user profile


$display should be one of view modes (full, teaser, rss or ...) or display setting array:

$display = array(
    'label' => 'hidden',
    'type' => 'file_rendered',
    'settings' => array(
        'file_view_mode' => 'media_original',
    ),
);


Embed rate number up down widget in panel node

You can try the following code.

 $up_down = rate_generate_widget('1', 'node', {current node id}, RATE_FULL, TRUE, FALSE, NULL);
 print render($up_down);


How can I add a flag for reporting abuse on private messages using hook_privatemsg_message_view_alter()?

I really don't know why you don't like the answer by Rene.

Let me show a more detailed example.
You have to replace YOURMODULE with name of your module or theme.

/**
 * Implements hook_privatemsg_message_view_alter().
 * The & for param $vars is important: we pass it by reference.
 */
function YOURMODULE_privatemsg_message_view_alter(&$vars) {
  // Message author
  $uid = $vars['message']->author->uid;
  // Get flag for abusing user
  $flag = flag_get_flag('abuse_user');
  // Make flag module to check permissions
  if ($flag->access($uid)) {
    // Use flag API to show a flag according to flag preferences
    $vars['message_actions']['flag-'. $flag->name] = array(
      'title' => $flag->theme($flag->is_flagged($uid) ? 'unflag' : 'flag', $uid),
      'html' => TRUE,
    );
  }
}

Here I'm using a flag with name 'abuse_user':

You can edit Flag labels, link type and permissions here.
The result:

Please, feel free to ask questions.


I tested my hypothesis above and it was correct.  The queue isn't fully processed during a cron run, so there are stale node objects sitting in the queue table in the database.  The solution was to reload the node in the worker callback.

Original Code

/**
 * Implements hook_cron().
 */
function ih_transcript_import_cron() {
  // Load all Video nodes.
  $videos = ih_transcript_import_load_video_nodes();

  $queue = DrupalQueue::get('ih_video_transcripts');
  foreach($videos as $video) {
    $queue->createItem($video);
  }
}

/**
 * Implements hook_cron_queue_info().
 */
function ih_transcript_import_cron_queue_info() {
  $queues['ih_video_transcripts'] = array(
    'worker callback' => 'ih_transcript_import_import_transcript',
    'time' => '60',
  );
  return $queues;
}

/**
 * Implements callback_queue_worker().
 */
function ih_transcript_import_import_transcript($video_node) {
  // THIS IS THE PROBLEMATIC PART, $video_node is stale since it is
  // pulled from the queue table of the database and there may have been
  // multiple cron runs since it was created (2 days in my case).
  $video_node->field_transcript_text[$video_node->language][0]['value'] = "My value";
  node_save($video_node);
}

The Fix

/**
 * Implements callback_queue_worker().
 */
function ih_transcript_import_import_transcript($video_node) {
  // THIS IS THE IMPORTANT FIX, reload the video node to ensure
  // we are saving the most up to date data.
  $video_node = node_load($video_node->nid);

  $video_node->field_transcript_text[$video_node->language][0]['value'] = $transcript_text->data;
  node_save($video_node);
}

Better Fix

Save ONLY the node Id in the queue rather than the entire node.  Also, I added some code to ensure that there are no duplicates in the queue.  My queue table had 64000 records!!

/**
 * Implements hook_cron().
 */
function ih_transcript_import_cron() {
  // Load all Video nodes.
  $videos = ih_transcript_import_load_video_nodes();
  $currentQueueItems = array();
  $claimedItems = array();

  $queue = DrupalQueue::get('ih_video_transcripts');

  // We only want to add an item to a queue if it doesn't already exist in the
  // queue to avoid the queue table becoming massive.  Retrieve a list of
  // node ids that already exist in the queue.
  while($item = $queue->claimItem()) {
    $currentQueueItems[] = $item->data;

    // Store a copy of the claimed items, so we can release them again. We
    // only claim them in order to grab the node Id, so need to release again
    // to allow processing.
    $claimedItems[] = $item;
  }

  // Release claimed queue items to allow them to be processed by other workers.
  foreach($claimedItems as $claimedItem) {
    $queue->releaseItem($claimedItem);
  }

  foreach($videos as $video) {
    // Don't add videos that already exist in the queue.
    if(!in_array($video->nid, $currentQueueItems)) {
      $queue->createItem($video->nid);
    }
  }
}

/**
 * Implements hook_cron_queue_info().
 */
function ih_transcript_import_cron_queue_info() {
  $queues['ih_video_transcripts'] = array(
    'worker callback' => 'ih_transcript_import_import_transcript',
    'time' => '60',
  );
  return $queues;
}

/**
 * Implements callback_queue_worker().  Can also be called independently of cron
 * to import a single transcript.
 */
function ih_transcript_import_import_transcript($video_nid) {

  $video_node = node_load($video_nid);

  $video_node->field_transcript_text[$video_node->language][0]['value'] = $transcript_text->data;
  node_save($video_node);
}


How to make all render caches update on a configuration override?

In the meantime I have come up with this approach, but I am still open to other solutions.

I have found a solution in a pre_render callback for the blocks, by deconstruction the cacheable metadata, searching it for a system.site tag and append my own context and tags (if required).

/**
 * Implements hook_block_view_alter().
 */
functionmymodule_block_view_alter(array &$build, \Drupal\Core\Block\BlockPluginInterface $block) {
  $build['#pre_render'][] = 'mymodule_block_view_pre_render';
}

/**
 * #pre_render callback: Sets my module cache tags.
 */
function mymodule_block_view_pre_render(array $build) {
  $cacheable_metadata = CacheableMetadata::createFromRenderArray($build);
  $tags = $cacheable_metadata->getCacheTags();

  if (in_array('config:system.site', $tags)) {
    // Always add a cache context, so we have a variant without overrides as well.
    $cacheable_metadata->addCacheContexts(['mycontext']);

    if ($entity = MyEntity::Load(1)) {
      $cacheable_metadata->addCacheableDependency($entity );
    }
  }

  $cacheable_metadata->applyTo($build);

  return $build;
}


I think you'd find this article in the Drupal documentation relevant and helpful.

The solution is to wrap your custom Javascript code within a closure as shown below:

(function($) {
  // Your Javascript code goes here
})(jQuery);

Javascript files from all Drupal core modules follow this convention. So, you can look them up for reference.

I'm not really sure but either before/after some version of jQuery, the $ was a global alias for the jQuery object itself and could be used directly without the closure but was later removed as it conflicted with other libraries.


How to export pseudo fields display configuration to code

Strongarm will do this because field_bundle_settings() stores the settings in a huge variable called field_bundle_settings. There is a patch to move it into several variables, but it'll be variables nonetheless.

Edit: I guess the core source code counts as "official source", doesn't it?


How to customize exposed filter for date field?

You can create your own form controls to send his values to exposed filters. For example, create your own select list inside a exposed filters template (views-exposed-form.tpl.php). This select list can have your desired options with respective values, according is needed in the exposed filter, for example:

<select id="edit-date" class="form-select" name="date">
<option value="-1 day">New members</option>
<option value="-7 day">Members within 1 week</option>
<option value="-30 day">Members within 1 month</option>
<option value="">All members</option>
</select>

Also, if you need a more complex behavior, you can alter view's queries with query_alter hook. This answer is an example of how to use query_alter with a custom select list.

I hope information be useful.


Most likely you will need to repatch the module, if you doing it manually.

If are using composer to manage your drupal set up, you can use "cweagans/composer-patches", and this composer plugin it will reapply the patch for you automatically and let you know if the patch will no longer work on the newer version of the module.

This is a big time saver.


node.html.twig gets cached while other templates do not

drupal site:mode dev won't turn off all the caches. Tunning caching for dev purpose requires manual changes to the settings.(local.)php.

Open the example.settings.local.php file located in the sites directory and copy its content over to site's settings.(local.)php file.
Focus on the cache bins - in your case render and dynamic_page_cache.

$settings['container_yamls'][] = DRUPAL_ROOT . '/sites/development.services.yml';
$settings['cache']['bins']['render'] = 'cache.backend.null';
$settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';


You have a typo in your services.yml file, you misspelled arguments.
Additionally, for a service, you don't need to (and shouldn't) define the create method. Your dependent services are injected from services.yml, but keep your constructor as is.
The only time you need to define the create method to inject dependencies is when working with plugins, controllers, forms, etc as mentioned in the dependency injection documentation on d.o.


Best practice for node expiration with email notification

Drupal has a custom module available called Rules with a submodule Rules Scheduler that will allow you to set up custom scenarios for when you want a certain action to take place.

In your specific scenario you would use Rules and Rules Scheduler to set up custom emails to be sent out at your specified time based off of your time field.

Node one has several tutorial videos available to watch with a specific video available about how to use content fields and rules scheduler to set up time specific actions.


Let the site administrator edit content at page

It is not clear what you want to edit - content types (page, article, blog etc.) or nodes? If you want to edit particular nodes in a view which outputs fields, core Contextual filters module have views implementation so you can choose Global: Contextual links as a field. You can even configure which links to display as contextual links.
Check out Views Bulk Operations and Administration Views as they allow you to alter the admin interface using views.


How can I pass a fixed argument to a view within a panel?

I'm making the assumption your on D7, with views 3, and have Views Content Panes running on your site (Views Content Panes comes with ctools).

So your gonna create your view as you normally would. When it's good and displaying as you want it to, add a display of a content pane (up near the top, under the display, hit the plus sign, select content pane). This will give you access to the "PANE SETTINGS," one of which is "Argument input." Click on this. If you have two contextual filters running on your view, there should be two drop down menus, one for each of your contextual filters.

Set both of these to "input on Pane Config." Now when your adding your views to your panels, your going to use the "View Panes," NOT the "views." Once you add your view pane, you should be presented with two text boxes for your contextual filters, you may set provide the arguments for those here.


Why the menu items to edit a specific vocabulary and terms does not show up in administration tool bar?

You need to add 2 more permissions as below

1) 'Use the administration pages and help' under System
2) 'Use the administration toolbar' under Toolbar


Can Drupal be configured to find modules in other locations?

Before answering, it's helpful to have a little background about how Drupal finds modules. Drupal uses a list of suggestions from the Drupal root to figure out where to find modules. In order of priority:

sites/$SITENAME/modules
sites/all/modules
profiles/$INSTALLPROFILE/modules
modules

If Drupal doesn't find a module in (1), it checks (2). If it's not there, it checks (3), and so on.

For (1), if you're just using a basic, single-site install of Drupal, $SITENAME is default. Otherwise:

In Drupal 6, $SITENAME is the host name of the site. If your site is located at example.com, $SITENAME would be example.com.
In Drupal 7, $SITENAME is defined in sites/sites.php. If you look at example.sites.php, you can see how to define it. It's also important to note that any module listed there will only be usable for that specific sites, not all sites.

In (2), any module found there will be usable on any site in the Drupal installation. It will also be left untouched when you upgrade the core installation. This is, of course, the recommended place to put modules and likely all documentation you've read have told you to put your modules here.

(3) is used for installation profiles that require a specific module. Installation profiles are essentially a way to define a custom initial state for a Drupal site. For example, Drupal comes with two installation profiles built in: Standard, which includes most-used features, and Minimal, which only includes the bare minimum needed for a Drupal site to function.

(4) is used by Drupal core. While you can technically add modules here and they will be available for all sites, you shouldn't. Seriously. The modules folder is touched when Drupal core is updated, and will cause problems down the line if you're sticking modules you need for your site to function there.

Now that the background is out of the way, you can use file system tricks to have your modules housed outside of where Drupal looks.

For example, you could set up a symbolic link from sites/all/modules to another directory outside of the Drupal installation:

In Unix/Linux/BSD-based systems: ln -s /path/to/modules/folder /path/to/drupal/sites/all/modules
On Windows Vista/Server 2008/7 and higher: mklink C:\path\to\drupal\sites\all\modules C:\path\to\custom\modules\folder

As far as I'm aware, there's not much you can do in earlier versions of Windows that don't have mklink.


How can I update the block content programmatically?

Placed blocks are stored in the config entity block. The IDs are more or less unpredictable but you can load the blocks by specifying properties:
$entity_type_manager = \Drupal::entityTypeManager();
$blocks = $entity_type_manager->getStorage('block')->loadByProperties([
  'plugin' => 'my_custom_block',
  'region' => $region,
  'theme'  => $theme,
]);

A code example to load all blocks placed for the custom block plugin, do some checks and modify the settings:
$entity_type_manager = \Drupal::entityTypeManager();
$blocks = $entity_type_manager->getStorage('block')->loadByProperties([
  'plugin' => 'my_custom_block',
]);

foreach ($blocks as $block) {
  if ($block->getRegion() == 'my_region') {
    $settings = $block->get('settings');
    // modify settings
    $block->set('settings', $settings);
    $block->save();
  }
}