Adding multiple users to a field using user/autocomplete I have the following code to add a field to my custom module to add in users. But I can only add in one user using the user/autocomplete feature.

$form['usershare'] = array(
  '#title' => t('Share Collection with:'),
  '#type' => 'textfield',
  '#autocomplete_path' => 'user/autocomplete'
);

How do I enable multiple users? These users should be separated by a comma on the back end for me to process it.

as @Geat said:

Your form should be like below.

    $form['usershare'] = array(
      '#title' => t('Share Collection with:'),
      '#type' => 'textfield',
      '#autocomplete_path' => 'user/autocomplete',
      '#multiple' => TRUE,
    );

    // Implemenbts hook_menu() for user/autocomplete path.
    function module_name_menu() {
      $items['user/autocomplete'] = array(
        'page callback' => '_user_autocomplete',
        'access arguments' => array('access user autocomplete'),
        'type' => MENU_CALLBACK
      );
      return $items;
    }

    // Implements callback function to get users in autocomplete with comma seperated
    function _user_autocomplete($string) {
      if ($string) {
        $items = array_map('trim', explode(',', $string));
        $last_item = array_pop($items);
        $prefix = implode(', ', $items);
        $result = db_select('users')->fields('users', array('name'))->condition('name', '%' . db_like($last_item) . '%', 'LIKE')->range(0, 10)->execute();
        foreach ($result as $user) {
          $value = !empty($prefix) ? $prefix . ', ' . $user->name : $user->name;
          $matches[$value] = check_plain($value);
        }
      }
    // return output in JSON format.
    drupal_json_output($matches);
}


How to display a block only for an article with a specific node id? I have quickly seen view reference and context module. Though they can display a view or block to a specific content type, I'm not sure if they can do it within a specific node.

As an example: I want to display a block only for an article with node id 3.

Can that be done?

I would steer clear of using PHP for block visibility.  If you type something wrong you can break any number of things.

Just go to your block settings, and take a look at the vertical tabs at the bottom of the page.  The first option is Pages.  Just change the radio button to "Only the listed pages" and enter node/3 in the box.

EDIT

If you use the Views Reference module mentioned in your question, then you can quite easily embed a Views block as one of your fields just as any other field.  The field itself can't be exclusive to a node ID, only an entity type.  However, you could just leave it blank for the other entities of the same type and use Field Permissions if you are worried about other people using the field incorrectly/at all.

One unrelated helpful hint with Views Reference - I generally tag my "reference-able" views with the same tag (i.e. Embeddable, Referenceable e.t.c.).  then you can easily select which Views to make available to the Views Reference field.

You MIGHT be able to embed blocks with Entity Reference combined with BEAN or Boxes, but I'm not 100% sure.  Failing this you are probably looking at breaking up the entire $content variable in the template and embedding it yourself (which would mean much more maintenance if fields get added or removed), using Views and turning the whole content types into blocks that can be positioned (MUCH effort).


Is it possible to pass parameters in a taxonomy term's aliased URL using clean URLs? I am trying to pass URL parameters and access them in a preprocess function. I have done a fair amount of research but did not find an answer. It works if I do the following /example?id=1, but that's quite ugly and non-SEO friendly. Clean URLs is much better.

Is it possible to pass parameters in a taxonomy term's aliased URL using clean URLs?

Yes, the arg() function can do this.

https://api.drupal.org/api/drupal/includes%21path.inc/function/arg/6.x

At the end of Drupal's .htaccess file, you can see how Drupal makes those URLs work by rewriting them to ?q= if they are not real files or directories. Without this, they would cause a 404 too.

In http://api.drupal.org/api/function/arg/6 you can see how it handles them.


Where are contact form entries stored? I am aware that Webform is now out of the Window and has more or less been replaced by Core Contact Forms. I created a form and it works great. Only problem is, I can't for the life of me find out:

If it stores a copy of the submitted form locally?
Where it stores it if it does?
Or if it does not store it, how to allow it to be stored?

Like webforms, I want to click somewhere and see "Show all submissions". But no idea where?

I don't know if it really stores them anywhere by default, but I think that this module wouldn't exist if it does store them. Check it out.


Warning: array_flip(): Can only flip STRING and INTEGER values! I have a custom module that hooks into a commerce extension module.

The function splits a payment for a product and splits it to beneficiaries who helped create the product.

I use user_referance module in a field collection field in the product content type to store the beneficiary users from the system. The drupal system log shows this when running through the function

Warning: array_flip(): Can only flip STRING and INTEGER values! in      EntityAPIController->load() (line 219 of /www/opigno/profiles/opigno_lms/modules/contrib/entity/includes/entity.controller.inc).

Drupals error back trace function showed the error came from this line

  if (!empty($item_id)){
      $split_pay = commerce_funds_object_to_array(entity_load('field_collection_item',
array($item_id)));
  }

The function does run through fine but I'd like to squash any bugs that are appearing, the $item_id array only contains the user_ids of beneficiary users so i don't really understand why a non integer value is being passed

I had a similar issue, you just have to be sure it is an integer and not a string, also you can use entity_load_single:

if (!empty($item_id)){
$item_id = (int) $item_id;
  $split_pay = commerce_funds_object_to_array(entity_load_single('field_collection_item', $item_id));
}


Views Sort Criteria: Contextual Filter Multiple Value Order I have a view that pulls in a collection of nodes via node id.  I'm using the Node:Nid filter, and have it set to allow multiple inputs separated by the '+' sign. (443+112+2060...)  This part works beautifully.

I was wondering if I could sort the view by the order of the nids?  I thought it might do this by default if I remove all sort criteria, but no joy. I'm looking and I don't see a way to sort the view by this data.

Any advice you might be able to give me would be greatly appreciated.

Drupal 7. Views 7.x-3.x-dev.

I guess some other people had the same idea I had.

The Views Arguments Extras module handles my situation perfectly. I used the version for 7 (duh :) ), but there is a drupal 6 version as well.


The following SSH command responded with a non-zero exit status (drupal-vm) My environment:

Vagrant 2.2.4
VirtualBox 6.0.6r130049
ansible 2.7.10
config file = None

Mac OS Mojave (10.14.4)

I use drupal-vm to build my local development environment.

I cloned this repo and run vagrant up. After first time vagrant up everything was fine and Drupal was installed correctly. Then I did vagrant halt, to stop my VM.

After I do vagrant up again I get this error:

==> drupalvm: [vagrant-hostsupdater] This operation requires administrative access. You may skip it by manually adding equivalent entries to the hosts file.
The following SSH command responded with a non-zero exit status.
Vagrant assumes that this means the command failed!

 setup

Stdout from the command:

Stderr from the command:

bash: line 5: setup: command not found

What do I have to do and what's wrong?

It seems to be related to a bug in VirtualBox 6.0.6. I downgraded to 6.0.4 and it now works.

Source: https://github.com/dotless-de/vagrant-vbguest/issues/278#issuecomment-486505824


Correct permission for site, default and files folders? I just need to know if these permission are corrects:

site --> 775
site/default -->775
site/default/files --> 775
site/default/setting.php --> 555

Actually the permissions should be

sites -> 755
sites/default -> 755
sites/default/files -> 775
sites/default/settings.php -> 444

See the top 3 answers to this question for some great details.


How do I set the node title as breadcrumb? How can I set the breadcrumbs for a node? I have a node which is in the menu and also the head menu with the id 2 which contains the imprint.

If I open my page http://my.page.tld/imprint (I'm using the SEO stuff) I can see my text with the correct title but with no useful breadcrumbs. It's Home instead of Home » Imprint.

How can I fix that?

You can use Menu Breadcrumb. It allows you to Append the page title to the breadcrumb (either as a clickable url or not) . Or you can edit your theme's page.tpl.php - simply add $title after the $breadcrumb variable.

There are also a ton of other breadcrumb modules if you want to get fancy:

Crumbs
Custom Breadcrumbs
Hansel

See an older comparison chart.


D8 to D8 migrate source plugin? Migrate Source

  The migration configuration entity always contains a source key. The
  value is an associative array containing the name of the plugin and
  the configuration of it. Only the plugin key-value pair is mandatory,
  some plugins might not have any configurations.

source:
  plugin: d6_node

Googling I see examples outhere that use d6_node and d7_node but what does one use to migrate nodes from d8 to d8?

Looking at the core/modules/node/src/Plugin/migrate/source folder there is no such thing as d8_node

The Drupal 8 migration module has been moved into core as explained in this issue. If you're using at least Drupal 8.6.x, you don't need to apply the patch.

Old answer:

I'm going out on a limb and say that currently there isn't one and it can only be done by creating a custom plugin.

Just found this Drupal 8 migration (source), thanks Berdir & Primsi.


How to create my own custom simple action in D8? I'm creating a view that is used to review migrated content that was flagged for review during the migration process. I want to provide a bulk action on this view that allows the user to select a bunch and mark them as "resolved".

I created a custom action to do this following some guidance from https://www.drupal.org/node/2330631:

config/install/pu_news_migrate.action.resolve_news_migration_flag.yml

langcode: en
status: true
dependencies:
  module:
    - node
id: resolve_news_migration_flag
label: 'Resolve news migration flag'
type: node
plugin: resolve_news_migration_flag
configuration: {  }

And created the action plugin implementation:

`src/Plugin/Action/ResolveNewsMigrationFlag.php

<?php

namespace Drupal\pu_news_migrate\Plugin\Action;

use Drupal\Core\Action\ActionBase;
use Drupal\Core\Session\AccountInterface;

/**
 * Removes the "needs review" flag on a migrated news article.
 *
 * @Action(
 *   id = "resolve_news_migration_flag",
 *   label = @Translation("Resolve news migration flag"),
 *   type = "node"
 * )
 */
class ResolveNewsMigrationFlag extends ActionBase {

  /**
   * {@inheritdoc}
   */
  public function execute($node = NULL) {
    if ($node) {
      /** @var \Drupal\node\NodeInterface $node */
      if (!$node->hasField('field_news_migration_review')) {
        throw new \RuntimeException("News migration field not found on node.");
      }
      $node->set('field_news_migration_review', FALSE);
      $node->save();
    }
  }

  /**
   * {@inheritdoc}
   */
  public function access($object, AccountInterface $account = NULL, $return_as_object = FALSE) {
    /** @var \Drupal\node\NodeInterface $object */
    $result = $object->field_news_migration_review->access('edit', $account, TRUE)
      ->andIf($object->access('update', $account, TRUE));

    return $return_as_object ? $result : $result->isAllowed();
  }

}

I also added a schema file: config/schema/pu_news_migrate.schema.yml:

action.configuration.resolve_news_migration_flag:
  type: resolve_news_migration_flag
  label: 'Remove the "needs review" flag from a migrated article.'

I uninstalled the module and re-installed it so that the action definition is loaded into Drupal's config.

However, when I view the list of actions I can select in views, it doesn't appear there. I enabled the "Actions" module which displays a list of all actions, and it does not appear there either.

What did I do wrong here?

Action plugin yaml definitions need to be prefixed with the name system.action.action_name.yml, and not mymodule.action_name.yml.

For reference, check the provided action plugins for node and user module in core in their config/install and config/schema folders.

Uninstall the module, rename the files, and install the module again so the changes are picked up. You should then see your custom action.

So:

config/install/system.action.resolve_news_migration_flag.yml


Bookings API versus existing spaghetti code I'm working on an appointment booking system that allows registered users to book an outcall with an agent.

I've only come across Bookings API and Public Bookings, which seems more for things like library work rooms than it is for service industry people -- and even then, nothing about it looks at all pretty (Not a knock to the devs; it just isn't at the point comparable software is at on other CMSes.). My client has an existent system coded in some pretty funky PHP -- nothing OO, all logic code is in the same file as the design code (which is in, get this -- tables. Everything. In tables.) -- and I'm currently thinking about porting it to Drupal.

My questions are thus:

a. Are there any alternatives to Bookings API for appointment booking?

b. If not -- and considering I don't have a ton of Drupal programming experience -- would it be more worthwhile to update the existing spaghetti code appointment booking system to function as a Drupal module, or more worthwhile to just make Bookings API function more eloquently in this usage case (considering it has a lot more functionality, hooks, etc. than I could probably program into a new module in a short time)?

Thank you!

In answer to part (a) there is the Resource Conflict module, which appears to be similar in goal to the modules you mention above.

As for part (b) I'd argue that it is typically better to update or replace custom spaghetti code in such a way to work with existing modules--doing so will greatly ease the work of future maintainers of your code, and allow it to benefit from future enhancements to the Bookings API.


How/where do I add $('#fullpage').fullpage() code? I want use the fullpage library. In my theme.libraries.yml file, I added theses lines.

fullPage:
  header: true
  js:
    js/fullPage.js/jquery.fullPage.js: {}
  dependencies:
    - core/jquery

jquery.js and jquery.fullPage.js are now present in the <head> tag,
but to run fullpage.js, I must execute [this additional script2.

$(document).ready(function() {
    $('#fullpage').fullpage();
});

How and where do I add this little script?

You need to create a javascript file in your theme and attach it to pages as shown in the documentation.
https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme

Make sure you theme library has a dependency on fullPage.


Inform user with account creation email, for existing users to Is there a way(It doesn't matter if passwords need to be recreated/generated) to send all the users an email about there account being added to the website after they are already added?

I'd be really interested in this idea too.  I'm making a website to contain and extend an existing registry and it would be great to set the whole thing up with all the members' details and then just send out a mass email containing each user's username and generated password when everything's put together...

I haven't tested it yet, but it could potentially be done:

Set up your users, ensuring 'Notify User' is unchecked and Status is 'Blocked'.  If you already have active users, block them (make sure no email goes out, check admin/config/people/accounts)
When you're ready to notify the users, go to admin/people and check all the blocked users, then user Bulk Options to Activate them (if there's a huge amount of users you might want to do a group at a time to save the server a bit...)
Individual emails should be sent out containing a 'one-time login', see admin/config/people/accounts and scroll down to E-mails and choose 'Account Activation' for the email which goes out.

I will give it a shot and let you know if it worked.


How can I add special classes to only all blocks that's generated in certain region? I want to add some classes to each block that generated in custom region automatically.
For example I want to all blocks that generated within sidebar-left have some special classes and in addition I don't want to those blocks in other regions have those classes.

I try to use something like below code to add desired class to each block that's generated in sidebar-left:

region--sidebar-left.html.twig

{%
  set classes = [
    'region',
    'region-' ~ region,
  ]
%}
{% if content %}
  <div{{ attributes.addClass(classes) }}>
    {{ content }}
  </div>
{% endif %}

But it seems there isn't any loop functionality Like below to I can use for each blocks and add my desired classes to them:

{% for item in items %}
  <div class="my-desired-class">
    {{ content }}
  </div>
{% endif %}

I am afraid this is no longer possible, according to Region-specific block templates are not available in Drupal 8.

  In Drupal 7 it was possible to specify separate block templates per
  region, such as block--header.tpl.php and block--footer.php to output
  different HTML for blocks placed in the header and footer regions. It
  was also possible to adjust variables based on region in
  hook_preprocess_block(). Both of these features have been removed.

  It is suggested you use standard CSS cascading selectors to style
  blocks differently on different parts of the page.

Therefore, you have 2 options:

1) In your page.html.twig you add a parent/wrapper class or id

{% if page.sidebar %}
    <div class="my-sidebar">
       {{ page.sidebar}}
    </div>
{% endif %}

Then in CSS use your parent/wrapper to style your blocks .my-sidebar .block { border: solid red; }

2) Individually create a block--block--[id].html.twig for each of your sidebar blocks and add my-desired-class here.


How to create a view with contextual filters and then make menus to filter it? I have created a content type that I want to list and filter on taxonomy terms.
For example I want to show all posts of that content type on the frontpage. Then I want to be able to create menu items with name of all the existing taxonomy terms I have to choose from. Then i want those terms to link to a page with the filtered content for only that term.

I can create this by making a new view for every taxonomy term but it must be a better way to do this since if I have around 40 terms it's gonna get really messy.

I managed to figure this out. With help from this tutorial http://www.metaltoad.com/blog/using-drupal-contextual-filters-views and the reason why the links in the menus dind't work for me were because I was using the same url as the taxonomy term had so I only got a term list. So I just changed the view url to something else than the taxonomy and it worked.

It now works if I write the view adress/any termreference without having to create a separate view for all of them.


Webform Message / Custom Module I'm trying to create a custom module which will display a message after my webform. I know that in order to display a message, I could use the following code:

$message = "Message here";
drupal_set_message(t($message));

But rather than having a specific message, I want to have a conditional message based on PHP if statements. E.g.,

    if($class == A) {
    print "Correct!";
}

So, my question is how can I get the results of this PHP code to display on my webform? I'm not familiar with PHP code, so I don't know if I can combine the $message code with the if statement somehow. (I've tried variations of this with no success.)

Thanks for your help.

One of the features and APIs of the Webform module for Drupal 8 that I personally enjoy using is support for inline messages using the WebformMessage element

The WebformMessage element supports dismissal messages and #states API.

Here is the YAML version of a Message element

message:
  '#type': webform_message
  '#message_type': warning
  '#message_close': true,
  '#message_storage': user,
  '#message_message': 'This message can be dismissed by a user'

Here is the PHP syntax, which can be used in your custom code.

$build['message'] = [
  '#type' => 'webform_message',
  '#message_id' => 'custom_message_id',
  '#message_type' => 'warning',
  '#message_close' => TRUE,
  '#message_storage' => WebformMessage::STORAGE_USER,
  '#message_message' => $this->t('This message can be dismissed by a user'),
];


Implementing Area 51 with Acquia Commons? I'm probably going to use Acquia Commons to put together a site for communities, and I understand that it's set up as installed to have administrators create the groups and subgroups. However, I'd like users to be able to petition for new groups (and subgroups?) to be created in a process something like Stack Exchange's own Area 51, though perhaps without the following phase.

How would I go about implementing that sort of thing on the current release of Commons? It's based on Drupal 6 until more modules are ported to D7.

Here's a simple solution:

Create a content type, say 'proposal', that any user can add for the petition group (with title as group name and body for reason).
Users can comment on nodes of that type so they can discuss the proposal.
Create a view to show nodes of type 'propsal' and enable filtering, sorting etc.
Use the Votingapi module and one of the voting widgets (like vote up/down) to allow people to vote on the node.

For the creation of the groups, you can either:

Do it manually, monitoring when a proposal gets a specified number of votes.
Use the Rules module to do it automatically.


Adding comments to a node via drush or commandline I'm trying to set up a server documentation system using drupal 7. Each server would have it's own page/ node. Updates or changes made to the system would be noted as comments on the servers page. What I'm looking to do is to be able to add a comment via drush or some other command line tool so that I can create an alias on each server to add a comment to that servers page.  I'm not a programmer so any help would be appreciated.

Expanding on Shawn Conn's answer, below is a Drush command that adds a comment to a Drupal 7 node.

Usage:

drush add-comment --uid=1 --subject='A comment' 'This is my awesome comment.'

Save the script below as add_comment.drush.inc, and place it in your $HOME/.drush directory.

<?php

/**
 * Implements hook_drush_command().
 */
function add_comment_drush_command() {
  $items = array();

  $items['add-comment'] = array(
    'description' => "Add a comment to a node.",
    // Describe the arguments for this command.  Delete
    // this seciton if command takes no arguments.
    'arguments' => array(
      'comment' => 'The comment to add.',
    ),
    // List all options used for this command. Only options that
    // are listed here (or that are global Drush options) may
    // be specified on the commnadline; all others raise an error.
    'options' => array(
      'nid' => array(
        'description' => 'The node id to add the comment to.',
        'example-value' => '3',
      ),
      'subject' => 'The comment subject. Defaults to empty.',
      'uid' => 'The user id of the user to post the comment as. Defaults to anonymous.',
    ),
    // Give one or more example commandline usages for this command
    'examples' => array(
      'drush add-comment --nid=123 "This is my great comment."' => 'Do something.',
    ),
    'aliases' => array('addc'),
  );

  return $items;
}

/**
 * Implements hook_drush_help().
 *
 * @param
 *   A string with the help section (prepend with 'drush:')
 *
 * @return
 *   A string with the help text for your command.
 */
function add_comment_drush_help($section) {
  switch ($section) {
    case 'drush:add-comment':
      return dt("Brief help for Drush command add-comment.");
    // The 'title' meta item is used to name a group of
    // commands in `drush help`.  If a title is not defined,
    // the default is "All commands in ___", with the
    // specific name of the commandfile (e.g. add-comment).
    // Command files with less than four commands will
    // be placed in the "Other commands" section, _unless_
    // they define a title.  It is therefore preferable
    // to not define a title unless the file defines a lot
    // of commands.
    case 'meta:add-comment:title':
      return dt("add-comment commands");
    // The 'summary' meta item is displayed in `drush help --filter`,
    // and is used to give a general idea what the commands in this
    // command file do, and what they have in common.
    case 'meta:add-comment:summary':
      return dt("Summary of all commands in this command group.");
  }
}

/**
 * Implementation of drush_hook_COMMAND().
 *
 * Add a comment to a node.
 */
function drush_add_comment($comment) {
  $nid = drush_get_option('nid');
  $uid = drush_get_option('uid', 0);
  $subject = drush_get_option('subject', '');

  $comment = (object) array(
    'nid' => $nid,
    'cid' => 0,
    'pid' => 0,
    'uid' => $uid,
    'mail' => '',
    'is_anonymous' => ($uid == 0),
    'homepage' => '',
    'status' => COMMENT_PUBLISHED,
    'subject' => $subject,
    'language' => LANGUAGE_NONE,
    'comment_body' => array(
      LANGUAGE_NONE => array(
        0 => array (
          'value' => $comment,
          'format' => 'filtered_html'
        )
      )
    ),
  );

  comment_submit($comment);
  comment_save($comment);
}


8 - How to open node preview in a new tab I'm trying to get the preview button to always open in a new tab. Are there any "clean" or "correct" ways of doing this? Currently I feel like I would need to hack core to achieve the job.

I was able to create a simple hack with jQuery that works better than I expected. I would prefer to handle it in php though. What I did was when the user hovers over the preview button I manually add and remove the target attribute to the form.

jQuery('#edit-preview').on('mouseover', function(e){
  jQuery('.node-form').attr('target', '_blank');
});
jQuery('#edit-preview').on('mouseout', function(e){
  jQuery('.node-form').removeAttr('target');
});
jQuery('#edit-preview').on('click', function(e){
  jQuery('.node-form').attr('data-drupal-form-submit-last', '');
});

The last part, allows the form to be submitted after launching the preview.  Otherwise, it thinks you are hitting the submit button twice.


More information than standard "Site Details", also to be available as tokens Is there a way to add additional fields to the config/system/site-information area such as business owner, "business location", "hours of operation", "phone number", etc. I would then like to be able to use that information throughout nodes and blocks as tokens.

That way if the details change, they will change throughout the site. This is particularly handy when using token filter for document templates on uses for multiple sites, like privacy statements.

Is this possible, or is there another way to add this functionality?

I wrote a tutorial on most of this: http://www.jaypan.com/tutorial/drupal-8-extending-core-configuration-extending-core-forms-and-overriding-core-routes

I didn't get into creating tokens for the new items, but you can do it by implementing hook_token_info_alter() and declaring the new tokens as part of the site tokens, and implementing hook_tokens_alter() to set the values from the config you create following the tutorial.


Switch theme by content type My company has just purchased a Drupal theme to apply to some new pages they want to add to an existing site. This theme is different to the existing theme of the site.

They want to create a new content type which will work with the new theme and not affect any of the existing pages using the default theme. So basically we want to switches themes based on what the content type of the page is. They also want the freedom to create any URL they choose so using a multi-site configuration is out of the question.

I've seen a number of posts on the internet showing this is possible in Drupal 7. Is this possible in Drupal 8 and how can I make it work?

In Drupal 7, it was straight forward possible by implementing hook_custom_theme() in your custom module.

As for Drupal 8, you will need to create a ThemeNegotiator. Link to the respective change record : 'theme callback' and hook_custom_theme() replaced by theme negotiators.

In the applies() function of the class you can apply your logic and return the theme you wish to have in the determineActiveTheme() function.

Note that, you might have to create multiple ThemeNegotiators for multiple conditions.


Creating Email Sending Rules in WebForm in Drupal 7 Is it possible to create rules for sending automated emails within WebForm?

Some of the examples include (all emails are separate):-

Send an email to user if he left a field to come back and fill it later.
Send an email if he left certain part of the form.
Send an email if a field is updated (or not updated).

Many Thanks.

See webform_rules:

  Did you ever want to react on webform submission using rules but
  couldn't find the proper event? Webform Rules makes it possible to
  catch webform submissions by rules and do whatever you'd like to do
  with it (meaning: do whatever rules let you do with it).

It should let you perform most of the logic you've outlined here.


notify after event in followed node by follower I use the Flag module in Drupal 7, and created a flag (for nodes) with  "follow" as name of the flag.

I want to add new event on the followed content by user, send notify for follower by php code or display counter of new event unread to user.

How can I do this?

If i understand you right, you want to do something after a user was flagged...

The flag module has a full Rules module integration.
This module gives you the ability to react to specific events (like flagging a user) and do actions like showing a message, sending a email, or execute some custom php-code.


Tokens causing incorrect text substitutions I'm running Drupal 7 on Ubuntu 14.04 server, core and all modules up to date as of today (7th May). We have noticed today that zeros (0) are not displaying correctly in blocks that have a custom token. They are being substituted for the word 'custom'.

For example, "7,500" displays as "7,5customcustom".

I'm not sure how long it has been doing this, as we have only just noticed it today. In blocks without Custom Tokens, the zeros display correctly. This is a relatively recent issue, as it was not a problem a couple of months ago when our site was reviewed by our solicitors.

The source for the content is correct - so it appears to be a display issue. Any ideas?

As an aside, the zeros being replaced need not be in the Custom Token to be replaced (it happens whether they are part of the Custom Token, and when they are just plain text on the page).

It appears to me that the explanation for your issue might be because of any of the following reasons

Reason 1:

It could be related to what is described in  https://www.drupal.org/node/390482, which states:

  The tokens available depends on what modules you have enabled on your Drupal site.

So could it be that you (accidently) disabled a module recently, which was actually the module related to the token that you now have an issue with?

Also, some more related considerations, based on what I read at comment #3 in the issue queue on D.O:

What does that "00" in the "7,500" actually refer to? I want to better understand which module(s) are related to it.
What result do you get if you (temporary) enable all of your currently disabled modules? FYI: if you only enabled the module that is causing this issue, and not uninstalled it, the problem might be resolved, at least for now. And then you can think of how to best resolved it permanently.

Reason 2:

When you define a custom token, for "Text format" (under the "Content" box): verify what the text format is you use there. And also verify what the text format is of where you are trying to USE that custom token (as in the original question: in the block), or in your Webform, Email etc.

Because maybe something is wrong in the way you're using/mixing text formats. Refer to How to use the Custom Tokens module, especially to this part of it (bold markup added here):

  note that "Custom Token" sends what you put in the "Content" box to the page. It doesn't evaluate it first and then send it. Therefore, if your custom tokens include other tokens and/or PHP code, then the "Body" box in which you place your tokens must use the same text format that you used to define them, so that the other tokens and/or PHP get evaluated.

The question here might be a minor variation of the scenario described in that community page ...

Other reasons worth verifying:

Maybe the field "type" got changed somehow, and that is what's causing it?
Something similar within the content type settings?
Could it be related to something about some missing "permissions" (for those cases where there is this issue)?

Curious to hear if either of these 2 reasons are actually also a solution for what this question is about.


Batch operation doesn't get called I am trying to write a batch. And I have a problem that none of the batch operations callback functions are getting called.

I wrote drupal_set_message at the start of each callback and none of the messages are displayed.

I can get the batch page, but the callback ops aren't called at all.

Here's the code I used:

function mymdoule_node_batch()
{
    $batch = array(
        'title'         => t("Migrating"),
        'operations'    => array(
            array('mycallback_001'),
            array('mycallback_002'),
        ),
        'finished'      => 'mycallback_finished',
        'init_message'  => t('Initializing...'),
        'error_message' => t('An error occurred.'),
    );

    batch_set($batch);
    drupal_set_message("step: 0"); // this is the only message the system returns
}

function mycallback_001(&$context)
{
    drupal_set_message("step: 1");
    $nids = db_select("node", "n")
            ->fields("n", array("nid"))
            ->orderBy("nid", "ASC")
            ->execute()
            ->fetchCol();
}

function mycallback_002(&$context)
{
    drupal_set_message("step: 2");
    $nids = db_select("node", "n")
            ->fields("n", array("nid"))
            ->orderBy("nid", "ASC")
            ->execute()
            ->fetchCol();
}

P.s. The batch is getting called in form submission.

What's wrong in that?

It worked after I added file to the $batch array.

function mymdoule_node_batch()
{
    $batch = array(
        'title'         => t("Migrating"),
        'operations'    => array(
            array('mycallback_001'),
            array('mycallback_002'),
        ),
        'finished'      => 'mycallback_finished',
        'init_message'  => t('Initializing...'),
        'error_message' => t('An error occurred.'),
        'file'          => 'mypatch.ops.inc',
    );

    batch_set($batch);
    drupal_set_message("step: 0");
}


How do I make link act like a view or a view look like a link? Good morning!

I want to create a link that displays a node, the most recently created for example. What is the best way to do that in Drupal?

I have a menu link that does what I want with:
moneymap/Pro/EURUSD/Day?sort_by=field_map_id_value&sort_order=DESC
but I don't know how that works or how to make that work in an HTML link.

I've made a few views but still a beginner? How should I proceed?

Thanks!

Easiest way to achieve above is using Views
Create a new view with block view

Sort Content by Post Date
Select fields as Content Display and show only one item
Enable the block by Navigating to blocks list page "admin/structure/block"

Please find the view code which you can simply import using "admin/structure/views/import"

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

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Latest Node';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '1';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block');


How can I pass variables from views template to node template? I have a view of contents of a content type. This content type has fields which references entities of another content type (and that in turn references another set of entities of yet another content type).

I am trying to iterate through this view with twig templates.

If I choose to show contents for my format, I can easily access the referenced entities and its fields. My quandary is however, I cannot track what row.content row/index I am in.

If I switch to show fields, I can use the global view results count and I have an effective counter.  However, I cannot seem to be able to access the referenced entities to get the values of the fields.

So far I have not found anything thru searching the net that actually addresses this particular problem.

I am using the views-view-unformatted template which in turn calls the node--view template. I am unable to 'pass' along the row index from the unformatted views template to node view template.

I already know that this is doable when using fields, but fields is out of the question because of the inability to access referenced entities.

Now there are two possible solutions to this issue:

Show content and somehow track the row.content index between twig templates.
Show fields and be able to actually access the fields of referenced entities.

Anyone have any suggestions?  Thank you.

Possibly use devel and kint modules.

Once both modules are enabled add {{ kint(fields) }} or {{ kint(content) }} to see what your options are for displaying your view's data. If the view wrks successfully then you should be able to display it using twig e.g. if you find field_name in kint and it output's the correct data then add <p>{{ fields.field_name }}</p> to your template


Creating a userlist in Views (including custom user fields) I've encountered an issue using Views 3 in Drupal 7.
I want to create a user list with a bunch of fields I added to the user profile (using Drupal's core user fields). I need a list of all users, and right now I keep getting the currently created content and its author (with the appropriate user fields). Not all users have created content.

I've created a relationship "Content: Author" to get access to the custom user fields, but that's not the reason I keep getting the content with its author. I get the same result when I remove the relationship and custom user fields.

In Drupal 6 with views2 I made the same page and had no issues. Could this perhaps be a bug in Views 3, or am I missing something?

Your question makes it sound like you've created a node view, listing content. If you create a view listing users, you should be able to accomplish what you're trying here.


How to perform bulk operations on a view when the view is displayed but without the need to select rows? I would like to execute certain Rules based bulk operations on a view (using the VBO module). But not the way they are normally done when using VBO, i.e selecting the rows in the view and then clicking the operation to execute.

Instead I want VBOs to get executed when the view page is displayed. So that I dont need to select the rows and execute VBO operations on them.

Any suggestions?

To "trigger the execution of certain Rules when visiting the view page" (as in your question), is something you can do by using a special feature of the Rules module, i.e. a technique that is similar to what is described in the answer to "How to execute VBO list of nodes in Rules on After updating an existing user account event?". Read on for more details about the steps to be completed, specific to your question here.

Create a custom Rules that will execute the VBO list that you already have, and which looks similar to this example (which was used to process a VBO view of unread messages, with a path like user/%/messages/unread):

{ "rules_mark_all_unread_messages_read" : {
    "LABEL" : "Mark all unread messages read",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "views_bulk_operations" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:url" ],
          "match" : "user\/\\d+\/messages\/unread",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [
      { "views_bulk_operations_action_load_list" : {
          "USING" : { "view" : "messages_by_user|page_3" },
          "PROVIDE" : { "entity_list" : { "unread_msgs_list" : "A list of unread messages" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "unread-msgs-list" ] },
          "ITEM" : { "current_msg" : "Current message" },
          "DO" : [
            { "component_rules_flag_a_message" : { "message_to_flag" : [ "current-msg" ] } },
            { "drupal_message" : { "message" : "The message with ID [current-msg:mid] (created [current-msg:timestamp]) was marked as read." } }
          ]
        }
      }
    ]
  }
}

Some more details about the rule above:

Rules Event: Drupal is initializing
Rules Condition: Check if the path being visited is user/%/messages/unread (adapt this path to use your path).
Rules Actions:

Create a list of unflagged messages (replace this list by your VBO list).
Loop over each of the unflagged messages found, and flag those messages (replace this action by the "execution of certain rules", as in your question).

This rule also performs an extra "set message" action, so that you can see what it does if you want to try it in your own site (it shows a message for each entry in the list). Remove that message after QA-testing if you want.

That's it, works like a charm!


hook_form_alter doesn't load load my form_id I'm trying to hide a CCK field in my node-edit form. I followed this tutorial:

http://dominiquedecooman.com/blog/drupal-how-disable-form-element-cck-form-using-form-alter

but i'm stucked at the implementing hook_form_alter function, it seems that this hook doesn't recognize my form, i've tried this:

function video_tutorial_form_alter(&$form, &$form_state, $form_id) {
  print_r($form_id);
}

but it only prints "search_block_form search_theme_form";

You have 3 options if you wish to hide a form item:

Use .css and make your life simple using display:none;
create a custom module (see below)
Why even have the cck field if you are going to hide it? What's the point of that?

Please note that the above tutorial DISABLES the field and does not HIDE it. Disabled fields can not be edited, but they are still displayed!

To point 2:
Is this function in your themes template.php? If yes, I presume your theme is called 'video_tutorial', if not, you should rename your function so it is THEMENAME_form_alter.

However, since you're using the edit node form it will actually be using the admin theme, not your front end theme - unless you have changed permissions for certain usergroups not to be able to access the admin theme or you are using the front end theme as your admin theme (unlikely) -, so you're better off creating your own module to override the form rather than using the themes template.php file:

How to create your custom module:

Create a folder, call it whatever you like - but it should make sense - eg:

custom_admin_overrides

In it, create two blank text files:

custom_admin_overrides.info
custom_admin_overrides.module

Open custom_admin_overrides.info and add the basics so drupal can see your module:

name = Custom Admin Overrides
description = Custom Module that provides Admin Area Overrides
package = Custom
core = 7.x

Save the .info file and add the following to your custom_admin_overrides.module file:

<?php
function custom_admin_overrides_form_alter(&$form, $form_state, $form_id) {
 if($form_id == 'YOUR_FORM_ID') {
  $form['FIELD_NAME']['#disabled'] = TRUE;
 }
 // YOU CAN UNCOMMENT THE BELOW FOR EXTRA HELPFUL DETAILS
 // GET FORM ID UNCOMMENT BELOW
 drupal_set_message("YOUR_FORM_ID is : " . $form_id);
 // GET ALL FORM ELEMENTS UNCOMMENT BELOW
 // drupal_set_message(dprint_r($form, TRUE));
}

Note that we aren't closing the

Save and upload the folder to your site/all/modules/custom/ folder.

Now enable the module and from that point onwards you should see the form id's displayed on all admin pages in the drupal message box at the top.

Now go to your specific node create/edit page and make a note of the form id and the field name you wish to disable. Now reopen your custom_admin_overrides.module file and replace the values for

YOUR_FORM_ID

and

FIELD_NAME

Save and now your field should be uneditable. Uncomment the following line to stop displaying the form id's:

drupal_set_message("YOUR_FORM_ID is : " . $form_id);


Safe and elegant way to access nested entities via fields I've seen a variety of approaches to access entity values in the theming layer. The code below is just a simple example using magic methods. It assumes all values are set - if any part of that returns a NULL, then in my experience errors ensue.

$value = $node->field_paragraph
    ->entity->field_media
    ->entity->field_file
    ->entity->field_text->value;

There are methods like ->hasField and ->count() to check things, and i have a variety in my themes. I can get the job done but sometimes it feels ugly. I'm interested the coding patterns that devs use to safely and elegantly drill through entity references.

Suggestion, create a domain object that has the logic.

Normally these entities represent something that fits your business-domain.

E.g in your instance, the node might be an event.

So you might model a domain object called EventWrapper.

<?php

namespace Drupal\my_domain;
use Drupal\node\NodeInterface;
use Drupal\media\MediaInterface;
use Drupal\file\FileInterface;

class EventWrapper {
  protected $node;
  public static function fromNode(NodeInterface $node): EventWrapper {
    $instance = new static();
    $instance->node = $node;
    return $instance;
  }
  public function getMedia() : ?MediaInterface {
    if ($this->node->hasField('field_media') && !$this->node->get('field_media')->isEmpty()) {
      return $this->node->field_media->entity;
    }
    return NULL;
  }
  public function getMediaImage() : ?FileInterface {
    if (($media = this->getMedia()) && $media->hasField('field_file') && !$media->get('field_file')->isEmpty()) {
      return $media->field_file->entity;
    }
    return NULL;
  }
  public function getImageCaption(): ?string {
    if (($file = this->getMediaImage()) && $file->hasField('field_text') && !$file->get('field_text')->isEmpty()) {
      return $file->field_text->value;
    }
    return NULL;
  }
}

Then in your code:

<?php

$image_caption = EventWrapper::fromNode($node)->getImageCaption();


More template suggestion for views exposed form Using the debug function I have found only one template suggestion for view's exposed form:

form--views-exposed-form.html.twig

I need to make changes to particular view, but I dont have other default suggestions like:

form--views-exposed-form--view-name--display-name.tpl.php

Should I write a function like hook_views_exposed_form_alter()

create exposed form filters template following this naming standard:
views-exposed-form--{view-name}--{display-name}.html.twig

to get the view-name you can get from Backoffice (Structure > Views > search for your view > then get machine name and repalce the underscore with dash - see image bellow)

so we get this template:
views-exposed-form--media-gallery.html.twig
put your static HTML(we will replace in next step) there and clear cache you'll find the new tempalte.
if you want to print the exposed fitlers just put {{form} in your tempalte

  views-exposed-form--media-gallery.html.twig

{{form}}
but if you want to print each exposed fitler serpately follow this steps :    (Structure > Views> search for your view > Edit > click on filter name under the FILTER CRITERIA > scroll down and copy Filter identifier input value > go back to the template and print your exposed filter one by one  {{ form.$fitler name }}

  views-exposed-form--media-gallery.html.twig

{#1.print 1st exposed fitler form element + label #}
{{ form.field_thematiques_target_id }}

{#2.print 2nd form element + label #}
{{ form.field_type_media_value }}

{#3.include all other form elment ex submit button but to prevent
duplication remove other one #}
{{ form|without('field_thematiques_target_id','field_type_media_value') }}


What is the twig template name for a node edit form? In Drupal 8, what is the twig template name for a node edit form for a custom content type called for example "device".

For a default node we use node-edit-form.html.twig
So what is the edit template name for a custom content type ?

I would appreciate your help.
Thank you !

You could have a look at this comment. It suggests adding a theme suggestion like this:

  This feels hacky, but it's the best I can come up with. First add this
  code to your admin .theme file (likely a sub-theme of Seven):

function NAMEOFTHEME_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {
   if ($hook == 'node_edit_form') {
     if ($node = \Drupal::routeMatch()->getParameter('node')) {
      $content_type = $node->bundle();
     }
     else {
       $current_path = \Drupal::service('path.current')->getPath();
       $path_args = explode('/', $current_path);
       $content_type = $path_args[3];
     }
     $suggestions[] = 'node_edit_form__' . $content_type;
   }
 }

  Next, create twig templates in your theme's template directory in the form
  of node-edit-form--NODE-TYPE-SEPARATED-WITH-DASHES.html.twig.


Alter Ajax callback on Webforms I'm loading a webform on a Ajax modal dialog. The form submission is also set to Ajax. I want to alter the Ajax submit callback so I can have more control over the form behaviour. I'm not being able to do that. The callback being executed is always submitAjaxForm, set on the WebformAjaxFormTrait trait.

Try using a

hook_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  ....
  if (isset($form['actions']['submit'])) {
    $form['actions']['submit']['#ajax'] = [
      'callback' => '/path/to/your/controller/or/webformhandler/submitModalFormAjax',
      'event' => 'click',
    ];
}

in your *.module and then implement the callback function somewhere

public static function submitModalFormAjax(array &$form, FormStateInterface $form_state) {...}


Print from drupal to a printer over the internet Hope someone can shed some light on this. I've been asked to develop an ecommerce site in which once the order goes through a receipt will be sent some order details over the internet to a printer without the need of a computer in the middle. This is for a takeway restaurant so I do not know what kind of printer I could use either. Has someone faced a similar problem and could point me in the right direction?

You can create batch script on remote PC that connects with your site database and check if it required to print something. Then generate document from database data, and print it from command line.


Can't create a new view I am having trouble creating a new View. I am just testing out the module, but when I click "Save" after setting everything up, I receive the following error:

  PDOException: SQLSTATE[HY000]: General error: 1267 Illegal mix of
  collations (utf8_general_ci,IMPLICIT) and (utf8_unicode_ci,IMPLICIT)
  for operation '=': SELECT s.uid, c.updated FROM {ctools_object_cache}
  c INNER JOIN {sessions} s ON c.sid = s.sid WHERE s.sid <> :session_id
  AND c.obj = :obj AND c.name = :name ORDER BY c.updated ASC; Array (
  [:session_id] => 3nTvCCvx2_Zopg07JqIBReKxL3TzvilIkwmHjFKZ93o [:obj] =>
  view [:name] => recently_posted_jobs ) in ctools_object_cache_test()
  (line 145 of
  /home1/mt/public_html/mtnet/sites/all/modules/ctools/includes/object-cache.inc).
  The website encountered an unexpected error. Please try again later.

Any ideas why this is happening?

Clear all your caches and try again.

You db seems to become corrupted or misconfigured. Your ctools module is using a different collation to store values in the db. So most of your site is utf8_general_ci and the ctools is using utf8_unicode_ci.

I gathered all of that from this line:

  (utf8_general_ci,IMPLICIT) and (utf8_unicode_ci,IMPLICIT) for operation '=': SELECT s.uid, c.updated FROM {ctools_object_cache}

If the clearing of caches fails then...

If you have phpmyadmin installed, go to the site's db and check what the Collate value is. Try changing it to utf_8 or something.

NOTE: I would create a backup of the db before you play with any collate value stuff.


How to migrate drupal6 ubercart to D7 commerce I have a website in D6, and ubercart is used now i want to upgrade the site to D7 but with commerce. How can it be done?

You probably want to look at Commerce Migrate together with Commerce Migrate Übercart that respectively understand how to create Commerce content and read Übercart content.

Commerce Guys already wrote two blogposts, Part 1, and Part 2, on the difference between the two.


Any particular vacuum policy to increase performance using Drupal with PostgreSQL? I'm running Drupal 7 with PostgreSQL as a Q&A (with a lot of nodes inserts/updates and several contrib modules). Do you recommand any particular pgsql vacuum policy on particular tables ?

In theory you can run your database optimization commands any time you want, but I think at least bi-weekly helps. However, if by running database optimization commands you intend to improve the performance of your site by more than 5%-10%, I'm afraid no vacuum optimization policy will do. You will need to utilize traditional performance troubleshooting procedures such as checking all your server's error logs, access logs, database slow query logs, as well as taking in consideration your peak and average load versus your current architecture.


How can I limit the maximum weight of an order? Is there a way in drupal commerce 2 to prevent adding a product to the cart, if the order weight exceeds a certain amount, let's say 40kg?
We are also using the commerce_cart_api plugin, in case this provides some hooks to prevent an add?

Alright, I'm definetly not sure, if this is the intended way of doing things, but I did it now this way via a custom cart event subscriber:
modules/custom/my_checkout/my_checkout.services.yml:
services:
  my_checkout.cart_subscriber:
    class: Drupal\my_checkout\EventSubscriber\CartEventSubscriber
    arguments: ['@messenger', '@commerce_cart.cart_manager', '@string_translation']
    tags:
      - { name: event_subscriber }

modules/custom/my_checkout/src/EventSubscriber/CartEventSubscriber.php:
<?php

namespace Drupal\my_checkout\EventSubscriber;

use Drupal\commerce_cart\CartManagerInterface;
use Drupal\commerce_cart\Event\CartEntityAddEvent;
use Drupal\commerce_cart\Event\CartEvents;
use Drupal\commerce_cart\Event\CartOrderItemRemoveEvent;
use Drupal\commerce_cart\Event\CartOrderItemUpdateEvent;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\Core\TypedData\Exception\MissingDataException;
use Drupal\physical\Calculator;
use Drupal\physical\Weight;
use Drupal\physical\WeightUnit;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class CartEventSubscriber implements EventSubscriberInterface {

  use StringTranslationTrait;

  /**
   * The messenger.
   *
   * @var MessengerInterface
   */
  protected $messenger;

  /**
   * The cart manager.
   *
   * @var CartManagerInterface
   */
  protected $cartManager;

  /**
   * Constructs event subscriber.
   *
   * @param MessengerInterface $messenger
   *   The messenger.
   */
  public function __construct(MessengerInterface $messenger, CartManagerInterface $cart_manager, TranslationInterface $string_translation) {
    $this->messenger = $messenger;
    $this->cartManager = $cart_manager;
    $this->stringTranslation = $string_translation;
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    return [
      CartEvents::CART_ENTITY_ADD => [['guardWeight', 100]],
      CartEvents::CART_ORDER_ITEM_UPDATE => [['guardWeight', 100]],
      CartEvents::CART_ORDER_ITEM_REMOVE => [['guardWeight', 100]]
    ];
  }

  /**
   * @param CartEntityAddEvent|CartOrderItemUpdateEvent|CartOrderItemRemoveEvent $event
   * @throws MissingDataException
   */
  public function guardWeight($event) {
    $cart = $event->getCart();

    // @todo - this should be configurable
    $maximumWeight = new Weight(40, WeightUnit::KILOGRAM);
    $orderWeight = new Weight(0, WeightUnit::KILOGRAM);

    foreach ($cart->getItems() as $order_item) {

      $purchased_entity = $order_item->getPurchasedEntity();
      // Calculate only items with a weight
      if (!$purchased_entity || !$purchased_entity->hasField('weight')) {
        continue;
      }

      $quantity = $order_item->getQuantity();
      if (Calculator::compare($order_item->getQuantity(), '0') == 0) {
        continue;
      }

      /** @var Weight $weight */
      $weight = $purchased_entity->get('weight')->first()->toMeasurement();

      $orderWeight = $orderWeight->add($weight->multiply($quantity));
    }

    if (!$orderWeight->lessThanOrEqual($maximumWeight)) {

      switch (get_class($event)) {
        case CartOrderItemUpdateEvent::class:
          $orderItem = $event->getOrderItem();
          $originalQuantity = $event->getOriginalOrderItem()->getQuantity();
          if (intval($orderItem->getQuantity()) > intval($originalQuantity)) {
            $orderItem->setQuantity($originalQuantity);
            $orderItem->save();
          }

          break;
        case CartEntityAddEvent::class:
          $orderItem = $event->getOrderItem();
          $cart->removeItem($orderItem);
          $orderItem->delete();
          break;
      }

      $this->messenger->addError($this->t('You would exceed the maximum order weight of @maxWeight, we could not update your cart.', [
        '@maxWeight' => implode('', $maximumWeight->toArray())
      ]));
    }
  }

}

It works well, but the "Your cart was updated" message is unfortunately still there. My guess is, it is still not the best location for this kind of logic.


A custom template file is not properly rendered I know this issue is covered quite well, but at the moment I'm really perplexed on this.

First, I'm using the Zen theme. In my template folder I've created page-music.tpl.php, page-gallery.tpl.php, page-bio.tpl.php, page-front.tpl.php, and so on. I've tried putting the code in the template.php for the custom pages, but I can't redefine the zen_preprocess_page() function. The custom pages won't render the admin menu module, or display the modules properly for that matter. The JavaScript code is all funky.

I'm not sure if I'm using the right code for the the template.php. There seems to be a lot of jumbled imformation on this matter.

If you have path like contact then the page-contact.tpl.php will be automatically available (view the theming documentation).

You can also declare your own tpl with this code (put this in a custom.module):

function custom_menu() {
  $items = array();
  $items['contact'] = array(
    'title' => 'Contact us',
    'page callback' => 'custom_make_section',
    'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

function custom_make_section() {
  return;
}

Also a little bit easier is using the module Empty Page in order to create the custom paths you want and then these paths will provide the page-....tpl.php you need.


Is there a way to conditional sort criteria in views Is there a way to make a conditional sort criteria with views in D7?

I want to do the following stuff:

if node property = x
  use this sort criteria
else
  use this one

You could achieve this using Views PHP.

Excerpt from the page:

  This module allows the admin account (user 1) to add fields, filters
  and sorts to views which use PHP code. It also supports additional
  accounts when the core PHP Filter module is enabled.


User subscriptions using Webform and Rules I set up a webform which is displayed as a block on a large number of nodes. The webform asks the user if they would like to subscribe to certain node updates - when a certain field changes value and when a new file is uploaded to another field. I therefore have two checkboxes which the user can check, but my problem is - what next? I can fetch the user email, node id and node title via the webform, but what to do with them? How to sort the users based on what they checked? How to display that on their profiles? Should I assign different roles to them? I would then need a role for every node x 2, which seems like overkill. I did quite a lot of googling, MailChimp seems to have many useful features... Any ideas?

I eventually solved this by using the Flag module and doing everything as suggested in this tutorial.


How to use the Theme Page reactions in context In the context module, how does the reaction Theme Page work? I am confused how to use it in my theme

I am using an Omega subtheme and want to display the Section title used in the context to show up in a region. How can I get this value to show?

You need to use a theme preprocess hook to pass the variable to the right zone template. Here's how I added it to my header zone:

function my_theme_preprocess_zone(&$vars) {
    $zone = $vars['zone'];

    if ('header' == $zone) {
        $theme = alpha_get_theme();

        // set via context module
        if (isset($theme->page['section_title'])) {
            $vars['section_title'] = $theme->page['section_title'];
        }
    }
}

Then in your zone--header.tpl.php file

<?php if (isset($section_title)): ?>
<div class="grid-<?php print $columns ?>">

<?= $section_title ?>

<?php endif; ?>


How to Create twig template files in drupal 8 for customizing user login,profile edit and forget password forms? Earlier we use the below code for creating custom template of user login ,user profile edit and forget password forms:

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

'user_pass' => array(
  'render element' => 'form',
  'template' => 'templates/user-pass',
),

'user_profile_form' => array(
  // Forms always take the form argument.
  'arguments' => array('form' => NULL),
  'render element' => 'form',
  'template' => 'templates/user-profile-edit',
),
);
}

function Yourtheme_preprocess_user_register(&$variables) {

$variables['rendered'] = drupal_render_children($variables['form']);
}

function Yourtheme_preprocess_user_login(&$variables) {

$variables['rendered'] = drupal_render_children($variables['form']);
}

How to Create same twig template files in drupal 8 for customizing user login,user profile edit and forget password forms?

Using hook_theme_suggestions_alter, you can create whatever template suggestions you like.  For example, based on the form id.  Just remember, the suggestion has underscores ("_"), but the template file has hyphens ("-").

function Yourtheme_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {

  if ($hook == 'form' & !empty($variables['element']['#id'])) {
    $suggestions[] = 'form__' . str_replace('-', '_', $variables['element']['#id']);
  }
}

then you would create templates in your theme, such as

form--user-register-form.html.twig

and

form--user-login-form.html.twig

You are doing some non-standard and unnecessary things by rendering the form in a preprocess hook and registering custom theme hooks for your forms.  You don't need to create new hooks in hook_theme, you can just use the suggestions, and it will do the rest, after you clear cache.

You can render your elements within the template.

For example, for form--user-login.html.twig:

    <form{{ attributes }}>

hello world

            {{ element.messages }}
            {{ element.name }} {# username element #}
            {{ element.pass }} {# password element #}

                <input id="show_password" class="show_password" type="checkbox" />
                Show password
                Forgot Password?

            {{ element.form_build_id }} {# required #}
            {{ element.form_id }} {# required #}

                {{ element.actions.submit }}

    </form>


setting comments unpublished by default for a content type? I want to open the comments for a content type by should be unpublished by default. Currently the comments are published by default.

Is there any way to accomplish this task. There is no option in the comments settings of the

If you don't want users to add comments without admin approval then you need to disable the below permission...

Skip comment approval

Once you disable it users would be able to post comments but they will not be visible to other users until the comment is approved by an admin.

This would set the permission for the entire contents and not for a specific content type.

If you want to set it for a particular content type then you would need to look into one of the contributed modules

commentaccess

Allow anonymous comments per node type

Comment Permissions - Stable Version only for 6 does not have a stable 7 version yet


How to use Migrate module to import Videos? I have a bunch of blog posts from an old site, some of which have .flv videos. I'm using the Migrate module to migrate all of these blog posts and the videos are the only piece left. I'm using the Video module for the embedded videos in my blog posts.

How do I use the Migrate module to import those videos into drupal?

I had to migrate a few thousand flv and mp4 videos. I ended up just migrating the file name into a field, uploading the videos files to s3 and then using a custom node.tpl.php to render the player:

<?php
  //display legacy videos
  $mediaid = $content['field_mediaid']['#items'][0]['value'];
  if ($mediaid != '') {
      $video2 = '';
              flowplayer_add('#player', array(
                'clip' => array(
                  'autoPlay' => TRUE
                ),
              ));
        print $video2;
 }
 //hide the mediaid field from display
 hide($content['field_mediaid']);
?>

Not very elegant but it got the job done. I used migrate 7.x-2.2 back then, maybe 2.5 has better video and/or file import features.


Why does drush rsync require a local site? It's clearly documented that drush rsync requires one of the sites to be local.  I'd like to understand why this restriction is in place.  I have configured site aliases to work with ssh, and I'm able to ssh into a system and then launch drush rsync.  Why can't drush do that?

Drush just performs the following in commands/core/rsync.core.inc:

$exec = "rsync -e 'ssh $ssh_options' $options $source $destination";

This isn't compatible with rsync daemons, as stated in the rsync manual:

  you must not specify the --rsh (-e) option.

Now, if you want to use drush to rsync between two remote environments, you'll need to install Drush on the source, then:

drush rsync @remote.source @remote.target


Drupal 404 not found with SOME browsers hello I have a drupal multisite setup, with the same modules and paths enabled ( services with REST endpoints).
I have some weird behavior:

on site1 I call a URL and get the HTTP status 401 ( which is normal as the test has the not signed request). I am not signing for the purpose of this test.

on site1 it works no matter which browser I use.

now site2, all is setup, and when I test it from chrome/firefox/IE/safari it all works (rest client, rest console etc...), when I say it works it means that I get the 401 back.
BUT when I test with safari mobile, or webview I get a 404. same request, same everything.

here are some log entries:

site1.net ###.##.180.109 - - [13/Aug/2013:16:07:01 +0000] "GET /REST/myapp/sendPassReset/oscar4/123 HTTP/1.1" **401** 157 "-" "Mozilla/5.0 (iPhone; CPU iPhone OS 6_1 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B141 Safari/8536.25" [smartphones] [0.671] [MISS] [nil]

site2.net ###.##.180.109 - - [13/Aug/2013:16:07:15 +0000] "GET /REST/myapp/sendPassReset/oscar4/123 HTTP/1.1" **404** 5 "-" "Mozilla/5.0 (iPhone; CPU iPhone OS 6_1 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B141 Safari/8536.25" [smartphones] [0.219] [-] [nil]

site2.net ###.##.180.109 - - [13/Aug/2013:16:54:36 +0000] "GET /REST/myapp/sendPassReset/oscar4/123 HTTP/1.1" **401** 180 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36" [-] [0.285] [-] [k-xae2qQMbNdjU4VbQoTpoTh1c2gfnvp-8cz7505Ajk;]

both sites are served by nginx, and PHP-FPM, with the same configuration.
same code base.

any idea as to what can be happening?

Finally tracked down the isse to broken/partially updated menu  in some templates... they were causing the issue. have not been able to close the issue though.

hard reset of memcached fixed the issue... not nice to do in production site on busy day.
we had to look through the whole bootstrap to finally see this.


Rules- How can I copy the formatted text in one field to another? I need to move the values of a field (long text and summary) to another field (long text and  summary).  I am trying to do this with Rules and VBO.

I have fetched nodes A and B, and I want to set the value of the field in B to the value of the field in A.

The challenge is that I can't use the Set a data value action to simply set B to A.  I can use Rules to create a text variable and get the value from A that way, but I still can't set that text variable as the value (Rules requires a formatted text variable).  However, if I try to create a formatted text variable, I can't set the value of the Long text and summary field as the value.

I have the two nodes available in Rules and they both have fields of type Long text and summary.  I just want to set the value of B to the value of A.  How can I do this?

I figured it out-- I needed to add :value after the body field, since the field value contains the summary, text format, and text value.

So for example, instead of profile:field-myfield, use profile:field-myfield:value.


Getting the auto summary from a node body I load an Article node with node_load() and I'd like to get the summary for the Body field. I know that I can access it with $node->body[$node->language][0]['summary'] but unless the user explicitly adds a Summary Body, then this field is empty.

I know that drupal will automatically generate a "trimmed body" if they don't add a Summary Body. How can I access that trimmed body?

EDIT:

I'm not interesting in render()ing the content, I just want the text. My module is generating a json feed for an external source.

node_view() is appropriate when you need to render whole node or many of it's fields.
But sometimes you have to render the only field you need. It can be done with field_view_field() or field_view_value():
$node = node_load($nid);
// Render array of body field.
$build_body = field_view_field('node', $node, 'body', 'teaser');
// Render it in common way.
echo render($build_body);

The interesting thing is that you can pass your own field formatter settings instead of view mode with the fourth parameter.
Please, read API docs for more info.


How to prepend a text of string to a content_type's field? For my assignment I have to write a module that when enabled will prepend a text of string "Hello World" to the body of a text field of hello_world_article content type.

I first tried to use Drupal 8 config export to try to set a default value (hello World) by using a yml file. However I get an error enabling the module that " field.field.node.hello_world_article.body already exists in active configuration."

My yml file is:

uuid: 42c51471-d897-4cb1-ac37-b2b6cddc6f0e58
langcode: en
status: true
dependencies:
  config:
    - field.storage.node.body
    - node.type.hello_world_article
  module:
    - text
_core:
  default_config_hash: e_0gHBXrh9sHHe-XksjIYpOmFEiugHbtoJdYPxbftAI
id: node.hello_world_article.body
field_name: body
entity_type: node
bundle: hello_world_article
label: Body
description: ''
required: false
translatable: true
default_value:
  -
    summary: ''
    value: "
Hello World!
\r\n\r\n
&nbsp;
\r\n"
    format: basic_html
default_value_callback: ''
settings:
  display_summary: true
field_type: text_with_summary

How else would I get about approaching this problem. Help would be much appreciated.

Create a template override for the field. Because it sounds like a class assignment, I'll leave the actual coding to you.


How we can change the Select option into Autocomplete I have one search index view for content type, here there are two term reference fields called, category and location.

I added those two term reference fields in that view exposed filter as select options. But i have one stuff here, if i change select options to Autocomplete filter means i couldn't see the view results, just blank page is coming.

So i needs to make those Select options to Autocomplete in hook_form_alter.

Please help me to solve this stuff.

While not a direct answer to your question, I would recommend trying the Chosen module, which integrates the jQuery Chosen plugin.  It will essentially convert most of your selects into something searchable / autocompletable, while keeping them as selects.  It works particularly well with multi-selects, and I have it working with some large vocabularies in Views exposed filters on a few sites.


How to prevent user registration I'm getting a couple of user registrations on my personal website (presumably from bots or people trying to hack my site). How do I disable new user registration entirely?

Change the setting 'Who can register accounts?' to 'Administrators only' at http://yoursite.com/admin/config/people/accounts


Missing formatter options for field from a custom table defined in hook_views_data() I integrated a custom database table to views using hook_views_data().
$data['custom_watchdog']['message'] = [
    'title' => 'Message',
    'help' => 'Full log message.',
    'field' => [
        'id' => 'standard',
    ],
    'filter' => [
        'id' => 'string',
    ],
];

It works, as I can display values in a view, but it misses a formatter option.
For example, the Taxonomy term: Description field has formatter options which allows to select Default or Trimmed.
Why isn't it available for my custom field?

You are comparing a standard Views field with an entity field. Only entity fields have field formatters. Create a custom entity instead of a custom table if you want to use this feature. For a standard field you have to use the options provided by Views. There is a trim option as well, but it is named differently, trim in the alter section. You see it in Views UI. Try to configure it and check the exported View.


How to load jQuery from a module Drupal 7.x, Garland theme.

I am writing a module that depends on jQuery.  I am seeing that when an anonymous visitor comes by that jQuery isn't being loaded.  How do I load jQuery from my module?

I am not really a Drupal developer.  This is my first module.  I want to maintain Core as is (no hacking) for easy updates and I don't want to change themes from Garland, so I don't really want to edit the theme to force jQuery.

Thanks.

jQuery should be available to you right out of the box in D7 if I remember correctly. But you need to use jQuery(...) instead of $(...). If jQuery is not being included for some reason, try using drupal_add_js().

See Drupal 7 JavaScript API documentation for more information.


Count content views show in number with icon I have enabled Count content views in Statistics.

The bottom of article show "3 reads".

I checked the code, the code is 3 reads

Because the number and word is together, I can't change word "reads" to an "eye" icon.

How do I show the number with icon.

Below is the effect I want

Assuming you're using D7, you can implement hook_node_view() in your custom module and override statistics count text as per your requirement. Check example below:

/**
 * Implements hook_node_view().
 */
function [YOUR_MODULE_NAME]_node_view($node, $view_mode) {
  if ($view_mode != 'rss') {
    if (user_access('view post access counter')) {
      $statistics = statistics_get($node->nid);
      if ($statistics) {
        // Alter text as per your requirement below.
        $links['statistics_counter']['title'] = format_plural($statistics['totalcount'], '1 read', '@count reads');
        $node->content['links']['statistics'] = array(
          '#theme' => 'links__node__statistics',
          '#links' => $links,
          '#attributes' => array('class' => array('links', 'inline')),
        );
      }
    }
  }
}


Multiple Images from external WEB URL My problem is simple though multiple solutions touch upon it but none address it directly. Hence posting this question.

Problem: I have multiple servlet urls (hosted at external web server)
that returns a single image in response stream. My task is to embed
images from these (precisely 6) URLs in my drupal site. How can I do
that.
Attempts: I tried using Media Module, Embedd Media Module,
Custom formatters but none worked for me (may be because I'm a
beginner). If anyone can help me with some sort of link of steps to achieve this.

I achieved it in a work-around. I am downloading images inside my drupal accessible folders with the fixed names. Updating these images with fixed names using a background script. Applied cache buster techniques so that images with same names are updated.


Move field from one profile type to another? I have a field in one profile type that really belongs in another profile type. The field already contains values.

I can imagine exporting the contents of the field, attaching a new instance of the field to the "other" profile, and importing the exported values to the new instance using feeds. But is there a more straightforward way to move a field (and existing values) from one profile type to another?

There's no easy way. That means if you don't have a lot of records your better off doing it manually.

If you must:
   1. Add the field to profile type B.
   2. Change the nid in the field data and revision DB table for every user from the nid of profile A to the nid of profile B.
   3. Remove the field from profile type A.


Drush on Windows 7 and WAMP Is running DRUSH on a Windows 7 64 bit machine in a WAMP dev environment worth it? I've heard there are some speed and performance issues with this set up? Will I lose any functionality with this set up?

Try the dev version at Drush-on-Windows-Installer GitHub.

Some key functionality, such as remote sql-sync, is not working yet. You could also try running drush under Linux using a Virtual Machine on your Windows box.


Problem attaching files to nodes with Services I'm trying to attach files (images) to nodes via Services 3 from an external app using JavaScript.

From what I understand (and doing) is:

1) Create a node posting JSON to my endpoint domain.com/api/node.json

{
  "type":"foo",
  "title":"Hello World",
  "language":"und",
  "body":{"und":{"0":{"value":"Body Text"}}},
}

2) Create file posting JSON to my endpoint domain.com/api/file.json

{
  "filename":"image.jpg",
  "target_uri":"public://image.jpg",
  "filemime":"image/jpeg",
  "file":"myBase64String"
}

No problem at all at this point.

Then when trying to attach the files created to the node, is where I have trouble, not http errors, simply nothing happens.

First I have tried posting JSON to my endpoint domain.com/api/node/*nid/attach_file after successfully creating a new file, and getting back the fid

{
  "field_name":"foo",
  "filename":"image.jpg",
  "fid":"*fid"
}

Returning Status 200 OK empty text, but when viewing the node remains the same without the file attached.

I have also tried to create the files first and then when posting for node creation adding the fid, the node is created but no file attached.

{
  "type":"foo",
  "title":"Hello World",
  "language":"und",
  "body":{"und":{"0":{"value":"Body Text"}}},
  "field_foo":{"und":{"0":{"fid":"*fid"}}}
}

My field is a field type Image, widget Image. I have also tried in another field type file, with same results.

If someone can give me a heads up, what am I doing wrong or what is missing. I can't find any explanatory documentation on line.

Thank you.

try adding more data to the attached file (it might be that fid and filename is not enough I can't find the example I used a long time ago, which had a similar problem):

alt (might be required in general or only if marked as required in bundle)
title (might be required in general or only if marked as required in bundle)
uid
filemime
uri
status = 1
display = 1

Some references I could find quickly:

https://stackoverflow.com/questions/5129559/attaching-image-files-to-nodes-programmatically-in-drupal-7
this answer: https://stackoverflow.com/a/19930610/1158887
https://drupal.stackexchange.com/questions/120078/is-it-safe-to-reuse-the-fid-file-id


_preprocess_views_view not getting called Drupal 7, Views, Bootstrap theme sub theme in use

I have a views-view-table.tpl.php file in my sub theme and I am trying to preprocess some of the variables sent to this tpl. I created a function bootstrap_preprocess_views_view(&$vars) in my template.php and it is not getting called when I visit one of my views pages. Why would this be? Other preprocess functions are getting called from the same template file. I have tried flushing the cache.

function bootstrap_preprocess_views_view(&$vars) {
  dsm($vars);
  dsm("aaaa");
  die;
}

Ok. Then, we have to consider the following possibilities:

The name of the function is bad typed. The structure for this case should be template_preprocess_HOOK(&$variables). The second part (_preprocces) and third part (_views_view) is well typed, but are you sure the first part is well typed? I assume that "bootstrap" is the name of your theme.
This template hasn't been called when you visit the page, for example, if the pages have been stored in cache_page table for anonymous users. Another possibility could be that a different template has been called.


Set module installed version In Drupal 7 we could edit the system table to set a module a version back to let the hook_update_n run again.

In Drupal 8 there is no system table.

Where can I find what version of the module is installed so I can change this and make sure the update hook is run again?

This is useful while developing hook_update_N() of my module so I can test this.

To store/get the version information for a module use the global functions:

drupal_set_installed_schema_version()
drupal_get_installed_schema_version()

For example set a new version for mymodule with drush:

drush ev "drupal_set_installed_schema_version('mymodule', '8123')"

Print the version with drush, in this example for the module comment:

drush ev "var_dump(drupal_get_installed_schema_version('comment'))"

The functions are defined in schema.inc. Here you can see how to access the key_value table through the keyvalue api, if you want to use your own code:

/**
 * Updates the installed version information for a module.
 *
 * @param string $module
 *   A module name.
 * @param string $version
 *   The new schema version.
 */
function drupal_set_installed_schema_version($module, $version) {
  \Drupal::keyValue('system.schema')->set($module, $version);
  // Reset the static cache of module schema versions.
  drupal_get_installed_schema_version(NULL, TRUE);
}


looping an image field with multiple values? alt or text? I am about to implement a img gallery in a  node template. The gallery has the usual HTML markup (a span with bgimage, wrapped by a div...) I do not have any knowledge on php, but - in the last 24h - i was able to modify some code snippets i found:

    <?php
$node = node_load($nid);
$image = field_get_items('node', $node, 'field_project_image');
$image_url =file_create_url($node->field_project_image['und'][0]['uri']);
foreach ($image as $key=>$value) {
$output = field_view_value('node', $node, 'field_project_image', $image[$key], array(
  'type' => 'image',
  'settings' => array(
    'image_style' => 'thumbnail', //place your image style here

  ),
));

print '
';
print '';

print '';

print '';

print 'title of the img???';

print '
';

}
?>

This works somehow. BUT: it always shows the same picture. (Apparently it is always the same image_url), plus: I don't have any idea how to implement the "title" or "alt" text for every single image. Please, I am in a serious need for help now...

You can follow the below code. Please change 'field_flexslider_example_image' with your field name in content type.

<?php
$node = node_load($nid);

$image = field_get_items('node', $node, 'field_flexslider_example_image');

foreach ($image as $key => $value) {
$output = field_view_value('node', $node, 'field_flexslider_example_image', $image[$key], array(
  'type' => 'image',
  'settings' => array(
    'image_style' => 'thumbnail', //place your image style here

  ),
));

$image_url = file_create_url($value['uri']);
$alt = $value['alt'];
$title = $value['title'];

print '
';
print '';

print '';

print '';

print '' . $title . '';

print '
';

}
?>


How do I programmatically remove one breadcrumb link? in Drupal 7 I could just use array_pop($breadcrumb), but in Drupal 8 the breadcrumb is an object and I don't see a method for removing the last element.

How can this be done?

Drupal 7 and Drupal 8 are more or less the same in some aspects.

If you use preprocess_breadcrumb in your theme, you would do

function my_theme_preprocess_breadcrumb(&$variables) {
  array_pop($variables['breadcrumb']);
  ...
}

You could also solve this in the template file, by skipping the first item in {{ breadcrumb }}

If you want module only solution, you could swap the breadcrumb service with your own thing.


form textfield name -value changed and does not validate any more i have a checkout-page (drupal commerce) form with an address section generated by the module addressfield.
currently all text-inputfields have this markup-structure:

<input class="last-name" id="edit-last-name" name="customer_profile_billing[commerce_customer_address][und][0][last_name]">

class + id + name

in this config they validate.

if i change the value of the name attribute the form doesnt validate anymore, the form says:

  field XY is required

the form-validator obviously doesnt recognise my inputs.

question: how can i get the validation process to work with a modified name attribute?

It all happens in drupal_validate_form().

  Validates user-submitted form data in the $form_state array.

If I could offer some advice - have a re-think. Changing the name attribute of form elements, especially on those that are part of field widget forms, is a good way to get unexpected results. The name on an input is completely irrelevant to the page, so changing it doesn't actually get you anything. If you're trying to change it so you can target the elements using JS, for example, I'd advise changing your JS code rather than the form markup. Trust me when I say it will be easier.

The only valid situation I know of to override the name of an element is when you need to provide multiple submit buttons on a single form that carry out the same action, but in a different context.


Redirect users to different page after a login failure in d7 I want to redirect the users to different page if they enter the wrong login details, for that I am using following code but it is not working.

function bartik_form_alter(&$form, &$form_state, $form_id)
{
    if ($form_id == "user-login")
    {
        $form["#validate"][] = "bartik_validate_login";
    }
}

function bartik_validate_login($form, &$form_state)
{
    // on successful login, the uid is set in form_state.
    if (empty($form_state["uid"]))
    {
        $_GET["destination"] = "some url goes here";
        drupal_goto("some url goes here");
    }
}

Please try with the correct form_id for user login.

i.e: if ($form_id == 'user_login') {

The form_id can be found in the HTML source hidden element

<input type="hidden" name="form_id" id="edit-user-login" value="user_login">


Best way for including javascript/jQuery OnLoad in EVERY page on my site Currently, in my theme.info file I am including 2 scripts:

scripts[] = js/backstretch.js
scripts[] = js/scripts.js

Backstretch is a jQuery plugin that allows for an expanding background image to cover your entire page.

I am currently using this code to autoload the JS:

(function ($) {

    var bgs=["bg1.jpg", "bg2.jpg"];
    var bgr=Math.floor(bgs.length * Math.random());
    $.backstretch(bgs[bgr], { speed: 1000 });

})(jQuery);

Two issues:

Sometimes it doesn't load the backstretch.js properly which may have something to do with my current OnLoad function in scripts.js. It loads the image but not maximum width/height of the browser initially.
For some reason, it doesn't work past 1 level in the site (although the JS seems to load when I check the site (could it be that the location of images is not relative of the JS file?) e.g.,:

  Works: site.com, site.com/page

  Doesn't Work: site.com/dir/page, site.com/dir/dir/page

I was wondering in my scripts file what would be the best OnPageLoad (or Preload?) function would be best to use?

Many thanks in advance.

Please read Managing JavaScript in Drupal, specifically the section on Behaviors. You'll need to do something like this:

(function ($) {

  Drupal.behaviors.exampleModule = {
    attach: function(context, settings) {
      var bgs=["bg1.jpg", "bg2.jpg"];
      var bgr=Math.floor(bgs.length * Math.random());
      $.backstretch(bgs[bgr], { speed: 1000 });
    }
  };

})(jQuery);


Drupal and reverse proxy: How to make Drupal aware that it's protocol is HTTPS? I have a reverse proxy Docker container in front a Drupal container on a Docker host.
My reverse proxy container is https://hub.docker.com/r/jwilder/nginx-proxy
The public site URL is https://ahora-stage2.dcycleproject.org
When a request is made to https://ahora-stage2.dcycleproject.org, drupal receives the following headers. I ran dpm(\Drupal::request()->headers); using devel/php on a backend web interface:
stdClass Object ( [__CLASS__] => Symfony\Component\HttpFoundation\HeaderBag [headers:protected] => Array ( [authorization] => Array ( [0] => ) [host] => Array ( [0] => ahora-stage2.dcycleproject.org ) [connection] => Array ( [0] => close ) [x-real-ip] => Array ( [0] => 216.246.250.184 ) [x-forwarded-for] => Array ( [0] => 216.246.250.184 ) [x-forwarded-proto] => Array ( [0] => https ) [x-forwarded-ssl] => Array ( [0] => on ) [x-forwarded-port] => Array ( [0] => 443 ) [content-length] => Array ( [0] => 212 ) [accept] => Array ( [0] => text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 ) [content-type] => Array ( [0] => application/x-www-form-urlencoded ) [origin] => Array ( [0] => https://ahora-stage2.dcycleproject.org ) [accept-language] => Array ( [0] => en-ca                 ) [user-agent] => Array ( [0] => Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.3 Safari/605.1.15 ) [referer] => Array ( [0] => https://ahora-stage2.dcycleproject.org/devel/php ) [accept-encoding] => Array ( [0] => gzip, deflate, br ) [cookie] => Array ( [0] => SESS06c9cc57c2abbd62a4b35358c6967749=zmOe3Gexxxxxxxx7238990ldZb50rMxl35yPOeM ) [x-php-ob-level] => Array ( [0] => 0 ) ) [cacheControl:protected] => Array ( ) )

Based on that information, https://x-team.com/blog/base_url-drupal-8/, https://medium.com/@lmakarov/drupal-8-and-reverse-proxies-the-base-url-drama-c5553cbc9a3e, and comments in the settings.php file, I put these custom settings in my Drupal settings.php file:
$settings['reverse_proxy'] = TRUE;
$settings['reverse_proxy_addresses'] = ['104.236.70.29','216.246.250.184'];

Nonetheless, Drupal always keep believing that the protol is HTTP, not HTTPS.
See enclosed image.

I'm wondering how I could set it up so that Drupal understands that it's behind a reverse proxy and that it's public URL should be served using the https protocol.

It turns out the IP which should be in the reverse_proxy_addresses is neither the IP which you get when you ping the domain, nor the ID in the headers which you can inspect. Rather, you need to temporarily install devel_php on your site, and then go to /devel/php and enter dpm($_SERVER['REMOTE_ADDR']);. This will give you a result such as 172.18.0.5, which then goes in $settings['reverse_proxy_addresses'];
More info at https://blog.dcycle.com/blog/170a6078/letsencrypt-drupal-docker/


Pass custom variable from template.php to *.tpl.php template.php > THEMENAME_field_CONTENT_TYPE(&$variables)
I am trying to check each field as it passes through...

if( $variables['element']['#field_name'] == 'field_I_am_looking_for' )
{
    if( $variables['element'][0]['#title'] == 'value_I_am_looking_for' )
    $variables['newVariableName'] = 'NewVariableValue';
}

or for Booleans...

$variables['newVariableName'] = True;

But in *.tpl.php file, when I do this...

<?php if( isset( $content['isIcebreaker'] ) ): ?>

It's What You're Looking For!

<?php endif; ?>

...Nothing happens.

Specific Details...
The custom content type is called 'Netrunner Card' and all cards have 0 or more 'subtypes'. The subtypes field is a taxonomy_reference field. One of those subtypes is 'Icebreaker' and I'm trying to set $variables['isIcebreaker'] = True; whenever a card has the subtype of 'Icebreaker' and then test against that in node--netrunner-card--full.tpl.php.

Basically, in regular-speak, when a card has 'Icebreaker' as one of its subtypes, I want to add in some custom div's and other content in the node--netrunner-card--full.tpl.php for those cards. But the custom variable isn't making it over. I'm uncertain as to what I'm doing wrong.

SIDE NOTE If there is a better way to do what I am trying to do, I would appreciate those answers as well. However, regardless, I would still love to know the appropriate, Drupal Best Practices way of passing custom variables from template.php to a *.tpl.php file.

CODE VIEW
I have split off my template.php and included the new file as sort of an extended template.php. Here are posts of both my template.php and my tpl file.

template_netrunner_card.php

node--netrunner-card--full.tpl.php

ANSWER: I used the preprocess_node function like so...

Every element key in the root of the $variables array will be available in the template file as an actual variable. The mechanics behind this is in theme_render_template(), which uses PHP's extract() function on the theme's variables.

So when you look at $content in the template file, that corresponds to $variables['content'] in the preprocess function.

Similarly, if you add $variables['newVariableName'] in the preprocess function, it will be available at $newVariableName in the template file.

If you want to add it to the content array, you need to do so explicitly in the preprocess function, e.g. $variables['content']['newVariableName'] = ...

Bear in mind that the content array is supposed to be a render array, so that's probably not the best place for it. The way you have it currently is fine, just use if (isset($newVariableName)): in place of your current array_key_exists condition.

Your current method is considered best practice for passing variables from preprocess functions (whether in template.php or a module file) to template files, you don't need to change anything in your thinking there.