How to show 404 page for nodes without translation?

At first I was tempted to alter menu items responsible for node auto-loader function like this:

/**
 * Implements hook_menu_alter to hijack node auto-loader function.
 */
function et404_menu_alter(&$items) {

  // Remove original node view item...
  unset($items['node/%node']);

  // ... add our own node view item with custom auto-loader
  $items['node/%et404_hijacked_node'] = array(
    // Array items are copy-paste from node.module
    'title callback' => 'node_page_title',
    'title arguments' => array(1),
    // The page callback also invokes drupal_set_title() in case
    // the menu router's title is overridden by a menu link.
    'page callback' => 'node_page_view',
    'page arguments' => array(1),
    'access callback' => 'node_access',
    'access arguments' => array('view', 1),
  );
}

/**
 * Overrides node_load to show 404 page if translation is not available.
 */
function et404_hijacked_node_load($nid = NULL, $vid = NULL, $reset = FALSE) {
  global $user;
  global $language;

  $node = node_load($nid, $vid, $reset);

  // Only anonymous users are refused access
  if (!$user->uid && !isset($node->translations->data[$language->language])) {
    $node = false;
  }

  return $node;
}

Unfortunately this solution won't work correctly, because of menu_get_object() function that is used across drupal. That function assumes that every entity has it's auto-loader function named like ENTITY_TYPE_load(). The _load suffix is hardcoded into the function whereas it should be red from the entity info array provided by the hook_entity_info() (explicitly the load hook parameter).

I decided to use different approach that involves hook_node_access().

Actually instead of showing 404 with drupal_goto() I decided to incorporate drupal core and show 403. It can be turned into 404 anyway with a help of m4032404 module.

Please note that the following code is part of a module that also provides language fallback features similar to those from language fallback module - hence the reference to $language->fallback property that doesn't exists in vanilla D7. I am the author of language fallback patch for entity translation for D7 and D8 but for this particular project I needed something very sophisticated that I couldn't achieve with the language fallback module.

/**
 * Implements hook_node_access()
 */
function et404_node_access($node, $op, $account = null) {

  // We restrict access only to anonymous users so authenticated users can still manage content
  if ($account->uid) {
    return;
  }

  // Basic sanity check
  if (!is_object($node)) {
    return NODE_ACCESS_DENY;
  }

  global $language;

  // Check if translation for current language exists
  if (!isset($node->translations->data[$language->language])) {
    // Check if translation for fallback language exists
    if (LANGUAGE_NONE != $language->fallback && isset($node->translations->data[$language->fallback])) {
      return;
    }

    return NODE_ACCESS_DENY;
  }
}

/**
 * Implements hook_translated_menu_link_alter()
 *
 * This function checks if specific menu item points to the node entity
 * and if it is, checks if node has translation for current UI language.
 * Nodes without translation are hidden.
 *
 * See StackExchange answer for more info:
 * http://drupal.stackexchange.com/a/32024/5982
 */
function et404_translated_menu_link_alter(&$item, $map) {
  // Alter only custom menu items from "main menu"
  if ('menu' != $item['module'] || !isset($item['menu_name']) || 'main-menu' != $item['menu_name']) {
    return;
  }

  // Process only nodes
  if (!isset($map[1]) || !isset($map[0]) || 'node' != $map[0]) {
    return;
  }

  if(!is_object($map[1])) {
    // Instead of loading node manually, use core function for that.
    if (!_menu_load_objects($item, $map)) {
      return;
    }
  }

  // After _menu_load_objects() the $map[1] contains node object
  $entity = &$map[1];

  if (!et404_translation_check_entity($entity)) {
    // There is no translation for this entity in current UI language.
    // Hide the item and quit.
    $item['hidden'] = true;

    return;
  }
}

/**
 * Implements hook_menu_link_alter()
 *
 * When custom menu item is saved, we add 'alter' option to be able to
 * customize this item with hook_translated_menu_link_alter() implementation.
 * See et404_translated_menu_link_alter() for details.
 *
 * @param array $item
 * @param array $map
 */
function et404_menu_link_alter(&$item, $map) {
  // Alter only custom menu items from "main menu"
  if (isset($item['module']) && 'menu' == $item['module'] && isset($item['menu_name']) && 'main-menu' == $item['menu_name']) {
    $item['options']['alter'] = TRUE;
  }
}

/**
 * Check if there is a translation for entity in current UI language only
 * @param object $entity
 * @return boolean|string
 *   FALSE if translation is NOT available; otherwise true.
 *   Note that FALSE is returned also for entities without "translations" property.
 */
function et404_translation_check_entity($entity) {

  // Invalid data?
  if (empty($entity)) {
    return false;
  }

  global $language;

  // Check if current UI language is the same as entity language
  // This is a fail-safe in case "translations" property is missing
  // Note that taxonomy terms doesn't have language property
  if (!empty($entity->language) && $entity->language == $language->language) {
    return true;
  }

  // Check if "translations" property exists.
  // Without it further checks doesn't make sense
  if (empty($entity->translations)) {
    return false;
  }

  // Check if there is a current UI language translation available.
  if (!empty($entity->translations->data[$language->language])) {
    return true;
  }

  // Check if there is a fallback language translation available.
  if (LANGUAGE_NONE != $language->fallback && !empty($entity->translations->data[$language->fallback])) {
    return true;
  }

  // No translation available
  return false;
}

And as a bonus, a fix for language switching links:

/**
 * Implements hook_language_switch_links_alter
 *
 * Function alters language switching links for nodes
 * if there is no translation for currently viewed node
 */
function et404_language_switch_links_alter(array &$links, $type, $path) {

  $translations = array_keys($links);
  $translations = array_flip($translations);

  if (arg(0, $path) == 'node' && arg(1, $path) && !arg(2, $path)) {
    // !arg(2, $path) --> This will make sure we're not altering links like /node/1/edit/LANG

    // Most probably dealing with nodes
    $node = node_load(arg(1, $path));

    if ($node) {
      $translations = array_keys($node->translations->data);
      $translations = array_flip($translations);
    }
  }

  $languages = language_list();

  foreach($links as $lang => &$link) {
    // Check if translation for the language exists
    if (!isset($translations[$lang])) {
      // If not, check if the fallback translation is also missing.
      if (!isset($languages[$lang]->fallback) | LANGUAGE_NONE != $languages[$lang]->fallback && isset($translations[$languages[$lang]->fallback])) {
        continue;
      }
      $link['href'] = '<front>';
    }
  }
}


How to show a block on user profile edit page ?

Using the block ui, you can select the visibility of block using user/*/edit/custom_url. The star is a wild card and will give you the ability to place blocks on pages that have a variable in the path.


I've tried several solutions using the Media module with Plupload with drag and drop capability, but I have never gotten them to work the way I want. I don't like the way Media handles files and even though I can bulk upload them into the Media area, when I want to connect them to an individual node, I still have to select them individually with an awkward media browser. Not a fan.

However, I have been VERY pleased with Multiupload Imagefield Widget (requires: Multiupload Filefield Widget). It works with a standard Image field, no need to change your content structure or do anything weird. All you need to do is edit the Widget Type on your Image field and change it from Image to Multiupload.

It will let you use the standard Image field upload, but you'll be able to select multiple images at once and upload them all with one click.


How to set the value of a date field via Rules?

Before you will be able to create a Rules Action like "Set a data value" for your date field, you have to make sure to add a Rules condition Entity has field (related to the  field for which you want to set a value). And make sure to add that Entity has field condition BEFORE other Rules Conditions in which you might want to refer to this field.

That's also what is mentioned in the Rules UI, e.g. when you're adding a "data comparison" condition: somewhere it says:

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

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


Is there an efficient way to dermine whether a node can be viewed by all users?

If you are needing to check node_access records, then you may be able to examine them similarly to how devel_node_access does.  In the end, all nodes have grants added to the node_access table, so if there are grants that deny or restrictively add access, then you can probably see it there.

Another option would be to have a dummy account that is an authenticated user, and used as the test case.  This will fail, of course, if you need to detect grant rules that deny access to authenticated users who would otherwise be entitled.  It's a sticky situation.

The hardest part about this question is that it seems as though you are looking for a general solution to a specific problem, and I'm not quite sure that a general solution exists.


This will not be simple, as it is a requirement which is probably unique to your site. I know of no modules designed for this scenario. In general terms, you need to do the following.

Import the field_data content WITH all the fields into your D7 field_data type.
Create your accomplishments content type, and clone each field_data type to an instance of the accomplishments type, recording the nid of the source instance (field_data). Look at the Node Clone module to see how it is done. (Note: This module will not do this out of the box. You will have to hack it to do what you want.) You can probably use hook_node_presave to change the bundle and move the nid to the term reference field, then blank $node->nid to create a new node. Using Feeds or Backup and Migrate will not give you the nid for the node reference.
Delete the unwanted fields from the D7 field_data type.

You might also be able to accomplish this through direct manipulation of the database, but it is probably best to do it 'the drupal way' to avoid any artifacts which you might introduce in the direct query method.

Good luck.


How to migrate Link Fields ('title' and 'url') involving local variables?

The link.migrate.inc file is not included in the Migrate Extras module, it's part of the Link module.

The file doesn't exist in the stable version of Link, but it does exist in the dev release. I think you're going to have to install the dev version of Link if you want this to work.

If you install the dev version and still get the error it's most likely because the file is not being automatically included. If that's the case try adding this to the top of your code:

module_load_include('inc', 'link', 'link.migrate');

EDIT

As I mentioned in your other question there's a slight error in your code, you should change this line:

$result = $query->execute();

to:

$result = $query->execute()->fetchObject();

That will return an object representing the first result that was returned by the query.


How to alter drupal views filter by start date query

Try this module Views between dates filter  I suppose this may help you


How to set paths for menu items in hierarchy to make it work with Superfish

Weirdly enough I've just stumbled across the Special menu items module, which is:

a Drupal module that provides placeholder and separator menu items.
A placeholder is a menu item which is not a link. It is useful with dynamic drop down menus where we want to have a parent menu item which is not linking to a page but just acting as a parent grouping some menu items below it.

I'm pretty sure that's just what you're looking for, and it has a stable release for Drupal 7 :)


How can I filter the taxonomy terms by language?

By enabling the module Internationalization Views, the option to filter the taxonomy term by the language is available. Note that the version is currently in dev but it works like a charm.


It sounds like you have "Strict node access permissions" enabled.

On the OG settings page (/admin/config/group/settings), make sure "Strict node access permissions" is unchecked.

This disables the OG permissions and lets you use the standard Drupal permissions alone.


Looking for a module to hit a tokenized URL when certain actions happen

The Rules HTTP Client module (+ Rules itself) will handle that:

  This module adds an action wrapping of drupal_http_request to use Rules for making http requests. It has many general uses, because the Hypertext Transfer Protocol is the foundation of web data communication.


How to add warning message before module is uninstalled

Before a module is uninstalled, Drupal invokes all the services implementing UninstallValidatorInterface and tagged with module_install.uninstall_validator. Their validate() method (see BookUninstallValidator::validate(), for example) returns an array of strings explaining why the module cannot be uninstalled, which are then shown in the user interface.

Notice that the validate() method receives the name of the module as parameter. While normally the module implementing the UninstallValidatorInterface service checks if itself can be uninstalled, a UninstallValidatorInterface service can avoid any module is uninstalled.

In Drupal 7, there isn't anything similar. The only way to achieve this is altering the page showing the list of the installed modules to show a message near a module.


Load library dynamically depending on settings

I would implement this slightly differently. What you can do is combine all the different style css files into one, and use a className prefix instead of a file name prefix. So instead of having foo.min.css and bar.min.css you'll have 1 css file that's always included but has body.foo {} and body.bar {}  styles in them.

Of course this gets easier with a preprocessor such as SASS: for every element you want to style you can wrap it in their respective body.foo or body.bar parents, without having to manually write body.foo in front of every element you want to style. So I highly recommend you use something like SASS for this, but it's not required at all.

The advantage of this method is I think it avoids problems with caching different CSS files since you're using only one. Also if your original goal of having separate CSS files was to keep them neat and separate then you can do that with your SASS files and they can be compiled into a minified single CSS file by your SASS processor.


Hide language flag on this language page?

if you want add class language to body. You can use hook_preprocess_html with code:

function Your_Theme_preprocess_html(&$vars){
  $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
  $vars['attributes']['class'][] = $language;
}

class current language will add to body.


List of all active modules used in a site

You can use drush pm-list --type=Module --status=enabled command for getting a list of all installed modules.

If you want to exclude the core modules use drush pm-list --type=Module --no-core   --status=enabled


How can I sum up the totals of groupings in views?

Most of the links I found for this kind of thing point towards Views Aggregator Plus.  Apparently it allows you to "aggregate and group by column" (source).


Drupal 8: Template suggestion for form-element in a views exposed filter is not working

Ok, looks like I was too tired. The problem was that the template should be called form-element--custom.html.twig.

Notice the '--' (double dash) instead of the __ (double underscore).

I also ended up using the more specific hook alter:

hook_theme_suggestions_HOOK_alter

...where HOOK for me was form_element.


How to use Rules to send separate email to every user referenced in user reference field?

You should create a rule that looks like so (in Rules export format):

{ "rules_send_email_to_selected_email_ids" : {
    "LABEL" : "Send eMail to selected eMail IDs",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : {
      "node_insert--article" : { "bundle" : "article" }
    },
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-email-addresses" ] },
          "ITEM" : { "current_email_id" : "Current eMail ID" },
          "DO" : [
            { "drupal_message" : { "message" : "An eMail about this new content with title \u0022[node:title]\u0022 and URL [node:url] will be delivered to [current-email-id:value]." } },
            { "mail" : {
                "to" : "[current-email-id:value]",
                "subject" : "You have new mail ...",
                "message" : "New content was created with title [node:title] ... You can read about it at [node:url].",
                "language" : [ "" ]
              }
            }
          ]
        }
      }
    ]
  }
}

Some more details about the above rule:

Rules Event: After saving new content of type "Article" (adapt the type to fit your needs, ie to XYZ).
Rules Action: a "loop" for all selected values of a multi value select list (which contains the eMail IDs), with machine name field_email_addresses (adapt the machine name to fit your needs). For each item (= current_email_id), an eMail is created with some subject and message that also contains the title and url of the node being created. Note: this will send 1 separated eMail to each of the selected eMail IDs (there is no way to send a single eMail to all selected eMail IDs).

If you have the Rules UI enabled, you can import the above rule in your own site, after you adapt the machine names of the content type and the field name containing the list of eMail Ids.

After you're convinced the rule works as expected, you may want to remove the Rules Action that displays a message after the node is saved (with drupal_message).

Video tutorial: have a look at the List and loops video which show a similar scenario.

Update

If you don't have such field with eMail IDs, but a field which is an entity reference field to user ids, then you can use a minor variation of the above rule. Instead of field_email_addresses, you'd want to loop over the list of users (indicated via the user reference field, let's assume it's named field_user_ids). And for each "item" (which I'd name "current_userid"), in the "to" field you'd use the current-userid:mail token for the user being processed. Here is how such rule could look like (in Rules export format):

{ "rules_send_email_to_selected_user_ids" : {
    "LABEL" : "Send eMail to selected user IDs",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : {
      "node_insert--article" : { "bundle" : "article" }
    },
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-user-ids" ] },
          "ITEM" : { "current_userid" : "Current user ID" },
          "DO" : [
            { "drupal_message" : { "message" : "An eMail about this new content with title \u0022[node:title]\u0022 and URL [node:url] will be delivered to eMail ID [current-userid:mail]." } },
            { "mail" : {
                "to" : "[current-userid:mail]",
                "subject" : "You have new mail ...",
                "message" : "New content was created with title [node:title] ... You can read about it at [node:url].",
                "language" : [ "" ]
              }
            }
          ]
        }
      }
    ]
  }
}


Add soft hyphen () in titles (in views) or other method to break words in a language-sensitive way

Our workaround inhouse: We've trained our editors to use Alt + 240 (hold alt key and press 2 4 0 on numeric pad) to manually add soft hyphens in title fields.

Is a bit weird because your editors don't see the hyphen in a text input field, but you can prove its existance by deleting it (backspace after such a hyphen will NOT delete the visible letter on first press)


How to use the Message module to log site and user activity?

The Message module is great, really! But still poorly documented. However, have a look at the tutorial "How to use Rules to notify users about new or updated posts on a Drupal site?", which explains how to use the Message module, together with the Rules module. What follows is a summary of what's included in this tutorial.

  You can use the Message module in combination with the Rules module create message "entities" (which is what you get if you use the Message module). And then just use the power of Views to display those messages that got created in the format you need (page, block, etc).

  Here is a blueprint of what you'd need:

  Define an appropriate Message type, using the Message module. Think of Message types as similar to "Content types", which will be used to create Messages, similar to nodes.
  Create a rule with a Rules Action "Create entity" (of type "Message"). Refer to the answer in 'Which user related token(s) can be used to create a Rule for setting up a message type?' for some examples.
  Make sure to also add a Rules Action to pass any relevant tokens, via the Rules module, as Replacement tokens that you can use in your Message type you created with the Message module. Refer to What's the purpose of "Replacement tokens" of a Message type? for more details on this.
  Use Views to display the created messages in the format you prefer.

Some more details specific to your question here:

For each of the 6 activities you want to record, define an appropriate (corresponding) Message Type (using the Message module). Let's name those message types like M1, M2, ... M6 for now.
For each of the 6 activities you want to record, there is an appropriate Rules Event you can take advantage of. If you'd just create 6 custom rules (1 for each activity to record, let's name those rules like R1, R2, ... R6 for now), it's a matter of combining each rule with a Rules Action to "Create an entity" (i.e. of type "Message"). E.g. Rule R3 should have a Rules Action to create a message of type M3.
As per the "I don't get exactly the same options (entity and tokens) ..."-part of your question: I bet sooner or later you're going to run into the issue that you want to create a message using a token which is NOT made available by only the Message module. E.g.: Assume that for recording your 6th activity (= "User F just commented on ...") you want the message to also include the actual comment body (text) that was posted. But the Message module doesn't offer any relevant token related to that comment body. In that case, you can use the approach/solution as documented in "What's the purpose of "Replacement tokens" of a Message type?", which is basically a technique to create your custom tokens (the comment body in the example here) and make them available to the Message module (so that you can include them in the message to be created).
Obviously, creating appropriate views of these messages (which are just entities) should be straight forward.

More info about the Message module

There is not a lot of documentation available about the Message module, which is what makes it a hidden Drupal gem. A possible way to get started with it, and to get an idea of the kind of things it can be used for, is to also have a look at these tutorials:

What is Drupal's Message Stack and how do its modules work together?
How to allow users to manage their own Message Stack messages?


How can I override the markup of a view I printed in a template file?

You can enable Twig debugging for your site in sites/default/services.yml

    parameters:
      twig.config:
        debug: true

Clear cache
Inspect element in the browser and you will see the path to the template
Copy the template to your custom theme's templates/ directory and adjust the markup


Try enabling Aggregate JavaScript files option at admin/config/development/performance.
Sometimes that resolves this type of issues

Here is the screenshot


How do I add a clearing DIV to the bottom of a region?

I would find a common class for your region(s), and add in the clearfix rules.  With kosher HTML and CSS, I don't recall the last time this didn't work in IE for me.


You might as well do it right and use webform. It will literally take you minutes once you figure it out.

And then for the ecard submission, you could install the rules module and pass the form values as tokens (including the email address) telling rules that when a webform with the id of "supid_ecard" is submitted, fire this rule -- http://drupalcontrib.org/api/drupal/contributions!rules!rules.module/function/rules_invoke_event/7

All you'd need to do is setup a custom module with hook_rules_event_info() to tell Drupal about your rules, hook_token_list() to list out your tokens, and hook_token_values() so it knows how to render your tokens. Or use the tokens already available.


access denied feed/[id]/import for a feed item

Feeds locks a feed when you start an import from it. As soon as the import finishes, the feed gets unlocked again.

When a feed is in a locked state, you cannot initiate another import. Therefore feed/id/import results into an access denied page.

There can be occasions in which an import failed to finish. This can for example be caused by bugs in Feeds or other modules. An other possible cause is that the database server restarted or stopped in the middle of an import. If you use periodic import on the feed, it may be that the import did not fail to finish, but just needs a few more cron runs.

To unlock a feed, go to the feed page and click on the "Unlock" button or go to feed/id/unlock. If you see no button or get access denied for that path as well, try to clear caches. Drupal caches access to menu paths (Feeds does clear the cache for the paths in question when a feed gets locked or unlocked).


views - group by first letter of results

A simple solution would be to add a field that only had the first letter and group by that.

Views also supports doing glossary, which is a but different, but allows you to group by the first letter and count the number of results and show fx

A(2) B(2) C(0), as an exposed filter, this is done through contexts in views 3.


db_insert() execute() without auto_increment primary key is returning 0

That makes sense - if you haven't got an auto-increment field on the table, then you already have the ID that you're inserting, so it would make no sense for an arbitrary column (or primary key, or whatever) value to be returned by PDO.

If the query fails it will throw an exception. That's the best (probably only) way to check that the insert was successful in your case, short of running a separate query.

try {
  db_insert('...')->execute();
  // No exception thrown; PDO thinks the record was inserted correctly.
}
catch (PDOException $e) {
  // Query failed; recover based on $e->getMessage()
}


Drupal 8 Webform - Change to Dev Version

if you have drush on your server you can easily select a version with this command

drush dl webform --select

it should show something like this

Choose one of the available releases for webform:
 [0]  :  Cancel
 [1]  :  8.x-5.x-dev     -  2017-Sep-07  -  Development
 [2]  :  8.x-5.0-beta16  -  2017-Aug-08  -  Supported, Recommended
 [3]  :  8.x-4.x-dev     -  2016-Nov-28  -  Development

and you could press 1 then enter to select 5.x-dev

i believe you'd also be prompted with a message warning you that you're overwriting the previously installed beta16 version and you'll say ok


How to use Git with Drupal 8 when using composer

Short answer: no, you do not need to commit the vendor folder, because the contents are built using composer.lock and composer.json (both should be committed) when running composer install. Some people have to commit vendor due to their hosting constraints and/or having no build process (where the application is built for deployment).

IMO management via Composer with vanilla D8 tarball is very difficult as it lacks the structure to facilitate solid version control, project management and patching workflow that others like Drupal Project or Acquia BLT offer.


How to remove the default cache tags on a block?

Nope, you can't really opt out of those.

They are defined as required cache contexts in services.yml. So even if you'd manage to remove them, they are added in Renderer.php.

You could change that globally, but you have to be aware of the risks as it is likely that not every contrib/custom code is adding the user.permissions cache context when required, so we decided to make that a default so that at least that kind of cache/acess separation is enforced.


how can I change all price view in drupal commerce

You can do this using the Commerce Currency API

Implement hook_commerce_currency_info_alter and add your own commerce_currency_format handler

e.g:

/**
 * hook_commerce_currency_info_alter
 *
 * Add custom currency format to selected currencies
 */
function MY_MODULE_commerce_currency_info_alter(&$currencies){
  $currencies['IRR']['format_callback'] = 'MY_MODULE_commerce_currency_format';
}

/**
 * Currency format callback
 *
 * Remove decimal places from output
 * while keeping commerce_amount_to_decimal formatting the same
 *
 * See: commerce_currency_format
 */
function MY_MODULE_commerce_currency_format($amount, $currency, $object = NULL, $convert = TRUE) {

  // Format the price as a number.
  // In our case, we remove decimal places
  $price = number_format(commerce_currency_round(abs($amount), $currency), 0, $currency['decimal_separator'], $currency['thousands_separator']);

  // Establish the replacement values to format this price for its currency.
  $replacements = array(
    '@code_before' => $currency['code_placement'] == 'before' ? $currency['code'] : '',
    '@symbol_before' => $currency['symbol_placement'] == 'before' ? $currency['symbol'] : '',
    '@price' => $price,
    '@symbol_after' => $currency['symbol_placement'] == 'after' ? $currency['symbol'] : '',
    '@code_after' => $currency['code_placement'] == 'after' ? $currency['code'] : '',
    '@negative' => $amount < 0 ? '-' : '',
    '@symbol_spacer' => $currency['symbol_spacer'],
    '@code_spacer' => $currency['code_spacer'],
  );

  return trim(t('@code_before@code_spacer@negative@symbol_before@price@symbol_spacer@symbol_after@code_spacer@code_after', $replacements));
}


You should also have a look at the Field Permissions module, which allows you to control granular permissions per field by role.

By default, if a user can edit a node they can edit all fields, but Field Permissions allows you to create specific privileges for the field if you need more granular control.

So for this instance, you'd want to enable edit privileges for the fields you want to hide from the anonymous users, then go to user permissions and grant edit permissions for those fields only to authenticated users.  The result would be that the fields would be hidden from anonymous users, but still editable by authenticated users.

You could then use the Forms API as Dan described to make the fields all of a length for anonymous users, or use something as simple as CSS if your theme attaches a body attribute for logged-out users (many do).


How to resolve configuration objects lang code differences?

I'm not sure I can help but I had a similar issue.
After enabling translation for pages, I got a similar error in admin/structure/types/manage/page/translate:

The configuration objects have different language codes so they cannot be translated:

node.type.page: en
core.base_field_override.node.page.title: pt

I think this happened because I was by mistake in /pt/admin (?).

Anyway, I fixed this (in my case, I always want en), by running the command:

$ drush cset core.base_field_override.node.page.title langcode en


Custom feed tamper plugin to convert an image GUID into a URI

I came up with a solution, simply using a DB query to get what I want. Here is the callback for the tamper module. Hopefully someone will find a better solution, if it's possible.

function myfeedsmodule_tamper_imagekey_callback($result, $item_key, $element_key, &$field, $settings) {
  $field = trim($field);
  if ($field == 'NULL') {
      $field = NULL;
      return;
  }
  $result = db_select('feeds_item', 'f')
          ->fields('f', array('entity_id'))
          ->condition('guid', $field, '=')
          ->condition('entity_type', 'file', '=')
          ->condition('id', 'my_image_importer', '=')
          ->execute()
          ->fetchField();
  if (!$result) {
      $field = NULL;
      return;
  }
  $entities = entity_load('file', array($result));
  if (!$entities) {
      $field = NULL;
      return;
  }
  $image = current($entities);
  $field = $image->uri;
}


in drupal you can create node using node_save function as below

$node = new StdClass();//creating a bare node
$node->type = 'answer';//giving it type
$node->status = 1;//give it a published staus
$node->title = "Step up to the FLava";//gives title
$node->body = "Body Body body"; //gives body

node_save($node);
//save it and give it the rest of the attributes`


How do I access a custom field from an action?

Preface

Be aware of what's written in comment nr 7 of issue nr 2574691:

  rules 8.x-3.0-alpha1 ... is a preview release and is not intended for production sites. Use at your own risk.

With that in mind, read on for more details to do a similar experiment with rules 8.x-3.0-alfa1.

Verify setup of content type and field

I'll use content type "Article", which already has a field with machine name "field_image" (out of the D8-box).
Navigate to /admin/structure/types/manage/article/fields to verify this.

Create a rule

Enable the Rules module.
Navigate to /admin/config/workflow/rules and create a new rule, with these details:

Use Rules Event "Before saving content"
Add a Rules Condition like "Entity has field" (for the field_image field). To do so, click on "Value" (within the "Entity" box), and select node. And also click on "Value" (within the "Field" box), and select field_image. Then click the Save button (to save the Rules Condition).
Add a Rules Action "Set a data value",and continue like so: click on "Value" (within the "Data" box), and select node:field_image:value (note that for this Data Selector I'm using : (twice), instead of . (twice) as in your screenprint). And also enter some "Value" (within the "Value" box), eg myNiceImage. Then click the Save button (to save the Rules Action).
You are then returned to the "edit rules reaction" screen (for the rule you are editing. And it shows a message like "You have unsaved changes.". Click the Save button (to save the rule). Then a message will be shown like "Reaction rule ABC has been updated." (ABC = the label you gave to your rule).

Verify if the rule got saved

Navigate to /admin/config/workflow/rules to ensure the rule was really saved (that it does show up there).
Navigate to admin/config/development/configuration/single/export and as "Configuration type" select "Reaction Rule". Then select the label of your rule as the "Configuration name".
You should then see the exported rule, which should look similar to mine, i.e.:

uuid: ab289332-0b45-484f-a1ae-38842620b7e4
langcode: en
status: true
dependencies: {  }
id: check_a_field_before_saving_a_node
label: 'Check a field before saving a node'
events:
  -
    event_name: 'rules_entity_presave:node'
description: ''
tags:
  - ''
config_version: '3'
expression:
  id: rules_rule
  uuid: 354332c5-8307-4097-b33c-0e77307a5e0e
  conditions:
    id: rules_and
    uuid: e82407a4-05c6-45d3-8195-1c1b5f34a07d
    conditions:
      -
        id: rules_condition
        uuid: 3c9094ed-95ec-4202-8398-5a6ca000604a
        context_values:
          entity: node
          field: field_image
        context_mapping: {  }
        context_processors: {  }
        provides_mapping: {  }
        condition_id: rules_entity_has_field
        negate: false
  actions:
    id: rules_action_set
    uuid: 3313095c-f75a-46f2-8d11-f845d12a90f2
    actions:
      -
        id: rules_action
        uuid: 23a3a68e-893e-48c4-a7ee-102201af5a25
        context_values:
          data: 'node:field_image:value'
          value: myNiceImage
        context_mapping: {  }
        context_processors: {  }
        provides_mapping: {  }
        action_id: rules_data_set

The above export should illustrate that I could perfectly save this ... because otherwise I could not have exported it, right?

Pushing the limits

So far so good, but next I wanted to update the value to be assigned in my Rules Action, let's say myNiceImage should be updated to myNewestNiceImage. So I returned to my Rules Action, and started to edit it. But, that resulted in an error message like so:

  The context Data may only be configured using a selector.

By clicking on the Switch to data selection button (so that the button label changed to Swith to direct input mode), and trying again, I got another error message like so:

  Data selector node:field_image for context Data is invalid. Unable to get variable node:field_image, it is not defined.

There has to be a way to do it ...

So it seems like updating a Rules Action is not what you should try to do (at least not in the current D8 release of the Rules module).

However, here are the steps I performed to actually get the value updated (from myNiceImage to myNewestNiceImage) anyhow:

delete the Rules Action (with the old value myNiceImage).
create a new Rules Action (with the new value myNewestNiceImage).

Voilà!

PS: did you notice I'm using "Entity has field", and not "Entity is of type"?


How to override a view template in Bootstrap sub-theme

This is how I template my views in bootstrap sub-themes with or without the bootstrap views module b/c sometimes you need to change those as well :)

First - In my sub-theme's for Bootstrap I make a folder called 'views' in the 'templates' folder (this is for sanity and structure, I think it works without the folder but don't quote me on that). There's only one view template in the bootstrap theme, for a responsive table so you can template anything however you want using the normal views templates.

You can also use the bootstrap views module mentioned in the other answer but you may still want to template those again in your subtheme so you will need the above folder '/templates/views' and now the  documentation page you mention has some of the templates but views comes with a way to accomplish this without that page in the UI.

Loose instructions for views templates.

open a view in the admin view UI screen
look on the left hand column for advanced, expand if needed.
look to the very bottom of that column and you will see Theme: Information
click that link, pop up appears
this is your views theming information, you will see that the current template being used is in bold.
I usually go find that template beg used, copy that into my subtheme's '/templates/views' folder and choose from the list in the popup what I need to name the file, like for a view named "repair" I wouldn't want to use views-view.tpl.php and overwrite all the views display output, I would want to use views-view--repair.tpl.php so I name my file that and change something subtle.
then I go hit the rescan templates files button in the popup and my new template will be in bold.
I save the view and go make sure I did something productive.
don't forget to clear cache if you aren't seeing what you want to see, it usually pops up after that, if not double check your naming of the file.

Hope that helps, views templates rock and I use them a pretty good bit just let me know if that doesn't work.


$roles = array('role1','role2','role3');
foreach($roles as $name) {
 $existing_role = user_role_load_by_name($name);
 if (empty($existing_role)) {
  $role = new stdClass();
  $role->name = $name;
  user_role_save($role);
 }
}

I have placed the same snippet in module install file and it is working just fine. You need to enable and then uninstall the module and re-enable it, I hope it will work.


How do you configure it so a published article promoted to another page instead of "front page"?

With Views, you can use "promoted to front page" as a filter value, so that things with that box checked can also be "promoted" to any page view that takes that as a filter.

If you don't want to us the native "promoted to front page" checkbox, but would rather have a separate checkbox just for that page, you can add a custom field to your content type(s) and use that as a filter value instead.


Cannot get currentUser after custom Drupal boot

You have to authenticate the user. This is what a normal Drupal request would do as one of the first things after the kernel is booted:
Drupal\Core\EventSubscriber\AuthenticationSubscriber
  /**
   * Authenticates user on request.
   *
   * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
   *   The request event.
   *
   * @see \Drupal\Core\Authentication\AuthenticationProviderInterface::authenticate()
   */
  public function onKernelRequestAuthenticate(GetResponseEvent $event) {
    if ($event->isMasterRequest()) {
      $request = $event->getRequest();
      if ($this->authenticationProvider->applies($request)) {
        $account = $this->authenticationProvider->authenticate($request);
        if ($account) {
          $this->accountProxy->setAccount($account);
          return;
        }
      }
    }
  }

Adapting this to the procedural code:
web/foo.php
<?php

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

$autoloader = require_once 'autoload.php';
$request = Request::createFromGlobals();
print_r($request->cookies);             // ... ( ... ( [SSESSabfa7...] => _Eu_28jS3Vr8Y... ))
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
$kernel->boot();
$kernel->preHandle($request);

$container = $kernel->getContainer();
// Ensure our request includes the session.
$request->setSession($container->get('session'));
// Authenticate the user, see AuthenticationSubscriber::onKernelRequestAuthenticate().
$account = $container->get('authentication')->authenticate($request);
if ($account) {
  $container->get('current_user')->setAccount($account);
}

var_dump(\Drupal::currentUser()->id());


What's $mask in file_scan_directory() to find all png files?

The following mask should work for you:

'/.*\.png$/'


How can I perform an operation programatically when the value of a user field is changed?

The Content translation module has code you could use, right in its hook_entity_presave() implementation (i.e. content_translation_entity_presave()).

if (!isset($entity->original)) {
  $entity->original = entity_load_unchanged($entity->entityType(), $entity->id());
}

In $entity->original you then find all the values that entity object had before being changed, as the documentation for entity_load_unchanged() says:

  Loads the unchanged, i.e. not modified, entity from the database.

  Unlike entity_load() this function ensures the entity is directly loaded from the database, thus bypassing any static cache. In particular, this function is useful to determine changes by comparing the entity being saved to the stored entity.

If you want to write code that will need less changes when passing to Drupal 9, you can use the following one, which replaces the call to entity_load_unchanged() (marked deprecated) with that function's code.

if (!isset($entity->original)) {
  $entity->original = \Drupal::entityManager()->getStorage($entity->entityType())->loadUnchanged($entity->id());
}

Also image_entity_presave() uses $entity->original, but it doesn't load it if it has not been set.

$original_uuid = isset($entity->original) ? $entity->original->getSetting('default_image')['uuid'] : NULL;

Probably, you could simplify the code.

if (!isset($entity->original)) {
  // Get the old value of the field.
}

Looking at the method calling hook_entity_presave(), EntityStorageBase::doPreSave(), the latter seems a more correct code.

  $id = $entity->id();

  // Track the original ID.
  if ($entity->getOriginalId() !== NULL) {
    $id = $entity->getOriginalId();
  }

  // Track if this entity exists already.
  $id_exists = $this->has($id, $entity);

  // Omissis

  // Load the original entity, if any.
  if ($id_exists && !isset($entity->original)) {
    $entity->original = $this->loadUnchanged($id);
  }

  // Allow code to run before saving.
  $entity->preSave($this);
  $this->invokeHook('presave', $entity);

EntityStorageBase::doPreSave() already sets $entity->original for entities that aren't new; the code used from content_translation_entity_presave() seems excessive.


Multiple regions in a zone with different widths

This issue has been resolved.

What i did to resolve the issue:

I had to setup the Zone in the sub-theme settings first. So i went to the sub-theme settings and assigned Weights from 0-5 for Regions Footer First uptil Footer Second.

Once this was done, the changes were reflecting properly.


col-sm-4 will be applied via a function in the theme. if you search through the theme for where the variable is set you can change it there. Possibly in the .theme file.


Sort an entity query by a term reference field's term weight?

Since the weight is kept in a different table than the one that stores the data related to your node, I'm afraid this is impossible using EntityFieldQuery. You'll have to do some custom coding after the query.

By the way, to use data from the reference field (field_data_your_reference) you could use a fieldCondition or fieldOrderBy.


How to manage the order of the modules execution?

You can change the module weight in your system table in the data base. This will reorder the execution of the modules and also the inclusion of js.

You can update the weight via myphp admin or you can do it via a custom modules .install file in a hook_install. for example:

db_update('system')
 ->fields(array(
   'weight' => 10,
 ))
 ->condition('name', 'module_name')
 ->execute();

Replace module_name with the name of the module you would like to delay.

Clear all cache afterwards


Some variables not listed when creating feature

If that variable is showing up in the Strongarm admin page, then it means that it's already strongarmed - it probably already exists in another Feature. Use the grep command to search for instances of it in your codebase:

grep -irn 'pathauto_entity_available_entity_types' [codebase-dir]

I bet that will turn up an existing Feature that is managing that variable.

You can't export the same variable to more than one Feature. But you can override it with the Features Override module.


Do we need hash in Config Sync Directory if outside root

The only purpose of the hash is to make it impossible to guess the location of the exported config. This is an additional access control in case .htaccess in the sync folder fails to do this.

If the config folder is outside of the root of the webserver you don't need the hash.


Different css of #main-content at differnt page url?

Option 1 - Pure CSS

For those specific pages you can use the classes found in the body tag to override your generic style like so:

#main-content { ... }

.page-node-123 #main-content {
  your override for this node
}
.node-type-article #main-content {
  your override again
}

Option 2 - CSS with Drupal coding

Use preprocess hooks like hook_node_view or template_preprocess_page or hook_preprocess_html in the template.php file in your theme and add additional classes based on your specific requirements/conditions

Then use CSS to target those classes or IDs.

Drupal helps us already by default on basic IDs and classes that we need to target things globally or specifically we just need to do an inspect element on the page and check for yourself.


Eliminate render-blocking JavaScript and CSS in above-the-fold content

The README has a guide on how to do this using current 7.x-2.31+ version of AdvAgg. Also see this wiki page on the High performance group. Most sites can achieve a perfect 100/100 score on https://developers.google.com/speed/pagespeed/insights/. Directions on how to achieve it for a fresh of install of AdvAgg below.

Be sure to check the site after every section to make sure the change didn't mess up your site. The changes under AdvAgg Modifier are usually the most problematic but they offer the biggest improvements.

Advanced CSS/JS Aggregation

Go to admin/config/development/performance/advagg

Select "Use recommended (optimized) settings"

AdvAgg Compress Javascript

Install AdvAgg Compress Javascript if not enabled and go to
admin/config/development/performance/advagg/js-compress

Select JSMin if available; otherwise select JSMin+
Select Strip everything (smallest files)
Click the batch compress link to process these files

AdvAgg Async Font Loader

Install AdvAgg Async Font Loader if not enabled and go to
admin/config/development/performance/advagg/font

Select Local file included in aggregate (version: X.X.X). If this option is not available follow the directions right below the options on how to install it.
Check "Use localStorage so the flash of unstyled text (FOUT) only happens once."
Check "Set a cookie so the flash of unstyled text (FOUT) only happens once."

AdvAgg Bundler

Install AdvAgg Bundler if not enabled and go to
admin/config/development/performance/advagg/bundler

HTTP/2.0 Settings

Under "Target Number Of CSS Bundles Per Page" select 25
Under "Target Number Of JS Bundles Per Page" select 25
Under "Grouping logic" select "File size"

HTTP/1.1 Settings (default)

Under "Target Number Of CSS Bundles Per Page" select 2
Under "Target Number Of JS Bundles Per Page" select 5
Under "Grouping logic" select "File size"

25 bundles vs 2 and 5 has to do with browser caching. More files equals a better chance of the browser having that combo in its cache, but more files means more connections being established and opened in HTTP 1.1. Use 2 for CSS as this number doesn't wait for any new connections; JS is 5 as most browsers have a concurrent connections limit of 6. This number for bundles was picked after many tests. In HTTP 2.0 there is one streaming connection and the penalty for multiple CSS and JS files is almost non existent; thus optimizing for the browser cache is the best choice; thus 25 should be used for CSS and JS when serving HTTP/2.0.

AdvAgg Relocate

Install AdvAgg Relocate if not enabled and go to
admin/config/development/performance/advagg/relocate

Select "Use recommended (optimized) settings"

AdvAgg Modifier

Install AdvAgg Modifier if not enabled and go to
admin/config/development/performance/advagg/mod

Select "Use recommended (optimized) settings"

Generating Critical CSS Files

Go to https://www.sitelocity.com/critical-path-css-generator and input as many landing pages as needed for critical css; the top 10 is usually a good start. If you have Google Analytics this will show you how to find your top landing pages https://developers.google.com/analytics/devguides/reporting/core/v3/common-queries#top-landing-pages
or for Piwik https://piwik.org/faq/how-to/faq_160/. If you don't know what page to start with do your site's homepage. You can also us this to generate css https://chrome.google.com/webstore/detail/critical-style-snapshot/gkoeffcejdhhojognlonafnijfkcepob?hl=en

Example filenames and paths below are for the "bootstrap" theme; they all start with sites/all/themes/bootstrap/critical-css/; in your theme create the critical-css/ directory. The next directory is based on the user; anonymous/,  all/, or authenticated/ can be used.

The next directory can be urls/ or type/. Looking at urls/; front is a special case for the front page, all other paths use current_path() as the directory and filename with .css added to the end; See https://api.drupal.org/api/drupal/includes%21path.inc/function/current_path/7.x

Looking at type/ this is a special case for node types. Use the machine name and add .css to the end. Any node of this type will then have this critical css file applied and inlined. Below are some examples showing how this works.

valid example file locations for the "front" page:
sites/all/themes/bootstrap/critical-css/anonymous/urls/front.css

valid example file locations for "node/1" current_path() page:
sites/all/themes/bootstrap/critical-css/anonymous/urls/node/1.css

valid example file locations for the node type of "page":
sites/all/themes/bootstrap/critical-css/anonymous/type/page.css

If you want some sort of automated way to generate these css files fourkitchens
has an excellent article on how to set that up:
https://fourword.fourkitchens.com/article/use-grunt-and-advagg-inline-critical-css-drupal-7-theme


how to prevent javascript from running again when an AJAX form is submitted

If Ajax reloads this part you are hiding, the marker once() has set is overwritten, also the show/hide status. Then you need a different approach, either submit the show/hide status, so that it can be returned by Ajax, or create a show/hide Ajax form element to have full control over it through Ajax.

If this is outside of the Ajax wrapper you can do this in javascript, but apply the jQuery selectors on context:

$('#views-exposed-form-faceted-search-page .form-type-select', context).once('search-hide').hide();

See https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview


"Add another item" using #ajax in hook_field_widget_form

Looks like you're just missing a #tree property:

  Used to allow collections of form elements. Normally applied to the "parent" element, as the #tree property cascades to sub-elements. Use where you previously used ][ in form_ calls. For more information, see #tree and #parents in the handbook.

e.g.

$element['question_wrapper'] = array(
  '#type' => 'fieldset',
  '#title' => t('Questions'),
  // Set up the wrapper so that AJAX will be able to replace the fieldset.
  '#prefix' => '
',
  '#suffix' => '
',
  '#tree' => TRUE,
);

And then in the validate handler:

foreach ($form_state['values']['question_wrapper'] as $key => $value) {
  if (is_numeric($key) && something_is_wrong_with($value['question'])) {
    form_set_error("question_wrapper][$key][question", 'Error');
  }
}


Drupal 7 - Add Items to multiple places in a menu

Unfortunately, this is a feature not available in Drupal core. The issue is being worked on, but does not currently have a solution: http://drupal.org/node/609542

In the meantime, one potential solution is to use path aliases to the same node. Thus you might have /voter/our-public-awareness-campaign and /news/our-public-awareness-campaign which both point at a particular node. Drupal should treat the two menu entries as unique/separate then, and thus only the one you want to show as the menu should be activated.


What variable will let me access user profile info?

If this link is to be on the user profile page then you can grab the related user ID from the internal URL (using the arg() function), and then use user_load() to load a user object that contains the username:

// Get user ID from internal router path (this isn't necessarily the URL shown in the address bar, it's the internal path that Drupal is using to serve the page).
$uid = arg(1);

// Load the user account and extract the username
$account = user_load($uid);
$username = $account->name;


Drupal Front end Form with fields with option to add More Fields

Assuming that "Name of Stocklists", "Sales as on Date", and "Closing Stock Value" are all CCK fields, you should be able to do this using Field Collection (https://drupal.org/project/field_collection).

1) Install Field Collection

2) Create a field collection field on your Report content type. Use the embedded widget. Be sure to make the field multi-value / unlimited values.

3) Go to admin/structure/field-collections and click Manage Fields for the field collection you created.

4) Add the 3 stock text fields to the field collection.

5) Now on the Report add/edit forms, you'll have the "Add Another Item" button.

To align the fields in a row, you should be able to use CSS. To make the button a +, you should be able to use hook_form_alter() or hook_form_report_node_form_alter().


In this particular case, the issue was that Drupal 7.30 had become available, and the UI of the site was reporting that it had 7.28 installed. This was cached by an out-of-date cache, I believe. Everything was resolved when I updated from 7.29 to 7.30.


It turns out that I need a combination of changes:

I had to implement hook_form_alter()in a module and set the form's #theme property:

function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['#theme'] = 'user_register';
}

And then in template.php:

function mytheme_theme($existing, $type, $theme, $path){
  return array(
    'user_register' => array(
      'render element' => 'form',
      'template' => 'templates/user-register',
    ),
  );
}

function mytheme_preprocess_user_register(&$variables) {
  $variables['rendered'] = drupal_render_children($variables['form']);
}

And then I added user-register.tpl.php with my desired markup, and

<?php echo $rendered; ?>

to print the form.


How to alter HTML generated for $messages?

You just need to override the theme function...

theme_status_messages($variables)

https://api.drupal.org/api/drupal/includes%21theme.inc/function/theme_status_messages/7

function YOURTHEME_status_messages($variables) {
// code goes here...
}


Editing the navigation menu template in Drupal 8

Simply needed to clear the cache... case closed!


Is it possible to hide menu items based on path?

Yes you can by using an access callback which when defined calls a function. In this function you can analyze the path and based on that return TRUE or FALSE. When you return FALSE, the menu item is not visible. See the documentation of hook_menu for more details.

A simple example:

// in hook_menu something like this, important part is the 'access callback'
 $items["menu/item"] = array(
     'title' => "menu item 1",
     'description' => 'Access test',
     'page callback' => 'node/1',
     'access callback' => 'check_path',
     'menu_name' => 'navigation',
     'type' => MENU_NORMAL_ITEM,
 );

// then define your access callback function
  function check_path(){
    // check path here and return TRUE or FALSE
    return TRUE;
  }

I just asked a similar question dealing with this: How to build a dynamic menu structure. You may find more information in that question that can help you.


Unset required attribute with multiple submit buttons and multistep form

You can set the #limit_validation_errors property on your submit button to an empty array to bypass validation on all required elements.


Are blocks still cached when "Cache block" setting disabled but "Cache pages for anonymous users" is enabled?

TL;DR yes

Well, not per se. But page it appears on is cached, including that block. There is no separate item for the block in any cache in situation you described, but it won't be recreated anyway. Code for it won't be executed. And yes, in default Drupal configuration page caches works only for anonymous users.


How to add two separate GA accounts in one Drupal site

Go to /admin/config/system/googleanalytics > ADVANCED SETTINGS > CUSTOM JAVASCRIPT CODE > Code snippet (after)

ga('create', 'UA-XXXXXXXX-Y', 'auto', {'name': 'foo'});
ga(function(foo) {
  foo.send('pageview');
});
ga('create', 'UA-XXXXXXXX-Y', 'auto', {'name': 'bar'});
ga(function(bar) {
  bar.send('pageview');
});

This worked for me.


How to diagnose an undefined index in a fresh install of Drupal 7?

In this development copy I've turned off Contextual (drush dis contextual) which of course gets ride of the error message.

I welcome any other answers that might offer a bit of enlightenment to me on this matter. We can live without the Contextual module's functionality but it does add some additional clicks to accomplish certain task.


Just create a local setup of drupal with meta tags module installed.

Now check for its table structure, if any of the table or column is missing add it manually. Because it can be issue occured you enabled the module.

Other soluion can be disable metatag module then uninstall it and then re-enable it. It might fix issue for you.
It is just the issue of missing table and column field.

Hope it will help.


How do I tell Drupal not to aggregate my css file

To stop a file being aggregated, you can add a flag to the drupal_add_css() command which loads the file. To do this, hunt where the CSS is added and add array('preprocess' => FALSE) after the style, e.g.

drupal_add_css('/fonts/fonts-min.css', array('preprocess' => FALSE));

Alternatively, external CSS are never compressed, so if you change the CSS to the absolute URL of the file it won't be compressed.

drupal_add_css('http://mysite/css/fonts-min.css');

If you want to change a CSS included from a .info file, it might be best to add it as an external file with _preprocess_html in template.php. This is well explained under 'Adding external stylesheets' on this page.


How to skip specific tables with drush sql-dump?

Dump all tables except the cache table and tables starting with cache_.

drush sql-dump --skip-tables-list=cache,cache_* > dumpfile.sql

Database structure only. No data at all.

drush sql-dump --extra=--no-data > dumpfile.sql

Data only. No cache data and no cache structure.

drush sql-dump --skip-tables-list=cache,cache_* --data-only > dumpfile.sql

No cache data but dump in their structures.

drush sql-dump --structure-tables-list=cache,cache_* > dumpfile.sql

sql-dump documentation


How handle large number of images in gallery node Drupal 7

I do not know the intended site behaviour, or interface, for your galleries.  However, I would restructure the site.  Have you looked at each gallery "entry" being a node with 1 picture field and 1 taxonomy term reference?  The terms would then be your "galleries", you could use views to build the pages any way you want, even lazy load.  You could add sorting, and since you would not have 100+ field entries on any one entity, loading the entity into a variable for the various page build tasks would be far faster.  Gallery nodes work fine if they have less than 30 entries, but it sounds like your data management could use some revision.


Yes it is because you uninstalled the contact module.  Try to install it again, then reset/delete that menu link from it and then uninstall it again.


Yes, this module has a critical error for your problem. A week ago an issue was opened and need to be revived. But you can add your own patch to the module by yourself.
Here is the issue and solution for Drupal v7:
https://www.drupal.org/project/imagick/issues/3026933

and you can apply to Drupal v8 under file imagick\src\Plugin\ImageToolkit\Operation\imagick

protected function process(Imagick $resource, array $arguments) {
    $color = $arguments['HEX'];
    $color = empty($color) ? 'none' : $color;
    //return $resource->colorizeImage(new ImagickPixel($color), 1);
    return $resource->colorizeImage(new ImagickPixel($color), 1, true);
  }


For this purpose is better to use exposed filters. You can hide output of this filter in theming - it still be working. Just pass filters vlue in GET parameters to view's page.


Using PrivateTempStore for anonymous users with Internal Dynamic Page Cache & Internal Page Cache modules

Private TempStore always generate Anonymous Session. That means If you are using any Caching Layer for your Application it always break. either in Acquia or other platform.
May be you can use Browser LocalStorage for saving data and sync it when its required. it will help you to cache your pages.
In Acquia, cookie based cache variation Generation possible so you have to create cookie and based on that value you can generate cache tags.


drupal 7 date field stores todays date even when user hasnt entered a value

By Form API reference you need to manually set '#default_value' to prevent it from defaulting to today. So just add:

'#default_value' => NULL,

to your field's array to prevent it.


URL paths taxonomyterm/pagename instead of content/pagename

Under /admin/config/search/path/patterns you can change the default pattern for the content type from content/[node:title] and set the pattern to [node:field-tag]/[node:title]. It is probably a good idea to restrict field_tag to a single value, and to make it required if you are going to use a pattern like this.


Change default language to English on this page /admin/config/regional/language


How to use a field value in Template.php

You can find the node object in $variables['node'], and from there you can use the field_get_items() function to extract your field value:

$node = $variables['node'];

// field_get_items() always returns an array, even if the field is limited to one value
$field_items = field_get_items('node', $node, 'field_name');

// Get the value from the first item in the array (if that's the one you need)
$title = $field_items[0]['value'];


How to reference a Current Node URL Prior/After a User submits a Rules Link trigger

A custom way to do it... Sorry not using Rules but it might help.

So you have two main node types ? And advert and an application ?
And the link to the application needs to contain the node ID of the advert.
I would use a custom link and hook_form_alter. For example;

If the apply link is only seen on the advert node page then you can use:

$nid = arg(1);
print l(t("Apply"), "node/add/application/$nid");

either in a node.tpl.php or in a preprocess function.

This will take the user to the node add form.
In a custom module you use hook_form_alter to get the $nid from the URL and add it to the form in the in the right field such as :

/**
 * Implements hook_form_alter().
 */
function custommod_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#id'] == 'application-node-form') {
    if (isset(arg(3))) {
      $form['field_advert_relation'][LANGUAGE_NONE][0]['target_id']['#default_value'] = arg(3);
    }
  }
}

This is for a normal entity reference field.
And the field could be disabled or hidden also.


Unique violation when trying to create a new Field Collection using Rules

It seems to be working fine, when I'm using event "Before saving content (of type ...)". If you also want to make sure, that it only affects newly created entities (mostly nodes), you'll also want to add condition "Data value is empty" for node:nid or another entity ID.


new submit button to node form not displayed?

It will be displayed somewhere between the node form elements. May be you didn't notice that. Try appending this form element under actions like this. Then You can see the button along with save and preview button.

$form['actions']['submit_delegate'] = array(
  '#type' => 'submit', // I tried also '#type' => 'button'
  '#value' => t('Delegate'),
  '#submit' => array('MYMODULE_form_submit_article_delegate'),
);


Display a value for an empty CCK Field without setting a default value?

The empty_fields modules will help in this case


How to sort view by content type, using literal ordering, as second order-by clause

Although there may be a method to do this via a query alter I was unable to find the correct solution. I was however able to find a solution.

Although we utilise search API heavily and we can use the content type relevance weighting we had a requirement to sort by a custom content type order and then by date, in addition some content types needed the same weight.

Our solution: Add a search weighting field to the required content types (e.g. integer 1-5) and include it in the index.  In the view add a sort filter for your search filter field.

You'll need to batch process or use views bulk operations to fill in existing node data and hide the field from content add / edit screens if required.

One added benefit of this method is, if the client wants to have a piece of content show at the top when it's in the result set they can manually amend the new field for it.


I've had this quite a few times, I'm not sure what the initial problem is but I've solved it by doing either one of the following:

Disabling the feature and re-enabling it
If above fails disable delete content type then re-enable (not an option if there existing content on the site)
Manually editing the content_field_instance table (D6) and enabling it there.


From another implementation of the same hook I found out that the node is actually available through the following. Try it out.

  $node = $variables['node'];

From there you can get node id.


Not all fields of node are present in content

The {{ content }} variable within node templates contains all fields configured to be visible within your content type's display settings. If you experience fields missing, they are most likely disabled within your display.

Head over to your administrative backend's Structure > Content types > [Your content type] > Manage display settings and ensure all fields you are trying to access are enabled for your current display mode.

You can always access disabled fields within your node templates by accessing the original node entity. The node entity along with its fields and some limited accessor methods are available within the {{ node }} variable of your templates.

Use e.g. {{ dump(node|keys) }} for debugging the available properties of the node within your template.

Comprehensive documentation about the variables within node templates can be found within it's header's comment block.


Filter a view based on current user's roles?

Following @Jimajamma's suggestion, here's what I used. I adapted his code slightly for Drupal 7 and to allow for other roles than Administrators full access to the results.

In the View, add a contextual filter on Author: Uid, and use the following settings:

WHEN THE FILTER VALUE IS NOT AVAILABLE:

Provide default value
Type: PHP Code

Use the following code:

global $user;

if (
    in_array('administrator', $user->roles) ||
    in_array('editor', $user->roles)
)
{return -1;}
else
{return $user->uid;}

WHEN THE FILTER VALUE IS AVAILABLE OR A DEFAULT IS PROVIDED

Specify validation criteria
Validator: PHP Code

Use the following code:

if ($argument == -1)
{return FALSE;}
else
{return TRUE;}

Action to take if filter value does not validate: Display all results for the specified field (this is what will give admins access to all results)

And that's it!

Notes:

Compared to my initial settings, the relationship (Content: Author) isn't needed anymore; neither is the "Author" filter (which was brought in by the relationship anyway).

Apparently, for Drupal 6 the condition in the first PHP snippet should rather be if (in_array('super user', array_values($user->roles))).


selected option on drupal form not coming up first

This is only a problem in firefox, and the way to fix it so it works in firefox as well is to add this:
     $form['#attributes']['autocomplete'] = 'off';


Having username as a path - Profiles 2 and Pathauto

you can automatically path save the user name when user access the user/uid page
add a submit handler in form alter and

$form['#submit'][1] = 'redirect_to_profile_username_page';

// here get the user name field

function redirect_to_profile_detail(&$form, &$form_state){
$uid = $form_state['build_info']['args'][0]->uid;
$user = user_load($uid);
$clean = $user->name;
      $Alias_1 = get_alias('source','user/'.$uid,1);
        $pathAlias = !empty($Alias_1) ? $Alias_1['alias'] : FALSE;
        if($pathAlias === FALSE){
                path_save($args = array("source" => 'user'.'/'.$uid,"alias" => $clean));
                $pathAlias = drupal_lookup_path('alias',$clean);
        }
       $form_state['redirect'] = $clean;
     }

this will redirect the user/uid page to that particular username as url page

here we are creating a aliase for user/uid so when you access sitename/username that user profile page will be loaded.


I would be rather suspicious about the '#ajax' way. Try to have a look here : http://api.drupal.org/api/examples/ajax_example%21ajax_example_misc.inc/function/ajax_example_render_link/7

What they say :

include the ajax.js
add use-ajax class
implement ajax callback under the link your link directs to

what should be done after the callback executes can be set by the ajax commands.


You could use Comment goodness it has a stable D7 release.

  Provides comment sorting, comment form placement and comment form
  configuration settings.


In Drupal7, both modules and themes are able to use preprocess functions in the same way, and a given theme hook can have many preprocess implementations, originating from both modules and themes.

As with anything like this in the Drupal framework, knowing the order in which these functions run is important. Preprocess implementations from modules run first, and implementations by themes run last.

A quick search of Drupal core modules will give you examples in the node and rdf modules.


How do I restrict the date popup to 12 months from start date?

Following Method i used to restrict the date Pop-up to 12 months

$form['set_start_date'] = [
      '#title' => $this->t('START DATE '),
      '#type' => 'date',
      '#attributes' => array('type'=> 'date', 'min'=> '-12 months', 'max' => 'now' ),
      '#date_date_format' => 'd/m/Y',
    ];

 $form['set_end_date'] = [
      '#title' => $this->t('END DATE'),
      '#type' => 'date',
      '#attributes' => array('type'=> 'date', 'min'=> '-12 months', 'max' => 'now' ),
      '#date_date_format' => 'd/m/Y',
    ];

  $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Filter'),
    );

 return $form;
}


Anyway to clone the shipping services at: admin/commerce/config/shipping

I would do this programmatically. As you will need this to be done only once, you can just run this from devel/php or in a custom module.

Zones are just there as an example; prepare an array with two letter zone codes / some other identifier and run the same code:

$zones = range(2, 10);
foreach ($zones as $zone) {
  $shipping_service = array(
    'name'            => 'flat_rate_for_zone_' . $zone,
    'title'           => 'Title for zone ' . $zone,
    'display_title'   => 'Display title for zone ' . $zone,
    'description'     => 'Description for zone ' . $zone,
    'rules_component' => TRUE,
    'data'            => array(),
    'is_new'          => TRUE,
    'amount'          => 900,
    'currency_code'   => commerce_default_currency(),
  );
  commerce_flat_rate_service_save($shipping_service);
}

Hope this helps.


Please override field-collection-item.tpl.php file present in the Field Collection module directory. You can put your code in that. Just simply copy it to your theme folder, and place the code inside it.


How to create a checkbox field in a node for Terms and Conditions

There are several contrib modules available that enforce users to agree to terms or conditions. Wouldn't it be technically easier and more practical for users to agree to the terms once, when they register? The legal module is quite good for this and has a feature where if you (as the site admin) change the terms and conditions after a user has previously agreed to them, then they can be asked to re-agree to the new terms next time they login.

If you absolutely have to go down your system design path, then:

You could use hook_form_alter() or hook_form__alter() to set a custom validation hook.
Have a look at the conditional_fields module for making it required depending on users role. You could alternatively do this logic in the hook_form_alter() or hook_form__alter() as per #1.
I'm pretty sure the Drupal Forms API won't allow links in the field label, but feel free to correct me. Alternatively you could add the links in the field description or write some jquery to achieve this (albeit a little hacky).

Hope that can help.


You can achieve that by using the Menu Trail By Path module.

  Menu Trail By Path sets the active-trail on menu items according to
  the current url.

  For example if you are at yoursite.com/blog/category1/article1 Menu
  Items with these paths will get the active-trail class on them and
  expand accordingly.

  blog blog/category1 blog/category1/article1

  8.x-1.x branch

  8.x-1.x branch is completely rewritten. It should be compatible with any menu.


Upgrading from 7.22 to 7.28, htaccess file in /tmp

Make sure your file system settings are set to /tmp or tmp, then...

In the tmp folder, select the htaccess and delete it from your FTP, then refresh your site cache.

Drupal will replace the missing .htaccess automatically.


using $_POST values in form alter to add validation

You should use $form_state['storage']. This will cache your data and make it available throughout the forms lifecycle.


Execute a rule after a countdown finishes

You need to use Rules Scheduler. You can create a date field on you content type, and then on some event such as creating or updating the content type you :

check for an old scheduled event on that content instance and delete it
read in the date field.
schedule a new event.

The event that you schedule will be a rules component that you create that will take in the nid of the content type, and then in its action section closes it.

If you need help on this check out Johan Falk from Node One's series on Rules.


Drupal 6: using template based on browser version

Normally that would be done with conditional css e.g. conditional_styles and that approach is recommended first.

Mainly because why change the entire template when only the CSS needs changing?

However, if you really need separate tpls ( e.g for new HTML markup ), you could probably use template suggestions in hook_preprocess_page after checking the browser user agent.

Something like this in template.php

/**
 * Implements hook_preprocess_page
 */
THEMENAME_preprocess_page(&$variables){
  // Requires browscap.ini, check PHP docs for details, else use $_SERVER['HTTP_USER_AGENT']
  $browser = get_browser();
  if($browser->browser == 'IE' && $browser->majorver == 7) {
    $variables['template_files'][] = 'page-ie7';
  }
}

After clearing all caches, you could then use page-ie7.tpl.php for IE7.

See the note on http://php.net/manual/en/function.get-browser.php for info else use $_SERVER['HTTP_USER_AGENT'] to check browser from request. You'll also need to make sure your cache varies on user agent as well.


How to Control Core Performance Cache Expire Time Of Day

Partial answer, but I typically handle exact scheduling and cron-but-not-cron tasks by using a custom script and calling it with wget in a crontab.  You can use cron.php for guidance on how to bootstrap, and then write your own function to clear what you want, then put it in crontab to run when you want.  Just remember to lock down the script in .htaccess or apache config.


Use hook_entity_bundle_field_info()

Copying from the api docs

function mymodule_entity_bundle_field_info(\Drupal\Core\Entity\EntityTypeInterface $entity_type, $bundle, array $base_field_definitions) {
  // Add a property only to nodes of the 'article' bundle.
  if ($entity_type->id() == 'node' && $bundle == 'article') {
    $fields = array();
    $fields['mymodule_text_more'] = BaseFieldDefinition::create('string')
      ->setLabel(t('More text'))
      ->setComputed(TRUE)
      ->setClass('\Drupal\mymodule\EntityComputedMoreText');
    return $fields;
  }
}


Configuration changes that will not import?

From what I can see this is a problem with how drush generates the temp files to compare against. It looks like drush is generating files with any comments removed as well as not adding qoutes around yaml strings that needs to be escaped.

+  # Set the node type to location
   type:
     plugin: default_value
     default_value: location
+  # set the location type to park
   field_location_type:
     plugin: default_value
     default_value:
       tid: 1
+  # Create the mappings from soap to drupal fields.
   title: abbreviatedName
   field_location_active_facilityid: ID
-  field_location_address/address_line1: address1
-  field_location_address/locality: city
-  field_location_address/administrative_area: state
-  field_location_address/postal_code: zipCode
-  field_location_address/country_code: country
-  field_location_parking_direction/format:
+  "field_location_address/address_line1": address1
+#  "field_location_address/address_line2": address2
+  "field_location_address/locality": city
+  "field_location_address/administrative_area": state
+  "field_location_address/postal_code": zipCode
+  "field_location_address/country_code": country
+#  "field_location_address/langcode":
+#    plugin: default_value
+#    default_value: en
+  "field_location_parking_direction/format":
     plugin: default_value
     default_value: basic_html
-  field_location_parking_direction/value: parkingCapacity
+  "field_location_parking_direction/value": parkingCapacity


Drush Make doesn't do anything (Windows)

I might be mistaken, but I think the YAML format for Makefiles is for Drush v.7 and later. I am using the "old" format with Drush v.6 (and Drupal 7), also on Windows

Might that work with the sample below?

; Drush Make API version
api = 2
; Drupal core
core = 7.x
projects[drupal][version] = 7.36

Hope it helps,


You've got to add these lines to your settings.php file to run memcache proper:

$conf['cache_backends'][] = 'sites/all/modules/memcache/memcache.inc';
$conf['cache_default_class'] = 'MemCacheDrupal';
$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';

If you're on top of a multisite installation also don't forget to add this one:

$conf['memcache_key_prefix'] = 'unique_key';

More information about configuration and setting memcache for drupal you can find here.


Better tagging / taxonomy reference widget

Select (or other) module looks like provide similar UI.

  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.

Unfortunately it doesn't support Term References.

Try Autocomplete Deluxe module or Chosen module for better UI and functionality.


Can't set PHP block visibility programatically

Re: https://api.drupal.org/api/drupal/modules!block!block.api.php/function/hook_block_info/7 you have to put the actual PHP code "in" the pages array key...

  For BLOCK_VISIBILITY_PHP, the PHP code's return value should be TRUE if
  the block is to be made visible or FALSE if the block should not be
  visible.

...not set it to the return of a function, eg, something along these lines:

$blocks['membership_package_information'] = array(
    'info' => "Membership Package Information",
    'visibility' => BLOCK_VISIBILITY_PHP,
    'pages' => '<?php return membership_block_visibility(); ?>' // ADDITION: you need the <?php ?> brackets :)
);

// make sure this function is in a module file that is always loaded...

function membership_block_visibility() {
  if(arg(0) == 'checkout' && arg(2) == null) {
    return true;
  }
  else {
    return false;
  }
}

Do also note the caveat off the api page:

  Most modules do not provide an initial value for 'visibility' or
  'pages', and any value provided can be modified by a user on the block
  configuration screen.


Images not displaying on site (or in view source) after uploading them with ckeditor

The text format needs to allow <img> tags, otherwise they will be stripped out by default.

For example, add <img> to the allowed tags here:

admin/config/content/formats/filtered_html > "Limit allowed HTML tags"

Alternatively, try the "Full HTML" text format, if available and applicable as it will allow images by default.


How to break up user roles checkboxes into groups?

One way to do this would be to use some JS to add a header element in front of the role that starts the group.  Each role has a unique id, e.g. input#edit-roles-2.  You could use some jQuery like:

$("input#edit-roles-2").before("
My Group
");

You would have to order the roles the way you want and find the right ids.

Also, this will probably require using a custom admin theme or a module in order to inject the JS since user editing generally uses that theme and not the main theme.


How to list entities and sort them by delta?

I think you're overcomplicating things here. From my reading, you really should be creating your view to:
Show content of type: Railway
This will be your "grouping". You don't want to using the Views grouping option here - that option is more useful when you want to group the result content by a field on each result, i.e. if your stations node type had a reference to Railways.
Fields to Display: Title, field_stations (or, preferable imo, configure a view mode for the Railway node that displays the fields you want to show).
Since we have a view of Railways, your results are naturally "grouped" by Railway. If you just display the stations field from the railway, you'll get the stations listed in the order on the field (its delta).
(optional) Contextual Filter: field_stations
I'm not sure if you actually need this from your description. You can configure a contextual filter for the field_stations field to allow you to show only the Railways (and their stations) if a Railway references a station you pass as an argument.


How do i use hook_menu to add a menu item into an exisiting menu

If this is your real code, then you're missing the return $items; line at the end, looks good otherwise :)

Edit: You are using 'type' => MENU_SUGGESTED_ITEM which means that the menu item needs to be enabled manually in the administration. And when you do, it will show as a sub menu item of /user/%user, which basically means it is invisible because there the default secondary menu position only displays top-level menu items. Try MENU_LOCAL_TASK instead to have it show up as a local task.

P.S.: permission strings are usually all lowercase (they are a technical identifier, not a user facing label or so).


Handle database connection exception via custom handler

To handle the logging for a specific exception implement an exception subscriber with a priority higher than 50, so that it runs before Drupal\Core\EventSubscriber\ExceptionLoggingSubscriber:

src/EventSubscriber/ExampleExceptionSubscriber

namespace Drupal\mymodule\EventSubscriber;

use Drupal\Core\Database\DatabaseAccessDeniedException;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;

/**
 * Example for catching a DatabaseAccessDeniedException
 */
class ExampleExceptionSubscriber implements EventSubscriberInterface {

  /**
   * @var \Drupal\Core\Logger\LoggerChannelFactoryInterface
   */
  protected $logger;

  public function __construct(LoggerChannelFactoryInterface $logger) {
    $this->logger = $logger;
  }

  public function onException(GetResponseForExceptionEvent $event) {
    $exception = $event->getException();
    if ($exception instanceof DatabaseAccessDeniedException) {
      $this->logger->get('php')->error('Custom logging message');
      $response = new Response('Custom error message', 500);
      $event->setResponse($response);
    }
  }

  public static function getSubscribedEvents() {
    $events[KernelEvents::EXCEPTION][] = ['onException', 60];
    return $events;
  }
}

mymodule.services.yml

services:
  mymodule.exception.subscriber:
    class: Drupal\mymodule\EventSubscriber\ExampleExceptionSubscriber
    arguments: ['@logger.factory']
    tags:
      - { name: event_subscriber }

If you don't set a response this subscriber only logs the error and the response is set by a subscriber with a lower priority. In this case you get two log entries, one from your subscriber and one from ExceptionLoggingSubscriber, because the dispatcher runs the event subscribers until one returns a response. Logging does not stop this.

Another option would be to extend ExceptionLoggingSubscriber, put the custom code in ExceptionLoggingSubscriber::onException and call the parent method to run standard logging when your custom code doesn't apply. Instead of putting the service in mymodule.services.yml you need to swap the existing service in the container then, see https://www.drupal.org/docs/8/api/services-and-dependency-injection/altering-existing-services-providing-dynamic-services

You find more infos about exception handling here How do handle exceptions?


How can I let anonymous users comment only once?

You can do this by means of two functions called flood_register_event() and
 flood_is_allowed().

When a anon user views a node, call flood_is_allowed in hook_node_view that sets COMMENT_NODE_CLOSED for the node.

When a anon user comments, register that as a flood event in hook_comment_presave for that particular node. By setting the $threshold (parameter for flood_is_allowed) to 1, the user will be stopped from commenting after the first comment is posted.

This is the bare bones of how to implement hooks that make use of these functions:

function MYMODULE_comment_presave($comment) {
  global $user;
  if (!$user->uid) {
    flood_register_event($comment->nid);
  }
}
function MYMODULE_node_view($node, $view_mode, $langcode) {
  global $user;
  if (!$user->uid && !flood_is_allowed($node->nid, 1)) {
    // This bars the anon user from posting a second comment of the node.
    // For a more sophisticated blocking method (e.g. to prevent the comment form from
    // showing up), ask another question about how to do that.
    $node->comment = COMMENT_NODE_CLOSED;
  }
}

PS: The module Anonymous Publishing is already using this pair of functions to limit the number of comments an anonymous user can post (but not exactly in the way you specify).  However, looking at the source code of that module should give you an idea about how to use this pair of functions for flood control of anonymous comments.


Disable (or workaround) form rebuild with managed_file field

This was happening due to the Clientside Validation module being enabled.

For anyone having this issue, I had to override the form settings in Clientside Validation for this particular form, setting "Validate fields on submit" to "No".


How to have a language switcher that allows you to select the country and then the langauge within the country?

Check Language Switcher module or Language Switcher Dropdown module.

But as of now there is no contrib module that does exactly as you wanted.


Got it!

if ($node = menu_get_object()) {
    $tabs = menu_local_tabs();
}


List all the taxonomy terms in a particular vocabulary in Drupal 6.

You can use taxonomy_get_tree()

Parameters

$vid: Which vocabulary to generate the tree for.

$parent: The term ID under which to generate the tree. If 0, generate the tree for the entire vocabulary.

$depth: Internal use only. Now deprecated and isn't used. It is left here only because of compatibility issues.

$max_depth: The number of levels of the tree to return. Leave NULL to return all levels.

API here


Cloning / Copying value of multi-value field

Consider using Entity References and not a complex compound field like your using now.

By using references you can use either the Inline Entity Form or the References Dialog modules to provide a more streamlined UI for adding new events from new popup windows. I was hoping you could reference exisitng events through a search using these modules (you can) but it won't clone the reference directly.

BUT, you could use the Replicate module, to replicated the entity reference you've selected to then edit it -- using custom code.

An example way to replicate a referenced entity can be seen in this replicate issue, as shown below:

/**
 * Replicate entities that are the target of entityreference fields
 *
 * Implements hook_replicate_field_FIELD_TYPE
 *
 * For entites that have one or more entity reference fields we need to replicate the
 * referenced entities as well so the cloned parents don't all point to the same children.
 * We also need to update the entityreference fields to point to them.
 *
 * @param object $replica
 *   Reference to the fully loaded entity object being saved (the clone) that
 *   can be altered as needed.
 * @param string $entity_type
 *   Type of the entity containing the field.
 * @param string $field_name
 *   Name of the field that is going to be processed.
 *
 * @see replicate_clone_entity()
 */

function MY_MODULE_replicate_field_entityreference(&$replica, $entity_type, $field_name) {

  // Only replicate entity reference field you are interested in
  if ($field_name == 'field_MY_ENTITYREFERENCE_FIELD') {

    // Wrap the replicated entity.
    $wrapper = entity_metadata_wrapper($entity_type, $replica);

    // Loop over the field values
    foreach ($wrapper->$field_name as $delta => $referenced_field_item_wrapper) {
      $referenced_entity = $referenced_field_item_wrapper->value();

      // Replicate the referenced entity and get the new id
      $replicated_referenced_entity_id = replicate_entity('node', $referenced_entity);

      // Give the replica reference field the new target id
      $replica->{$field_name}[LANGUAGE_NONE][$delta]['target_id'] = $replicated_referenced_entity_id;
    }
  }
}

So I'm saying Replicate and 1 of the many "dialog" modules could help make what you want to create more pretty. You could probably use the Replicate API and a custom button in your own form too -- if you want to do even more learning ... :)


Where are .po translations supposed to go?

Be sure the directory sites/default is writable, so that during installation the translation files can be copied to the translations directory at sites/default/files/translations


How to clone any standard webform element

The WebformElement plugin acts as a wrapper around a Drupal Form element plugin.  Therefore to actually create a webform element you need to define a Form element plugin with a corresponding Webform element plugin.

If you want to extend the Email element you need to extend the below classes

\Drupal\Core\Render\Element\Email
\Drupal\webform\Plugin\WebformElement\Email

All you might missing is a \Drupal\custom_module\Element\CustomModuleEmail class which probably will look something like...

<?php

namespace Drupal\custom_module\Element;

use Drupal\Core\Render\Element\Email;

/**
 * @FormElement("custom_moduel_email")
 */
class CustomModuleEmail extends Email { }


Yupp, simply download the Waypoints library, extract and rename the folder to just waypoints, then put it into themes/custom/MYTHEME/libs or into modules/custom/MYMODULE/libs and follow one of the following instructions:

Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme

Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module

Basically all you have to do is to create the corresponding MYTHEME/MYMODULE.libraries.yml file

waypoints:
  js:
    libs/waypoints/lib/jquery.waypoints.min.js: {}
  dependencies:
    - core/jquery

and then attach the library to all pages via hook_page_attachments() or hook_page_attachments_alter() inside the MYTHEME.theme or MYMODULE.module file.

<?php

function MYTHEME/MYMODULE_page_attachments_alter(&$attachments) {
  $attachments['#attached']['library'][] = 'MYTHEME-or-MYMODULE/waypoints';
}


create and save data to a file in the files folder from cron

I just need a simple example where a cron hook saves a simple file to a directory inside the files folder.

That would be literally as simple as:

function MYMODULE_cron() {
  $path = 'public://foo/bar/';

  if (file_prepare_directory($path, FILE_CREATE_DIRECTORY)) {
    $content = function_to_generate_content();
    file_put_contents($path . 'baz.ext', $content);
  }
  else {
    // Log an error
  }
}


How to alter the visibility of a menu tab for a page created in Views?

I created a mini module called helper.

In helper.info I put

name = "Helper"
description = "Provides custom support functions."
core = "7.x"

First we need to get the helper_menu_alter() to be called after views_menu_alter so we use hook_module_implements_alter to pull the value of our module in the array and put it back in which will always be done at the end of the array.

<?php

function helper_menu_alter(&$items){
  $items['user/%/workbench']['access callback'] = 'helper_access';
  $items['user/%/workbench']['access arguments'] = array(1);
  $items['user/%/workbench/drafts']['access callback'] = 'helper_access';
  $items['user/%/workbench/drafts']['access arguments'] = array(1);
  $items['user/%/workbench/needs-review']['access callback'] = 'helper_access';
  $items['user/%/workbench/needs-review']['access arguments'] = array(1);
}

/**
 * Helper access callback.
 */
function helper_access($uid) {
  if ($uid) {
    if ($GLOBALS['user']->uid == $uid || user_access('view all unpublished content')) {
      return TRUE;
    }
  }
  return FALSE;
}

function helper_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'menu_alter') {
    // Move helper_menu_alter() to the end of the list. module_implements()
    // iterates through $implementations with a foreach loop which PHP iterates
    // in the order that the items were added, so to move an item to the end of
    // the array, we remove it and then add it.
    $group = $implementations['helper'];
    unset($implementations['helper']);
    $implementations['helper'] = $group;
  }
}