Views to display nodes based on ACL permission I'm trying to use Flexiaccess with ACL to build a view based on node that the user has access granted by Flexiaccess.

I found this on Drupal.org, it's the same use case, but is not working for me maybe because is for Drupal 6. (http://drupal.org/node/549412):

    Here's how to do it:

  Under Arguments, create a new argument: "Node: Nid"

  Under "Action to take if argument is not present", select "Provide
  default argument"

  Set the "Default argument type" to "PHP Code", and enter the
  following:

  global $user; return db_result(db_query("SELECT
  GROUP_CONCAT(CAST(an.nid AS CHAR) SEPARATOR ',') FROM {acl_user} au
  INNER JOIN {acl_node} an ON au.acl_id = an.acl_id WHERE an.grant_view
  = 1 AND au.uid = %d", $user->uid));

  Then check "Allow multiple terms per argument", and click "Update".

I follow those steps but my view shows nothing.

Any help is really appreciated.

According to: https://www.drupal.org/node/1255426, Drupal 7 does not have db_result function. You have to replace it with db_query().

Code which worked in my special case:

<?php
global $user;
$query = db_query("SELECT GROUP_CONCAT(CAST(an.nid AS CHAR) SEPARATOR ',') FROM {acl_user} au INNER JOIN {acl_node} an ON au.acl_id = an.acl_id WHERE an.grant_view = 1 AND au.uid = :uid", array(':uid' => $user->uid));
$result = $query->fetchObject();
return reset($result);
?>


Is there any PHP package that's very similar to the Plugin API? I really like the Drupal 8 plugin system. I am now also working on a non-Drupal related project and am wondering if there's any similar solution to that on packagist.org? Was trying to find one but without success (maybe wrong keywords).

Does anyone know where the idea was coming from? Or is it original Drupal thing?

Drupal 8 Plugin API can be installed as a standalone package like follows:
composer require drupal/core-plugin
To make use of it you will have to develop a bunch of integration code.
Unfortunately there is no much documentation on how to use Drupal components without Drupal core.


Upgrade with third-party modules I'm trying to migrate a Drupal 7 website to Drupal 8.
I have installed on the same server those two websites. Drupal8 version is empty.
On the Drupal 7 website, more than twenty contrib modules are installed, like LinkIt, PathAuto, Token...
I downloaded with Composer the D8 version of those modules. I installed them without any configuration.
I followed the upgrading process on my D8 website, but the process cannot see installed modules on D8 version and told me that LinkIt or PathAuto won't be upgraded.

How can I fix it? Is there a solution to migrate configuration datas for these modules?

Pathauto has migrations for settings & patterns built into the D8 module. Linkit doesn't have built-in support migrations.


Get users by custom field and field type I'm using Drupal 7.
I'm trying to get all users with custom field field_id:

$users = user_load_multiple(array(), array('field_id' => '123456789'));
var_dump($users);

and I got the following error:

PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'base.field_id' in 'where clause': SELECT base.uid AS uid, base.name AS name, base.pass AS pass, base.mail AS mail, base.theme AS theme, base.signature AS signature, base.signature_format AS signature_format, base.created AS created, base.access AS access, base.login AS login, base.status AS status, base.timezone AS timezone, base.language AS language, base.picture AS picture, base.init AS init, base.data AS data FROM {users} base WHERE (base.field_id = :db_condition_placeholder_0) ; Array ( [:db_condition_placeholder_0] => 123456789 ) in DrupalDefaultEntityController->load() (line 191 of C:\wamp\www\my_proj\includes\entity.inc).

My questions:
1. How can get users by custom field ?
2. How to query the field type ? (is it text, int, float, etc..).

You'll need an EntityFieldQuery for that:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'user')
  ->fieldCondition('field_id', 'value', $field_id);

There's no native way to query by type of field. To do that you'll need to use the EntityFieldQuery::addTag() method to add a custom tag to the query, and then use hook_query_TAG_alter() to manually join the field_config table into the query before it's run.


Redirect a form just if the form is loaded in specific page(url) I've implemented a menu using hook_menu(),the page callback function checks if user is login or not, if user is logged in a form for creating a content of type 'request' is loaded if not using drupal_get_form, user login block is loaded.

Now what I'm looking for is when user signed-in, he/she returned back to this page so now he can fill the form.

I don't want all user login event redirected to this page, so now my question is :

  How to redirect a form just if the form is loaded in specific page(url)?

It can be accomplished adding 3 functions to your custom module:

The first one is to implement hook_form_alter():

function my_module_form_alter(&$form, &$form_state, $form_id){
  if($form_id=='user_login') { // It will be executed only on this form.
    // Check if the form is loaded in your custom path.
    if (current_path() == 'my_custom_path') {
      array_push($form['#submit'], 'my_module_login_custom_path_submit');
    }
    else {
      array_push($form['#submit'], 'my_module_login_user_submit');
    }
  }
}

The second one is to implement the redirect to your custom path:

function my_module_login_custom_path_submit(&$form, &$form_state){
  $form_state['redirect'] = 'my_custom_path';
}

The third one is to implement the redirect to user page:

function my_module_login_user_submit(&$form, &$form_state){
  $form_state['redirect'] = 'user';
}


Multiple image sizes I have a very treaky question: how can I make an image to be downloadable in different sizes? This mechanism is required for my photogallery website.

Example:

image field

you can also download this image in:

2000x1000 - these are the links to a specific image size
3500x1500
4000x2000
resolutions

You didn't mention which version of Drupal you are using, I'm assuming 7:

This is exactly what the image module in core does, it allows you to upload one image that it then can scale, crop and more. What it doesn't do is provide the links to download. I'd package this up into a small module (I couldn't find anything similar with a quick Google search) that defines the image styles using hook_image_default_styles(). You could then possibly create a field formatter that shows a thumbnail and then the links to different image sizes (you'd get the URL for each image style with image_style_url().

Probably one of many ways of doing this but if you are comfortable writing code this could be a good way to go!


Render image field from node in page.html.twig I make my first steps with Drupal 8. I have a site with a header image. On a specific content type "Blog" I want to replace the standard header image with a node specific header image. So in the content type "Blog" i made a image field "field_headerimage".
I also made it possible to make a content type specific page.html.twig, see https://drupal.stackexchange.com/a/141397/31981. This works.

Problem:
I want to render field_headerimage in page.html.twig. There is a "node" variable, but it seems like this values aren't able to render.

I would say that the Twig-ish way is to create a custom filter. The Drupal-ish way is to use a hook_preprocessor. The general idea of the MVC rewrite is to keep logic out of the templates. I couldn't see how to add Twig filters in Drupal 8 (anyone?) so I'll go with preprocessor.

Drupal 8 preprocessor

In your theme's template.php:

function mytheme_preprocess_page(&$variables) {
  if ( $variables['node'] ) {
    $node = $variables['node'];
    // Optionally limit by bundle type. How do you get a bundle in D8?
    // if ( $bundle != 'blog' ) return;
    // Get your image URI.
    $header_image = $node->get('headerimage')->value;
    // Just guessing here: not sure what to do but it may involve styles.
    $header_uri = $header_image->getFileUri();
    // Override the variable that normally stores the header image.
    // Not sure what that would be. Look in page.html.twig
    $variables['headerimage'] = $header_uri;
  }
}


How can I add a condition to the list of taxonomy a view is created from I've created a view using a taxonomy term let's say (a,b,c,d,e)

A content type can have multiple selections of these taxonomy term.

The view returns the content-type based off the taxonomy term selected "Content: Has taxonomy term (exposed)"

From this, it also returns a select list of all the taxonomy terms.

Now in the taxonomy I have a custom field "hide from public".  Terms "d" and "e" in the above list have this selected.

I would like to add a condition so that the view only returns the content type where "hide from public" is "false" and then the select list only shows the values where "hide from public" is false.

I can't add the condition if "hide from public" is false in the "Filter Criteria" because I believe it's checking for the Content-Type to have this value which it does not, so it returns nothing. How do I make the taxonomy list conditional?

Thanks!

The reason why you can't add a Filter based on a Taxonomy field is because you're building a Content type views and that information simply isn't available directly from content tables in the database. If you were using Taxonomy term views then you could add that filter directly.

But since you have an entity reference from your Content to the Taxonomy term, it is possible to add that extra information into Content Views, so you will be able to Filter your Content based on a Taxonomy term Field that is on the taxonomy term that your nodes are referencing.

With Relationships in Views you're allowing Views to reach into other database tables and use data from them, if they are somehow related to the entities the view is based on.

Here's how you do it in your case:

Add a Relationship to the field in your content that is referencing your relevant Taxonomy Taxonomy term referenced from field_mytermref

If you Require it, it will filter out only the nodes where that field isn't empty.
Add a Filter hide from public.

It will now be available in your Add Filter list because you added the Relationship in the above step, and that Relationship will be selected by default.

Adjust the Operator and Value so that it's not equal to Hide from public, or the other combination that it's equal to it being False.

Now your results will only show the nodes tagged with terms that are "public".
To adjust the Exposed filter the easiest is to use the Limit list to selected items option in its settings, and select only the terms you want to appear (Use the Ctrl key).


Programmatically node update while saving node How can I update the value of the field in the nodes while save/update the node?
When you save/update the node value from the field was taken and save in the same field in the other nodes.
I tried to do it hook_ENTITY_TYPE_presave()

$nodes = Node::loadMultiple($nids);
foreach ($nodes as $node) {
  $node->set('name_field', $value);
  $node->save();
}

But this causes infinite recursion

You can use hook_entity_presave

function hook_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {

    if ($entity->getEntityTypeId()=='node'){
        $value="099545";
        $entity->set('name_field', $value);
    }
}


Admin log in on site with no logins I'm working on a site that, in production, will have no logins. We've gone with Drupal to facilitate the creating and editing of content by non-experts.

My question is, in this scenario, what's the best practice for allowing an administrator to log in? Since there no login on the main site, how does an admin access it?

I know there's the standard page mysite.com/user or mysite.com/user/login. Leaving that out there where knowledgeable users could find it seems less than ideal to me.

Is that how people do it? Or is there another way?

Those pages are, by default, blocked in the Drupal generated robots.txt file meaning that it's very unlikely a "regular user" will stumble on them.

Someone would have to know you were using Drupal, and then type in that URL.  You're right though:  many people will know how to do that.

However, it's not a big deal.  Your admin account password should be strong enough that it cannot be guessed at.  Drupal is quite secure.  You have nothing to fear about leaving that login form where it is unless your passwords are really, really bad.

The amount of effort to re-create the login pages elsewhere does not make any sense in this case.


Views with contextual filter ignores sort order and number of nodes per page On my site I want to define tutorials. One tutorial consists of several nodes of the same Tutorial content type. The content type has a field taxonomy term reference and a weight, to determine the sort order.

My idea was to have a single view, selecting on Tutorial content type, ordering by weight, one node per page. So far this works. But to only show nodes for one specific tutorial I defined a contextual filter, on the tutorial field. Now only nodes for that specific tutorial are shown, as expected, but this also has the effect that:

The nodes are no longer sorted by weight.
I no longer have one node per page

I've been looking for workarounds, different settings, etc., so far to no available , so help would be greatly appreciated.

If this is a behavior of views that can't be helped, any other approaches to my use case would also be met with immediate gratitude.

Using: Drupal 7.39, Views 7.x-3.11

I tried your example (with Drupal 7.39 and Views 7.x.3.11) and was not able to reproduce the issue. In short, I followed the following steps:

Created a taxonomy vocabulary, called "Tutorial Vocabulary"
Created a content type, called "Tutorial Type" containing two additional fields:

"Tutorial term" (Entity Reference to Taxonomy Terms of type "Tutorial Vocabulary") and
"Weight" (Integer).

Created some content.
Created a View for "Content" type "Tutorial type", added the "sorted by Weight" criterium, removed the default "sorted by creation date" criterium, and configured the default pager to display only "1 item"
Created a contextual filter for the "Tutorial term" field, specifying "Show page not found" when the filter value is not in the URL, and leaving everything by default.

The contextual filter seems to work as expected when I pass the tid of the taxonomy terms: Only the nodes associated to a term are displayed, they are sorted by weight, and only one node per page.

Maybe you are following different steps from the ones I am listing above. If so, please edit your post to specify them, it might be useful in order to find a solution to your question.


Can't install Drush on FreeBSD I'm running FreeBSD 10 with PHP5.3.28

I can't use the port or package to install Drush because it will install the default PHP (5.4) as a dependency.  So I installed Drush manually.
Then when I invoked Drush it said:

  Can't find PHP

So I added this to csh.cshrc: setenv DRUSH_PHP /usr/local/bin/php

After reboot I now get this:

  Could not open input file: @pear_directory@/drush/drush.php

I don't have PEAR on my system and trying to install it also means it will install PHP5.4.  I was able to install Composer manually but I'm afraid it too will install PHP5.4 as a dependency for Drush.

Any ideas?

Note: php -i works.

composer install will not install php; go ahead and follow the instructions in the Drush README for the composer install, and you should be fine.

Note also that Drush master (Drush 7) will soon require php 5.4, so you should use Drush 6 if you'd like to stick with php 5.3.

I don't have a FreeBSD system to try this on, but composer global require drush/drush:6.* works fine on my Linux box.  If you have problems with the composer install, you might want to try composer self-update, to insure that you have a recent version; I can't imagine why FreeBSD should be different than Linux when finding and installing Drush.


Facebook share button not showing up I have installed the Facebook Share module on my Drupal 7 site and configured it accordignly to my preferences but it is not showing up on any of the pages I chose.

I just tested it even further by choosing it to be displayed every (full) node and it is showing up on basic pages, faq, and some more but not on my Ubercart products and one custom content type.  It does show up on another custom content type.

Any ideas?

I was finally able to resolve the problem. Just posting the solution in case it comes useful to anyone else.

As it turned out, the problem with Facebook share was display suite. The nodes that it was not working for were, of course, not random as it initially looked. They were the nodes which were using display suite. I didn't manage to find a solution to it and therefore I used the service links module (proposed by @Kenny Wyland), which had an extra feature covering the case that display suite is being used.


Set default values for a field from a node In Drupal, when you create a field, you can specify the default value for a field.
For example, if you have a field called price, you can set the default value to be 400.
When the user creates a new node, 400 is the default value, but s/he can change it to whatever s/he wants.

Is there a way to link this default value to a node field value.

For example, lets say on node/12 I have a field called "price default". If the user enters 500 on this field (on node/12), the default value of the price field (for all new nodes) will change from 400 to 500.

Ahmed was close, but to take it all the way you need to fetch the field's value:

function MODULENAME_form_alter(&$form, $form_state, $form_id) {
  if ($form_id = 'YOUR_FORM_ID_HERE') {
    // Fetch node that has default value
    $node = node_load($nid);
    // Fetch the value from price field
    $node_wrapper = entity_metadata_wrapper('node', $node);
    $field_val = $node_wrapper->field_price->value();
    // Set fetched value as default
    $form['field_price'][LANGUAGE_NONE][0]["value"]['#default_value'] = $field_val;
  }
}

I am itching for a clean way to avoid having ['und'][0] in there,  as these values can change with localisation, but this would still work.


How to implement validation of field values? I'll soon be involved in a project that requires this, I haven't started yet. I have some experience with Drupal but I'm not that much of a programmer.

Here's how it goes:

Create a content type with field 1,2,3.
The user A adds a new node, filling those fields.
The user B can go through those fields and do some kind of "OK" in each one. This OK will only trigger something else that will show a cross or a check mark instead, it won't have any interference with the field, which will not be changed.
The user A1 adds a new node, and the user B has to go all the way again.

I'm asking your opinion on possible options to accomplish this.
I understand that maybe I'll have to write some code...

Here's the draw that illustrates this:

You could use the Flag module for this. Excerpt from its project page (bold markup added here):

  ... Flag is a flexible flagging system that is completely customizable by the administrator. Using this module, the site administrator can provide any number of flags for nodes, comments, users, and any other type of entity. Some possibilities include bookmarks, marking important, friends, or flag as offensive. With extensive views integration, you can create custom lists of popular content or keep tabs on important content.

  Flags may be per-user, meaning that each user can mark an item individually, or global, meaning that the item is either marked or it is not marked, and any user who changes that changes it for everyone.

  In this way, additional flags (similar to published and sticky) can be put on nodes, or other items, and dealt with by the system however the administration likes.

If you're not familiar with the Flag module, checkout the set of 8 video tutorials about the flag module. Refer to Flag's Community documentation for (way) more details.

Specific to your 3 fields here, you'd need 2 flags for each field X (x=1, 2, 3) (so 3*2=6 flags in total) whereas you'd add these flags to the nodes where these fields are used:

1 flag to indicate Field X is Valid.
1 flag to indicate Field X is Not Valid.

And if you'd then use either of the options I described in my answer to "How to add a custom icon or symbol to a flag link?", you can even make its look and feel match with your requirements.

Optionally also using some CSS magic to align 2 of these flags next to the field X that they are related to (as suggested in a comment below this answer, merci!).

But wait, there is even more: by using all sorts of integrations with the Rules module, you could also implement things like:

"Send an eMail" to User B whenever User A does something that waits approval/review from User B.
"Send an eMail" to User A about the result (approve or reject) from User B.
Implement any kind of validations between those fields, such as "If field 1 has value P, then field 3 is not allowed to have a value of Z".

There are tons of other enhancements you could implement (potentially even causing User B to no longer be needed, since Rules becomes the validation engine ...).


Change stylesheet for just one page in Drupal 7 How can I add an additional stylesheet for just one page on a Drupal 7 site?

I want to add an additional stylesheet to a section of content on one page, but want the rest of the elements of the page to use the existing theme stylesheets?

How would I go about this, can I make a call to the additional stylesheet or should I embed the css directly in the page?

Thanks-in-Advance,

John

Try adding this code snippet in a custom module :

function MYMODULE_init() {
  // You can verify actual page by using arg() function. Example for targeting node with nid 123
  if (arg(0) == 'node' && arg(1) == '123') {
    drupal_add_css(base_path() . drupal_get_path('theme', 'mytheme') . '/path/to/css/file.css');
  }
  // You can verify actual page by using the actual alias
  // Supposing your page alias is : http://www.example.com/first-part/second-part
  $args = arg(NULL, drupal_get_path_alias());
  if ($args[0] == 'first-part' && $args[1] == 'second-part') {
    drupal_add_css(base_path() . drupal_get_path('theme', 'mytheme') . '/path/to/css/file.css');
  }
}

Don't forget to change MYMODULE by your module machine name


Insert grid of images into about page Im new to the forum  Hope you are all well?

I have a really simple thing I want to do with drupal but for the life of me I cant seem to get it right (I'm a beginner with drupal)

So I have an about page, and I add the body to the page. But what I want is to add images of members of the company the site is for above the body of text in the about page, like in a grid. So it would be the grid (say 3x3 image grid) then the body text at the bottom of the grid. How do I do this? I cant seem to find an answer anywhere and I'm pulling my hair out here.

Can anyone help me?

There are different pieces to this problem.

The grid with images.
You can do that with Views. I'd say create a Views display of type "Block".
E.g. if every member of the company is a node or a user with an image field, then you can use the view to show an image for each of them. There is a display plugin to show items in a grid.
Display this stuff on one page.
One way to do that is with panels.
Another way is to create a node type with a Block reference field in addition to the body text field. You create the about page as a node of that type, and fill in the body text and reference the Views block you just created.
Yet another way is to simply put the block into a theme region, and configure it to only show up on the "about" path.

Another way for all of this is to create a node type with a multiple-value image field. This is if you don't want every single member of the company to be a node or user entity by itself.

Then you can use a custom formatter, or just some CSS, or Display suite hook_ds_field_theme_functions_info(), to display the images in a grid.


How to set end date relative to start date in date range field Is it possible to set the end date relative to the selected start date in a D8 date range field?
I have a date range field that I use to specify an accounting period. The end date should now be put to one year minus one day from the selected start date. For example, the start date 2016-07-01 will give the end date 2017-06-30.
How is this possible?

The current widgets in core for the Datetime Range module do not allow this.

You would need to create a custom widget for this.  Off the top of my head, I would create one that extends DateRangeWidgetBase() and mostly mirrors what DateRangeDefaultWidget() does, except to collect a relative period in a plain text field for the end date.  Then, add a massageFormValues() function to turn the relative date into an absolute one, and then call parent::massageFormValues().  You may also be able to do this with a #process callback on the end date element, but I forget which of the two runs first during form processing.


Locating the source of Forbidden message When I login I see these "Forbidden" messages. How to track the source of this message?

Also I've enabled these settings:

error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

I started disabling modules one by one and rest_auth was actually causing it though it was  not being used. Simply disabling solved it. And yes it does not contain any word "forbidden".


View result alter title link based on content type I have view which it has content type filter with more than 1 content type(Eg: A,B). For one specific content type(B) i want to alter the title link to external url(This external url is a custom field in that content type(B) ).

If I alter through Rewrite results using token(custom url),it work fine for the title which comes from B content type, but the title which comes from A content type is going to home page since this custom field is not available in that content type(A).

Please some one suggest on this.

You can do it via views itself with the little tweaking.

Since you said the custom URL will not be available in other content types,

Add the required fields including custom field and the content path to your views fields.

Open the custom URL field and go to No Results Behaviour. Add the Replacement pattern of default content path.

Created a custom text and assembled results. Make sure u refer to custom URL field to link and not the default content URL.

It should automatically work now. Whenever there is no third party URL link not available, it will fetch the default URL. This should have your issue resolved.

But in case if the third-party URL field was available in all content type with some data, Then you need to do this in preprocess function. This approach will have issues.


How do I show the total number of votes for "Rating" option in Fivestar? When using the Fivestar module, I can show the result in three ways:

1) "Stars" - This has an additional setting called "Text to display under the stars". For example, it'll look like the following if I choose "Average vote":

*****
Average: 4.1 (235 votes)

2) "Rating" - There is no additional option whatsoever, so the above example will just look like the following:

4.1/5

3) "Percentage" - I don't use this, so let's just ignore it.

Is there a way to make the "Rating" option show the total number of votes like the following?

4.1/5 (235 votes)

UPDATE 1:

I have to overwrite the function theme_fivestar_summary on line 126, and add lines 279-301 right before return $output;:

function theme_fivestar_formatter_rating($variables) {
  $element = $variables['element'];

  if (empty($element['#item']['average'])) {
    $element['#item']['average'] = 0;
  }
  // Get number of stars.
  $stars = (empty($element['#instance_settings']['stars'])) ? 5 : $element['#instance_settings']['stars'];
  $average = $element['#item']['average'];
  // Rating is X out of Y stars.
  $rating = round(($average/100) * $stars, 1);
  $output = $rating . '/' . $stars;

  $votes = 235;
  if (isset($votes)) {
    if (!isset($user_rating) && !isset($average_rating)) {
      $div_class = 'count';
    }
    if ($votes === 0) {
      $output = ''. t('No votes yet') .'';
    }
    else {
      if (!empty($microdata['rating_count']['#attributes'])) {
        $rating_count_microdata = drupal_attributes($microdata['rating_count']['#attributes']);
      }
      // We don't directly substitute $votes (i.e. use '@count') in format_plural,
      // because it has a span around it which is not translatable.
      $votes_str = format_plural($votes, '!cnt vote', '!cnt votes', array(
        '!cnt' => '' . intval($votes) . ''));
      if (isset($user_rating) || isset($average_rating)) {
        $output .= ' (' . $votes_str . ')';
      }
      else {
        $output .= ' ' . $votes_str . '';
      }
    }
  }

  return $output;
}

But the big problem is that I have no idea how to pass the $votes variable, so I hardcoded $votes = 235; right above if (isset($votes)) {, just to see if the code works so far, which it does:

4.1/5 235 votes

I know where to add the parentheses (line 298), but I'm having trouble figuring out how to pass $votes. Any help is greatly appreciated.

UPDATE 2:

The code above is far from perfect, as it produces minor error messages regarding the $microdata & $rating_count_microdata variables. Using the code from Jeroen, I was able to come up with better code that I posted as the final answer below.

The output for average votes is set in the fivestar.theme.inc file, which is located at fivestar/includes. You have to overwrite the function theme_fivestar_summary on line 248 (version 7.x-2.1). In order to do this, simply copy the whole function to your theme's template.php file and make the necessary adjustments. I've already done that for you in the code underneath:

function YOURTHEME_fivestar_summary($variables) {
  $microdata = $variables['microdata'];
  extract($variables, EXTR_SKIP);
  $output = '';
  $div_class = '';
  $average_rating_microdata = '';
  $rating_count_microdata = '';
  if (isset($user_rating)) {
    $div_class = isset($votes) ? 'user-count' : 'user';
    $user_stars = round(($user_rating * $stars) / 100, 1);
    $output .= '' . t('Your rating: !stars', array('!stars' => $user_rating ? $user_stars : t('None'))) . '';
  }
  if (isset($user_rating) && isset($average_rating)) {
    $output .= ' ';
  }
  if (isset($average_rating)) {
    if (isset($user_rating)) {
      $div_class = 'combo';
    }
    else {
      $div_class = isset($votes) ? 'average-count' : 'average';
    }

    $average_stars = round(($average_rating * $stars) / 100, 1);
    if (!empty($microdata['average_rating']['#attributes'])) {
      $average_rating_microdata = drupal_attributes($microdata['average_rating']['#attributes']);
    }
    $output .= '' . t('!stars',
      array('!stars' => "$average_stars/5")) . '';
  }

  if (isset($votes)) {
    if (!isset($user_rating) && !isset($average_rating)) {
      $div_class = 'count';
    }
    if ($votes === 0) {
      $output = ''. t('No votes yet') .'';
    }
    else {
      if (!empty($microdata['rating_count']['#attributes'])) {
        $rating_count_microdata = drupal_attributes($microdata['rating_count']['#attributes']);
      }
      // We don't directly substitute $votes (i.e. use '@count') in format_plural,
      // because it has a span around it which is not translatable.
      $votes_str = format_plural($votes, '!cnt vote', '!cnt votes', array(
        '!cnt' => '' . intval($votes) . ''));
      if (isset($user_rating) || isset($average_rating)) {
        $output .= ' (' . $votes_str . ')';
      }
      else {
        $output .= ' ' . $votes_str . '';
      }
    }
  }

  $output = '
' . $output . '
';
  return $output;
}


Using taxonomy filter produces duplicate content in node view Each "info page" node on my site has a field referencing or more taxonomy terms from the 'info page' vocabulary.

I'm trying to use a node view to make it possible to find any/all content which references a particular taxonomy term. I'm getting duplicates in my node view whenever content has more than one taxonomy term and "Any" taxonomy terms are all searched. Within the returned results, nodes repeat a number of times equal to the number of terms the node references.
Eg. a node with 4 different taxonomy terms shows up 4 times in my table of results after searching using the view.

The view is output as an html table and using the filter -
Taxonomy:has taxonomy terms (i've selected all terms in my info page vocabulary) and exposed the filter.

The search works fine when any specific, but I get duplicates when searching "Any" terms within the vocabulary.

There are countless articles about how to solve duplication issues in views, none have worked for me so far, so I'm hoping that maybe the issue is with the way my view is setup.

Here's the export http://pastebin.com/P7EkC8KX

Under advanced, click aggregation settings then check Aggregation.  Then click Query Settings and check Distinct.


how to define entity preprocess function My custom module defines a custom entity, which extends the EntityAPIController class. I managed to make it basically working, i.e. displaying fields etc via my custom tpl.php file. But I would like to create a mymodule_preprocess_entity function (as suggested here) to add custom variables to the tpl.php file. But such function is not running (is not called).

Also, when I display this entity, I noticed that the function template_preprocess_entity(&$variables) from entity.module is not running, either.

What else needs to be defined to make the preprocess function for custom entity being called?

I created a general mymodule_preprocess(&$variables, $hook) function and it showed that the specific function name should be mymodule_preprocess_myentity. Where myentity is the proper name of the entity.

So, this code is working for me:

function mymodule_preprocess(&$variables, $hook) {
  if (isset($variables['elements']['#entity_type'])) { // or maybe check for $hook name
    $function = __FUNCTION__ . '_' . $variables['elements']['#entity_type'];
    if (function_exists($function)) {
      $function($variables, $hook);
    }
  }
}

function mymodule_preprocess_myentity(&$vars) {
  ...
}


How do I programmatically update the order status? After Payment is accepted, I need to update the order status to "Completed" from the page controller.

How do I do this, on Drupal 8?

I find no documentation about this; there is an example for Drupal 7.

// Updating Order status.
$orderObj = commerce_order_load($orderID);
commerce_order_status_update($orderObj, 'canceled', TRUE, 'Order Voided');
$orderObj->log = 'Order cancelled programatically';
commerce_order_save($orderObj);

You want to use the State Machine methods of the Commerce Order class.

It would be something like this, but it will depend on what you called your order states.

$order_state = $orderObj->getState();
$order_state_transitions = $order_state->getTransitions();
$order_state->applyTransition($order_state_transitions['complete']);

$orderObj->save();

If you aren't sure, you can always check the $order_state_transitions array to see what options you have.


I can't uninstall the Webform module I have the Webform module version  8.x-5.0-beta9, and when I try to uninstall the module Drush asks me to uninstall the webform_demo_application_evaluation module, first. When I try
drush pm-uninstall webform_demo_application_evaluation, it throws an error.

  PHP Fatal error: Call to a member function getColumns() on boolean in
  /var/www-drupal/core/lib/Drupal/Core/Entity/Query/Sql/Tables.php on
  line 227
  Drush command terminated abnormally due to an unrecoverable error.
  Error: Call to a member function getColumns() on boolean in /var/www-drupal/core/lib/Drupal/Core/Entity/Query/Sql/Tables.php, line 227

How do I resolve this issue? Do I need to install the development snapshot?

You should be able to manually delete the demo forms, blocks, and nodes and then uninstall the demo module.

Please create a ticket in the Webform issue queue.


Add a js file and be sure it is executed as last js file? I need to add a js file and make it to be executed as last js file (after all js that belong to modules)

I create a module for this. But I can't manage the order of modules execution. Don't I?
¿should I add this file in my theme or through a function instead?

Using drupal_add_js you can control the order of your JS files by assigning weight through $options array.

  weight: A number defining the order in which the JavaScript is added
  to the page relative to other JavaScript with the same 'scope',
  'group', and 'every_page' value.

  The exact ordering of JavaScript is
  as follows:

  First by scope, with 'header' first, 'footer' last, and
  any other scopes provided by a custom theme coming in between, as
  determined by the theme.
  Then by group.
  Then by the 'every_page' flag,
  with TRUE coming before FALSE.
  Then by weight.
  Then by the order in
  which the JavaScript was added. For example, all else being the same,
  JavaScript added by a call to drupal_add_js() that happened later in
  the page request gets added to the page after one for which
  drupal_add_js() happened earlier in the page request.

Code example:

drupal_add_js($file_path, array(
  'weight' => 10000, // Something higher than the weight of existing items
  'scope' => 'footer', // Make sure the script tag is rendered in the footer of the page, not the header
  'group' => JS_THEME, // JS_THEME has the highest group weight and will be rendered last
));


How do I override field_multiple_value_form()? I have to override the standard field wrappers which add additional divs.

Drupal uses the following code, in field_multiple_value_form().

$field_elements += array(
  '#theme' => 'field_multiple_value_form',
  '#field_name' => $field['field_name'],
  '#cardinality' => $field['cardinality'],
  '#title' => $title,
  '#required' => $instance['required'],
  '#description' => $description,
  '#prefix' => '
',
  '#suffix' => '
',
  '#max_delta' => $max,
);

I implemented hook_form_alter(), but this form needs extra data that are passed as argument: $field, $instance, $langcode, $items, $form, and $form_state.

How do I define hook_form_alter() in this case?

You need to implement hook_field_widget_form_alter(), which is invoked from field_multiple_value_form() using the following code.

  $element = array(
    '#entity_type' => $instance['entity_type'],
    '#entity' => $form['#entity'],
    '#bundle' => $instance['bundle'],
    '#field_name' => $field_name,
    '#language' => $langcode,
    '#field_parents' => $parents,
    '#columns' => array_keys($field['columns']),
    // For multiple fields, title and description are handled by the wrapping table.
    '#title' => $multiple ? '' : $title,
    '#description' => $multiple ? '' : $description,
    // Only the first widget should be required.
    '#required' => $delta == 0 && $instance['required'],
    '#delta' => $delta,
    '#weight' => $delta,
  );
  if ($element = $function($form, $form_state, $field, $instance, $langcode, $items, $delta, $element)) {
    // Input field for the delta (drag-n-drop reordering).
    if ($multiple) {
      // We name the element '_weight' to avoid clashing with elements
      // defined by widget.
      $element['_weight'] = array(
        '#type' => 'weight',
        '#title' => t('Weight for row @number', array('@number' => $delta + 1)),
        '#title_display' => 'invisible',
        // Note: this 'delta' is the FAPI 'weight' element's property.
        '#delta' => $max,
        '#default_value' => isset($items[$delta]['_weight']) ? $items[$delta]['_weight'] : $delta,
        '#weight' => 100,
      );
    }

    // Allow modules to alter the field widget form element.
    $context = array(
      'form' => $form,
      'field' => $field,
      'instance' => $instance,
      'langcode' => $langcode,
      'items' => $items,
      'delta' => $delta,
    );
    drupal_alter(array('field_widget_form', 'field_widget_' . $instance['widget']['type'] . '_form'), $element, $form_state, $context);

    $field_elements[$delta] = $element;
  }

For example, you could implement it using the following code.

function mymodule_field_widget_form_alter(&$element, &$form_state, $context) {
  $element['#prefix'] = $element['#suffix'] = '';
}

The arguments passed to field_multiple_value_form() are also passed to hook_field_widget_form_alter(), directly, or contained in $context.


Translation of BlockBase (ConfigurablePluginInterface) public function blockForm($form, FormStateInterface $form_state) {
    $form = parent::blockForm($form, $form_state);

    // Retrieve existing configuration for this block.
    $config = $this->getConfiguration();

    // Add a form field to the existing block configuration form.
    $form['Heading'] = array(
      '#type' => 'textfield',
      '#title' => t('Heading'),
      '#default_value' => isset($config['heading']) ? $config['heading'] : '',
    );

'#default_value' => isset($config['heading']) ? $config['heading'] : '',

can this thing be translated? And how?
I use it to display a text to site users

The key was in creating mymodule.schema.yml in mymodule/config/schema/mymodule.schema.yml

with content of a kind

block.settings.myblock:
  type: block_settings
  mapping:
    Heading:
      type: text
      label: 'Heading'
      translatable: true

also

$config = $this->getConfiguration();

is not needed
using

$this->configuration['heading']

insted

\core\modules\system\src\Plugin\Block\SystemBrandingBlock.php -- is a good example


Edit Blog Links & Breadcrumb? My client would like me to replace the s's with just ' on the links and breadcrumbs of user blogs for user names that end in s.

For example, the breadcrumb and blog links for the user Joe would remain Joe's blog while the breadcrumb and links for user Chris would be Chris' blog (instead of Chris's blog).

I searched for this and although I did find a way to do this inversion 6 it doesn't seem to work in version 7.

How can I do this?

I had similar, work to be done, in drupal 7.

So, what I did, is, I collected the breadcrumb title, like this,

$bread = drupal_get_breadcrumb();
$title = $bread[0];

$lastCharacter = substr($title, -1);

$lastCharacter gave whether the breadcrumb title ends in S or not. If it ended, then, I appended, (')at last otherwise, I apended, ('s).I did this by adding a function in template.php file. Also, you can do by making any module, or any other way you wish.


Add field to an entity_view for dispaly in a tapir table in ubercart In the simplest terms I am trying to add a 'vendor' column to the order view table in Ubercart which will display the author of each line item product.

Below is the table of interest.  I have hacked the direct code contained in uc_order.order_pane.inc but will refactor with hooks the drupal way ASAP. I have added my comments in the code below.

function uc_op_products_view_table($order) {
  dpm($order);
  $table = array(
    '#type' => 'tapir_table',
    '#attributes' => array('class' => array('order-pane-table')),
  );

  $table['#columns']['qty'] = array(
    'cell' => array(
      'data' => theme('uc_qty_label'),
      'class' => array('qty'),
    ),
    'weight' => 0,
  );
  $table['#columns']['product'] = array(
    'cell' => array(
      'data' => t('Product'),
      'class' => array('product'),
    ),
    'weight' => 1,
  );

Added by me:

  $table['#columns']['Vendor'] = array(
    'cell' => array(
      'data' => t('Vendor'),
      'class' => array('vendor'),
    ),
    'weight' => 1.5,
  );

.

  $table['#columns']['model'] = array(
    'cell' => array(
      'data' => t('SKU'),
      'class' => array('sku'),
    ),
    'weight' => 2,
  );
  if (user_access('administer products')) {
    $table['#columns']['cost'] = array(
      'cell' => array(
        'data' => t('Cost'),
        'class' => array('cost'),
      ),
      'weight' => 3,
    );
  }
  $table['#columns']['price'] = array(
    'cell' => array(
      'data' => t('Price'),
      'class' => array('price'),
    ),
    'weight' => 4,
  );
  $table['#columns']['total'] = array(
    'cell' => array(
      'data' => t('Total'),
      'class' => array('total'),
    ),
    'weight' => 5,
  );

  if (!empty($order->products)) {
    $build = entity_view('uc_order_product', $order->products);

This is the entity I want to edit. uc_order_product needs to have a field for Author / Vendor to make my table look right.

    dpm($build);
    $table['#rows'] = $build['uc_order_product'];
  }
  else {
    $table['#rows'][]['product'] = array(
      '#markup' => t('This order contains no products.'),
      '#cell_attributes' => array('colspan' => 'full'),
    );
  }

  return $table;
}

So this is the ugly hack I used to resolve the issue:

  if (!empty($order->products)) {
    $build = entity_view('uc_order_product', $order->products);
    foreach($build['uc_order_product'] as $line_item) {
      $node = node_load($line_item['#entity']->nid);
      $vendor['#markup'] = 'uid) . '>' . $node->uid . '';
      $vendor['#cell_attributes']['class'][] = 'vendor';
      $line_item_id = $line_item['#entity']->order_product_id;
      $build['uc_order_product'][$line_item_id]['vendor'] = $vendor;
    }
    $table['#rows'] = $build['uc_order_product'];
  }


Access JavaScript cookie in module file I am setting a cookie in an external JavaScript file with the current user time.
I want this time to be available to the server, so I am retrieving this from a cookie.

I am able to fetch the value, but only when I refresh the browser twice. If I change my current system time, and refresh the page, I still see the old time; when I refresh again, then I see the updated time.

JavaScript code

var now=new Date();
currTime=now.getHours();
document.cookie = "currentTime = " +currTime;

PHP code

$current_time = $_COOKIE["currentTime"];
echo $current_time;

I am calling the external JavaScript file in hook_nodeapi() using drupal_add_js().

As I said, I am able to get the updated value of current time from cookie but only if I refresh twice.

What could be the problem?

I understood the problem. It is because the first time it sets the cookie, and in the second time it becomes available to PHP; hence two refreshes.


user deletion : user_cancel_reassign not working when user has more than 10 associated contents I am attempting to suppress Users with no permissions/roles from our sites.
The user associated contents should be kept on user deletion.
This code below works when the user has a few associated content.
On deletion the content becomes of anonymous author.
It does not work anymore when the user is the author of more than 10 contents.
All associated contents are deleted when the user is deleted.
Another method is invoked , i suppose.
How can i solve this?
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use \Drupal\user\Entity\User;

function hook_preprocess_page(&$variables, $hook) {
  $route_name = \Drupal::routeMatch()->getRouteName();
  $user = \Drupal::currentUser();
  if (count($user->getRoles()) == 1 && ($route_name != "system.401" && $route_name != "user.login")) {
    $userWithoutRole = User::load($user->id());
    if ($userWithoutRole !== null){
      $method='user_cancel_reassign';
      user_cancel([], $user->id(), $method);
      $userWithoutRole->delete();
    }
    throw new UnauthorizedHttpException('insufficient permissions');
  }
}

NB: The same issue is remaining on the "auto purge users" module

user_cancel() is run in a batch. This means that either it's called in a form, or batch_process() needs to be called after it. For example, this is the code used from UserController::confirmCancel().
$edit = [
  'user_cancel_notify' => isset($account_data['cancel_notify']) ? $account_data['cancel_notify'] : $this->config('user.settings')->get('notify.status_canceled'),
];
user_cancel($edit, $user->id(), $account_data['cancel_method']);

// Since user_cancel() is not invoked via Form API, batch processing
// needs to be invoked manually and should redirect to the front page
// after completion.
return batch_process('<front>');

It's not necessary to delete the account, as that is already done from _user_cancel(), the batch operation callback used from user_cancel().
case 'user_cancel_reassign':
case 'user_cancel_delete':
  // Send account canceled notification if option was checked.
  if (!empty($edit['user_cancel_notify'])) {
    _user_mail_notify('status_canceled', $account);
  }
  $account->delete();
  // …

It's also probable that hook_preprocess_page() is the wrong place to call user_cancel() as it would be called when the page is being rendered, while the batch operations require to redirect users. See batch_process(), which contains the following code.
if (($function = $batch['redirect_callback']) && function_exists($function)) {
  $function($batch_url->toString(), [
    'query' => $query_options,
  ]);
}
else {
  return new RedirectResponse($batch_url->setAbsolute()->toString(TRUE)->getGeneratedUrl());
}


How to get/access field values while inside hook_block_view? I want to access the values of my field inside hook_block_view().

I tried with field_get_items(), and field_view_field() with no luck.

By the way the block is showing in a page. Is there a way to get the values set in the content type field settings?

You seem to need information about the field itself and not about its instances (neither globally nor in the context of a given entity).

Hence, you would want to do a:

$field = field_info_field('field_my_field');
$keys = array_keys($field['settings']['allowed_values']);
// $keys will now have the set of unique keys for your options as set from
// the field settings page. Eg. Alsace, Aquitaine etc.

field_my_field is the unique name of your field that you have also attached to a content type. To find this out, ensure the Field UI module is enabled, go to the Manage fields page for your content type and look up the Name column for the field in question.

If you are interested in knowing how the values you had set from the settings form go here, check out list_field_settings_form(). Here is a link to the documentation of field_info_field() as well.


Drupal 6 to Drupal 7 migration redirect not working I am migrating a D6 site to D7 and for some odd reason the redirect module is not creating the redirections. Any ideas? I am not getting any errors, warnings or notices

This is what I have:

class MyNewsMigration extends MyNodeMigration {
  public function __construct(array $arguments) {

    parent::__construct($arguments);

    $this->addFieldMapping('field_tag', '8')
         ->sourceMigration('Tag');
    $this->addFieldMapping('field_tag:source_type')->defaultValue('tid');
    $this->addFieldMapping('field_tag:create_term')->defaultValue(FALSE);
    $this->addFieldMapping('field_tag:ignore_case')->defaultValue(TRUE);

    // Redirect module to issue a 301 for each changing path
    $this->addFieldMapping('pathauto')->defaultValue(1);
    $this->addFieldMapping('migrate_redirects', 'path');

  }
}

Note: I added the migrate.redirect.inc using patch from here https://www.drupal.org/node/1116408

I had a slightly different use case - changing aliases for users from /source/user-name to /author/user-name and creating redirects from the old alias the new one - but the steps are still the same.

First, I implemented a complete() method in my migrate class. This is called after the new entity (node, user, etc) has been created:

  /**
   * Implementation of MigrateDestinationEntity::complete() method.
   *
   * @param $entity
   * @param $row
   */
  function complete($account, $row) {
    // Create redirect from old Source alias that uses /source/
    // to new user profile alias.

    if (!redirect_load_by_source($row->dst)) {
      // First, get the alias for the user profile. We have to generate it separately
      // here because pathauto_create_alias() has already been run by the time the code
      // gets here, and we don't have access to that path.
      $new_alias = pathauto_create_alias('user', 'return', 'user/' . $account->uid, array('user' => $account));

      // Next, create the $redirect object and save it.
      $redirect = new stdClass();

      redirect_object_prepare(
        $redirect,
        array(
          'source' => $row->dst,
          'source_options' => array(),
          'redirect' => $new_alias,
          'redirect_options' => array(),
          'language' => LANGUAGE_NONE,
        )
      );
      redirect_save($redirect);
    }
  }

And then, to handle rollbacks (during development), I created a new class that overrides DrupalDestinationUser and implements a custom prepareRollback method:

class CNSUserDestination extends DrupalDestinationUser {
  // Add prepareRollback() method to this class.
  public function prepareRollback($uids) {
    parent::prepareRollback($uids);
    // Load all of the entities, since we need them for pathauto_create_alias().
    $users = entity_load('user', $uids);

    // Load pathauto.inc file.
    module_load_include('inc', 'pathauto', 'pathauto');

    foreach ($users as $uid => $user) {
      $redirects[] = pathauto_create_alias('user', 'return', 'user/' . $user->uid, array('user' => $user));
    }

    // Delete redirects for user profiles.
    db_delete('redirect')
      ->condition('redirect', $redirects)
      ->execute();
  }
}

It worked like a charm.


AJAX added form element disappears after failed validation? I have a form field which uses the #ajax element. When a user interacts with this field a function is called and a new form element is added to the form and then the new form is displayed to the user.

However, if validation fails the added element disappears? Of course, I want it to remain.

How do I solve this problem?

Generally it's not good to create the elements in the ajax callback. What I usually do is add the form elements to the main form, but wrap them in the if statement, and then in the ajax callback just refresh the container of that element or the whole form if it's small.

function SOMETHING_form($form, &$form_state) {

  $form['nominee'] => array(
    '#type' => 'checkbox',
    '#title' => t('I am nominating someone else'),
    '#ajax' => array(
      'callback' => 'return_nominee_email_element',
      'wrapper' => 'nominee-email-wrapper',
      'progress' => array('type' => 'none'),
    ),
  ),

  if(isset($form_state['values']) && $form_state['values']['contact_details']['nominee'] == TRUE) {
    $form['nominee_email'] = array(
      '#type' => 'textfield',
      '#title' => t('Email'),
      '#required' => TRUE,
      '#prefix' => '
',
      '#suffix' => '
',
    );
  } else {
    $form['nominee_email'] = array(
      '#prefix' => '
',
      '#suffix' => '
',
    );
  }

 return $form;
}

function return_nominee_email_element($form, &$form_state) {
  return $form;
}

See if something like that works for you.


Menu links and content to appear in different languages I have a small link in my page; when I click it, the whole website should come up in a different language, i.e. menus and the content. What modules should I need for this to be done perfectly?

For example, I saw this website, where alignment and layout also get changed a bit.

The site is using the Internationalization module, but the different alignment, and layout is caused from a core feature Drupal has: When the language is one that is written from right to left, and a module adds a CSS file to the HTML output, e.g. using drupal_add_css(drupal_get_path('module', 'system') . '/system.admin.css');, Drupal search a file named system.admin-rtl.css, and uses it when that file is present; otherwise, it just uses system.admin.css.

In that site, the files having that "extension" are the following ones:

/modules/cck/theme/content-module-rtl.css
/modules/filefield/filefield-rtl.css?
/modules/nice_menus/nice_menus_default-rtl.css
/modules/node/node-rtl.css
/modules/poll/poll-rtl.css
/modules/system/defaults-rtl.css
/modules/system/system-rtl.css
/modules/system/system-menus-rtl.css
/modules/user/user-rtl.css
/modules/views/css/views-rtl.css
/themes/basic/css/style-rtl.css

To notice that, for example, /modules/poll/poll-rtl.css is not used instead of /modules/poll/poll.css, but together; /modules/poll/poll-rtl.css should then just contains the CSS styles that are specific for a right-to-left language.

The same is done for a left-to-right language; the difference is that Drupal looks for a file named, e.g., /modules/views/css/views-ltr.css, instead of /modules/views/css/views-rtl.css.


boost module - no file to Disallow: /boost_stats.php I have followed the installation guidelines and installed Boost, but where it states to add a line 'Disallow: /boost_stats.php' for robots.txt doesnt seem to make sense as I dont have a boost_stats.php file in root for search engines not to follow anyway. Do I really need to add this line?

This file was a part of the Boost module in Drupal 6. It is no longer present in the Drupal 7 version. If you are using D7 this instruction can be ignored.


Populating Select2 with AJAX I am trying to populate a selec2 field on open with AJAX in Drupal 8. In my hook_form_alter, I have added the following code:
  $form['#prefix'] = '
';
  $form['#suffix'] = '
';

  $form['field_author']['widget']['#ajax'] = [
    'callback' => 'myPopulate',
    'wrapper' => 'form-ajax-wrapper',
    'event' => 'select2:opening',
  ];

which correctly calls to the callback function when I try to open the drop-down list:
function reloadOptions(array $form, FormStateInterface $form_state){
  $query = \Drupal::entityQuery('node');
  $query->condition('type', 'author');
  $query->condition('status', 1);
  $nids = $query->execute();
  $nodes = Node::loadMultiple($nids);

  foreach ($nodes as $node) {
    $options[$node->id()] = FieldFilteredMarkup::create($node->getTitle());
  }

  $form['field_author']['widget']['#options'] = $options;

  return $form;
}

The query is ok, and the way in which the options are loaded also seems ok. However, when I click on the selec2 field to open it, the ajax throbber is shown but the drop-down list does not open.
Any ideas why is this happening?
Thanks!
EDIT:
A capture of the behaviour of the selector2. As you can see, the drop-down list is not displayed after you click. However, if the ajax call is removed, it works correctly.

The ajax callback is pointing to the wrong function, should be:
callback' => 'reloadOptions',

It's better to make it return just the field rather than the entire form
$form['field_author']['#prefix'] = '
';
$form['field_author']['#suffix'] = '
';

$form['field_author']['widget']['#ajax'] = [
  'callback' => 'reloadOptions',
  'wrapper' => 'author-ajax-wrapper',
  'event' => 'select2:opening',
];

Adjust the reloadOptions fuction, so it returns just the specific field
return $form['field_author'];


Composer require drupal/ packages doesn't work If I run...

composer require drupal/token

...I get...

Could not find a version of package drupal/token matching your minimum-stab
  ility (dev). Require it with an explicit version constraint allowing its de
  sired stability.

Not sure if this is relevant, but token is already installed in my site, but is not required in composer.  I want to require (and upgrade) the module with composer.

Changing my minimum stability from dev to stable does not resolve the problem.

I am having the same problem with other modules when I try to run 'composer require'.  Composer always responds with "Could not find a matching version of package..."

Here is a question I posted earlier today that may be related: Composer doesn't see that updates are needed

Sounds like Composer doesn't know about Drupal's packages, which suggests you're missing a reference to the repository in composer.json.

Add this and you should be good to go:

"repositories": [
  {
    "type": "composer",
    "url": "https://packages.drupal.org/8"
  }
]


How can I customize the first sidebar? I am trying to customize the Bartik theme.
How can I customize left sidebar? I want to add some more links, and remove the search fields.

You can disable the search block in "Structure -> Blocks" in the admin panel. On the same page you can create a new block and add some links to it. Then add the block to the side bar.


Inclusion of SEO-related content in the header using structured Microdata I am currently looking at the SEO of our site, and I will be using Schema.org Microdata in the head and 'rich snippets', as well as including Facebook OpenGraph data.

What is the best way to include this information in the header, extract it from the content etc.?

Are there any modules that can help out with this task? Are there any best practices?

You can use Drupal hooks and functions like

hook_preprocess_html - Get and set metadata here
drupal_add_html_head - add element to HTML head

You could also call drupal_add_html_head from other API hooks such as hook_node_view, hook_ctools_render_alter, hook_init etc..

e.g:

/**
 * Implements hook_preprocess_html
 */
function mytheme_preprocess_html(&$vars) {

  $content = drupal_get_title() ? drupal_get_title() : variable_get('site_name', 'Drupal');
  // Add open graph title to head
  $element = array(
    '#tag' => 'meta',
    '#attributes' => array(
      'property' => 'og:title',
      'content' => strip_tags($content)
    )
  );

  drupal_add_html_head($element, 'fb_social_open_graph_title');

}


How to redirect views of entity types (bean) for user roles? RabbitHole does not provide this functionality for bean blocks and Entity Bundle Redirect does not seem to work. There is a user role which may edit bean blocks but I want to prevent them from viewing the bean block itself, it rather gets included via php/ views on different nodes.

How can you do that?

EDIT

this is the way the bean blocks are printed

<?php
    $bean_left = bean_load(2);
    print render(bean_view($bean_left));
?>

From quick view of RabbitHole I would suspect that it doesnt support blocks. One way to prevent this could be to use hook_block_view_alter and drop the data when comparing the url. Something like

function MYMODULE_block_view_alter(&$data, $block) {
  // Remove the data if some page view, possibly
  // this would also disable the data on bean/123/delete... :/
  // mayby instead dpm($block) with devel for better targeting?
  if (arg(0)=='bean' && arg(2) !='edit') {
    unset($data['content']);
    //or redirect
    //drupal_goto('somepage');
  }
}


How do I fix these requirement conflicts? While updating through composer, I am getting an error from the Webform module. Drupal version 8.9.1 updated. How do I resolve this error?
Problem 1
    - drupal/webform_node 5.15.0 requires drupal/webform 5.15.0 -> satisfiable by drupal/webform[5.15.0] but these conflict with your requirements or minimum-stability.
    - drupal/webform_node 5.15.0 requires drupal/webform 5.15.0 -> satisfiable by drupal/webform[5.15.0] but these conflict with your requirements or minimum-stability.
    - drupal/webform_node 5.15.0 requires drupal/webform 5.15.0 -> satisfiable by drupal/webform[5.15.0] but these conflict with your requirements or minimum-stability.
    - Installation request for drupal/webform_node (locked at 5.15.0) -> satisfiable by drupal/webform_node[5.15.0].

drupal/webform 5.15.0 seems to be locked below the v5.15.0 and thus blocking the drupal\webform_node update.

check if you have an explicit version number in your composer.json that conflicts with the desired version
On several occasions, I unblocked such situation by removing the docroot/vendor directory followed by a composer install command (and removing the composer.lock file if a new conflict arised)

composer.json is a list of modules with version constraints that is user-defined.
composer.lock is the list of currently installed modules generated by composer install. If composer.lock is present, the list of resolved dependencies will be installed if you do composer install. This allow to define and deploy a set of resolved dependencies. composer update will resolve the dependencies again and update composer.lock (thus the update). From my experience, it could happen that you have unresolved conflict between explicit version definition in composer.json and the composer.lock. So you could get rid of it, and also the whole vendor directory, and do a composer install from scratch again. If the installation fails again, it must be from a human-generated composer.json conflict.


Creating an external authentication module In Drupal 7, is it possible to make a module that handles user authentication without using the user_external_login_register method?  (In other words, without saving the user in the Drupal database?)

Of course, Drupal will need the uid of the logged-in user, so my guess would be that this would be pretty hard if not impossible.

It would also require Drupal to do its checks on this external source every page load. So, would this require hacking the User module, or making something similar? Is that even possible?

I stumbled on the exact same problem recently, and ended up using a generic user for all ones authenticated via the external system. It's the only way I see to manage this without creating a Drupal user for each external one.

Of course, it all depends about what you're trying to achieve. If you need to customize the website based on each individual user, you're out of luck with this solution. But then, if you need this level of granularity, you'd use a standard solution with automatic user creation, right ?


How do I add an attribute in an anchor tag? I want to make a module which will add some attributes in an anchor tag, whether the user adds in CKEditor or it is from Drupal menu system, before rendering it to the browser.

I can do it through jQuery with $('a').attr('data-anchor', 'arial');, but is there any way to do it through a module?

You can do it using hook_link_alter

/**
 * Implements hook_link_alter().
 */
function mymodule_link_alter(&$variables) {

    $variables['options']['attributes'] = array('data-anchor' => 'arial');

}


hook_form_alter() does not work for the contact form? I have contact form module enabled from core drupal 8 modules.

When I use the below code it has

   $form['field_consumer_name']['widget'][0]['#title'] = 'Individual Name';

I want that this code which I have written should override default title but it does not .
I would be interested in knowing how I can override title?

 function referral_q_form_contact_message_referral_form_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state ) {
   // print_r($form['field_consumer_name']['widget'][0]['#title']);
$form['field_consumer_name']['widget'][0]['#title'] = 'Consumer Name Works';

   $form['#prefix'] = '
';

   $form['field_consumer_name']['widget'][0]['#title'] = 'Individual Name';
   $form['field_referral_date']['widget'][0]['#title'] = 'Date';

   $form['field_diagnostic_code_1']['widget'][0]['#title'] = 'Diagnostic Code';

   _referral_q_remove_radio_na($form['field_veteran']);

   $form['#suffix'] = '
';
 }

This is the array structure of the relevant part of the form.

Using `$form['field_consumer_name']['widget'][0]['value']['#title'] = 'Individual Name'; worked for me.


Get list of preprocess block variables How can I display a list of preprocess block variables so I can conditionally include a library? Using the 'plugin_id' doesn't seem to work and when I echo all of the variables all I see is a blank page. Is there a Drupal page that will show me what all the variables are for blocks?
My custom block module is called, 'leaflet_block'.
function leaflet_block_preprocess_block(&$variables) {
  echo "<pre>"; print_r($variables); echo "</pre>"; // shows a blank page

  if ($variables['plugin_id'] == 'leaflet_block') {
    $variables['#attached']['library'][] = 'leaflet_block/leaflet_block';
  }
}

echo "<pre>"; print_r($variables); echo "</pre>";

That's not how it should be done, instead, install the Devel module.
This will allow you to do:
dump($variables);

If you haven't turned caching off, for developing purposes, then you will have to flush all caches to see the dump.

In addition, if you also install the kint package/library with:
composer require kint-php/kint

now you could also do:
kint($variables);

Related: Welcome to Kint 101


Where do I find the Statistics module? I must use Drupal 5.10 for one project. It's already done, but I am doing some changes, so I must add this line to each node:

  Viewed: 3 | Total views: 30

I know I must use the Statistics module, but I cannot find one for Drupal 5. Can anyone help me please?

A quick search turned up this video from DrupalDude: Statistics module in Drupal 5

There's also the documentation for the module for the D5 version on Drupal.org that suggests you should be able to use statistics_get() to get the views for a certain node.

Something like the following would do it:

$stats = statistics_get($nid);

// Total view count
print $stats['totalcount'];
// Current day view count
print $stats['daycount'];
// Timestamp of last view
print $stats['timestamp'];


How to add a class to a List field based on the content? I have a List Field for the Articles that will work like a Category.

This is an image of the PSD file:

There are 6 options on the list so the user can select the appropriate one when creating the Article. The problem is that each of those options needs a different CSS class and it should still be possible to make a View for those contents and show them as shown on the next image.

The boxes with colors is what I need to create as the Category, but I cannot add CSS classes for each content on the list while having the View that shows those 4 articles.

Any idea how can I get this to work?

Found the solution with the Field Formatter CSS Class module to get the css added, then for being able to use it on the Views module, the instructions from are (Drewpal's instructions):
'm using the views module. In order to pass the css property captured with the Field Formatter CSS Class module through to the Views module, you have to do the following:

Go to ../admin/structure/views and edit the view that's displaying the field(s) where you want the css to be applied
In the "Fields" section, add the content field that's capturing the css class (in my case it was Content: Style)
On the configuration page, uncheck the "Exclude from Display" box and set "Formatter" to Key (if using Select List as in the video), then click apply
Next, edit the field that you'll want the CSS class to be applied
On the config page, in the "styles" section, check "Customize Field HTML" and then check "Create a CSS class"
In the "CSS class" textbox enter the token from the field that holds the css class (note: the token should be the name of the field like this [feild_fieldname] - mine was [field_style])
The select apply and it will pass the css class through.

More info here:
http://codekarate.com/daily-dose-of-drupal/drupal-7-field-formatter-css-class-module#comment-7154


Explain field's language opposed to node language I'm having a hard time understanding how it supposed to work.

For example I have a node where I set up the language to English. the langcode is en. If I want to read values from a field from this node I will have to do something like:

$node->field_custom[LANGUAGE_NONE][0]["value"]

and not

$node->field_custom[$node->language][0]["value"]

What is the point of having LANGUAGE_NONE for all fields if on all nodes this is the same, no matter what language the node has. Thanks.

If you use the module Entity translation you have the possibility to say that the body field can be translated but the image field should not be able to be translated.

In your example this would mean

The value of $node->field_body will have different values for the different languages the field is translated to. I.e $node->field_body['en'][0]['value'] could differ from $node->field_body['sv'][0]['value'].

But at the same time the image field will only have value in LANGUAGE_NONE.

Before the most used setup to have a multilingual site was to use the  Internationalization module, which would create a new node when a translation of a node was done. The new approach with entity translation translates the fields instead.

Worth noticing, the Internationalization module can be used together with Entity translation. I am only stating the older solution to multilingual sites.


Approach for building local/city versions of a national website? I'm looking for ideas and advices on how to adapt a national website to cities depending on whether the user is logged in or not.

As for a news website, the front page for anon users would be a mashup of nodes from all the regions.
But registered users will set their city during the registration process or later by editing their profile and will then have a local adapted version of the website.

Any ideas on how to achieve this are welcome

I'd recommend the Domain Access module(s) as the easiest way to set this up with multiple sub-sites (even with sub-domains) but still having a central site to control content and access:

  The Domain Access project is a suite of modules that provide tools
  for running a group of affiliated sites from one Drupal installation
  and a single shared database. The module allows you to share users,
  content, and configurations across a group of sites

It comes with a dozen or so helper modules and a few stand-alone projects that make it easy to create and manage sophisticated site networks.


Show or hide field data using java script in node I create one cck content type and add one text field in them with name of:  My friend name: text field with add more buttonThen, i submit form with entering my 15 friends names
Like this:
1
2
3
.
.
.
15
this node display all of 15 names,

i am trying to do after submit form display only 10 name and after 10 name display more link after click more button show remaining 5 names. Like this:12345678910 more...Remaining 5 names1112131415 how can i do this ? i am using Drupal 6

jQuery will do this for you, but you wiull probably have to either write your own code for list items > 10, or adapt existing code to suit your needs.

There are various show/hide plug ins for jquery. In Drupal the facet api uses a jquery function to do just that as well given it's limit.

Here is the function from facetapi.js

/**
 * Applies the soft limit to facets in the block realm.
 */
Drupal.facetapi.applyLimit = function(settings) {
  if (settings.limit > 0 && !$('ul#' + settings.id).hasClass('facetapi-processed')) {
    // Only process this code once per page load.
    $('ul#' + settings.id).addClass('facetapi-processed');

    // Ensures our limit is zero-based, hides facets over the limit.
    var limit = settings.limit - 1;
    $('ul#' + settings.id).find('li:gt(' + limit + ')').hide();

    // Adds "Show more" / "Show fewer" links as appropriate.
    $('ul#' + settings.id).filter(function() {
      return $(this).find('li').length > settings.limit;
    }).each(function() {
      $('').text(Drupal.t('Show more')).click(function() {
        if ($(this).prev().find('li:hidden').length > 0) {
          $(this).prev().find('li:gt(' + limit + ')').slideDown();
          $(this).text(Drupal.t('Show fewer'));
        }
        else {
          $(this).prev().find('li:gt(' + limit + ')').slideUp();
          $(this).text(Drupal.t('Show more'));
        }
        return false;
      }).insertAfter($(this));
    });
  }
}


Use View as root homepage handler In Drupal 7 I'm trying to accomplish the following:

1) www.domain.com          =   ViewA (All posts)
3)  www.domain.com/muffins  =   ViewA (Posts tagged with "Muffin" taxonomy)
4)  www.domain.com/cookies  =   ViewA (Posts tagged with "Cookie" taxonomy)
5)  www.domain.com/...      =   ViewA (Posts tagged with ... taxonomy)

I have a view, listing posts, with only one contextual Filter of "Category" (my vocabulary containing the required taxonomy), which works when tested in views.

I can set ViewA as the homepage, satisfying 1) but subsequent pages 2),3),4) are not handled by ViewA. Instead they return page not found as Drupal isn't aware that ViewA can handle the requests.

I know I can create a second page view ViewB with an additional url path segment like this:

www.domain.com/recipe/muffins  =   ViewB (Posts tagged with "Muffin" taxonomy)

But then all of my content has to live one "level" down under /recipe — which is not ideal.

Also, since the taxonomy grows as more recipes are added, hard-coding menu paths in a module is no a solution... or is it?

Any suggestions would be helpful.

I don't think this is possible without modification to Drupal core's routing. When you specify a Views page as the frontpage (e.g. /frontpage when you override the default Frontpage view), you're telling Drupal to route all www.example.com requests to that path (e.g. www.example.com/frontpage).

If you mandate that a required contextual filter (e.g. /frontpage/%), that path component isn't "copied over" (e.g. www.example.com/cookies doesn't route to www.example.com/fronpage/cookies). Nor can you add a views page with the root path /. If this was possible, you'd then have to deal with the problem of overlapping paths (e.g. should /admin be handled by system_admin_menu_block_page() or by your view?).

Instead of trying to fight Drupal's routing system, you'd be better off trying to hook into the alias system. For example, a module invocating hook_taxonomy_term_insert()/hook_taxonomy_term_update() could add a new alias for each term item you wish to shortcut to your view (e.g. aliasing /cookies to /frontpage/cookies).


File field emptied on node_save I know that similar questions have been asked before but none of the suggestions there have helped me at all.  I've been trying all day to get this node to save file data and nothing has worked.  I'm not sure whether I am missing something, but if anyone could help I appreciate it a whole lot.

This is the code, which seems accurate but when the node save happens the file field is emptied.  So I don't understand what is happening.  I have tried different approaches to this and haven't figured it out yet.

$file_object = file_save_upload('node_file', NULL, $dest, FILE_EXISTS_RENAME);
    if ($file_object !== 0) {
     $node->field_file_upload[$node->language][0]['value']=(array)$file_object;

        node_save($node);
    }

Well I answered my own question eventually.  The issue was the format for saving to this particular type of field 'file'.   I changed

$node->field_file_upload[$node->language][0]['value']=(array)$file_object;

to

$node->field_file_upload[0]['fid']=$file_object->fid;

For some reason the formatting that was given in other answers was not functional for me.  The file field type seems to be very particular about it's format, but it only NEEDS, the fid.  Once the node is loaded the full file array is loaded.

To answer longboardnode what I wanted was the array of data about the file that is stored when the file is uploaded.  Unfortunately node fields seem very picky about formatting.


Glossary mode on View Block disappear once a letter is clicked I know how to attach Glossary mode into View page, based on setting here. I have tried to attach this mode into one of my block, but it does not seem to work. Is there a solution that work for block with Glossary mode?

--- Update on March 28, 2015 ---

I fixed by adding a View page(then I disable this) and that Glossary mode just work fine on block, except it will disappear once a letter is clicked. I found a solution about this issue on Drupal 6. Does anyone know how to fix this on Drupal 7?

Found the step by step correct setting  from here.

Create a view with page to show desired content type  (PS: you must create a view page, event you only use the view block)
click on CONTEXTUAL FILTERS
add content title
Select this page override
Select Provide default value and type fixed value

Enter "a" for default display only "a" word containing content and enter "all" for default display "all" content

select Specify validation criteria:Basic
Click More AND check Glossary mode option
Set Character limit 1
save
Use Ajax "yes"

Now add a attachment

click on CONTEXTUAL FILTERS

add content title
Select this attachment override
Click Display a summary
Click Unformatted and check Display items inline, under Separator add "-" or "|"
Set Attach to: page From ATTACHMENT SETTINGS
Set Inherit contextual filters: NO From ATTACHMENT SETTINGS
Use Ajax: Yes
Now save and run the page


Invalid address: return even on successfully sent e-mail Need help ASAP.
My function is sending e-mail on successful quit. E-mail is sent well. The problem is that i'm always getting "Invalid address:" before my normal exit message.
Code is following:

$message_text = array(
'id' => 'modulename' . '_' . 'key',
'to' => '2@example.com',
'subject' => "OK",
'body' => array("OK"),
'headers' => array(
    'From' => '1@example.com',
    'Sender' => '1@example.com',
    'Return-Path' => '1@example.com',
          ),
);
$system = drupal_mail_system($module, $key);
$message = $system->format($message_text);
$system->mail($message);

Thanks.

This is because of the absence of $message_text['from'];
In SMTP module smtp.module.inc line 74-85 there is hack that handles the absence of 'Reply-To' by setting it to $message['from'] which is also absent, consequently 'Reply-To' will be empty hence throwing the error Invalid address:.
add $message_text['from'] = 'your from address' this will solve the issue.


Potluck (Food) Menu Sign up form I am looking a way to create a food menu sign up sheet.
Login user can select food menu from the list, If somebody picks the food, it is disabled, so nobody can sign up for that item again. Is there anything like this out there?

You could try a wishlist or gift registry module. Here's one. I haven't tried this but it should disable or remove items from the list once people select them.

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

Please note that this question has multiple or too many possible answers, so it might get disabled.


I can't get hook_menu() to work Hi I am running the code on p247 of "Pro Drupal 7 Development", which includes the code below and then defines a form.  I have enabled the module and cleared the cache but this isn't showing up in my menu system.  What am I doing wrong?

/**
 * Implements hook_menu().
 */
function formexample_menu() {
  $items['formexample'] = array(
    'title' => 'View the sample form',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('formexample_nameform'),
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM
  );
  return $items;
}

check
http:localhost/formexample

Back-end admin panel menu :

$items['admin/structure/formexample'] = array(
    'title' => 'View the sample form',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('formexample_nameform'),
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM
  );

used this code


Uploading an image from a form in my custom module I am creating a custom module where the user uploads and image to the Drupal DB using a form.  All the data except for the file is being put into the DB though.  The only thing that shows in the 'image' field is "[BLOB - 0 B]"  The only instructions/tutorials that I can find are for uploading files to a directory, not a table in the db.

function new_floor_map_form($form, &$form_state) {
    $form['new'] = array(
        '#type'     => 'markup',
        '#markup'   => '<h2>'.t('Start a new floor map:').'</h2>',
    );
    $form['#attributes']['enctype'] = 'multipart/form-data';
    $form['file'] = array(
        '#type'     => 'file',
        '#title'        => t('Choose a file'),
    );
    $form ['name'] =array(
        '#type'     => 'textfield',
        '#title'        => t('Name:'),
    );
    $form['active'] = array(
        '#type'     => 'checkbox',
        '#title'        => t('Set as current floor map?'),
    );
    $form['submit'] = array(
        '#type'     => 'submit',
        '#value'    => t('Submit'),
    );

    return $form;
}
function new_floor_map_form_submit($form,&$form_state) {
    if(isset($form['file']) && (!empty($form['name']))){
        $insert = db_insert('floor_map_images')
            ->fields(array (
            'image' => $form_state['values']['file'],
            'name'      => $form_state['values']['name'],
            'active'        => $form_state['values']['active'],
            ))
            ->execute();
    }

 }

You shoud use Drupal file managing system. When Drupal is aware of a file, its data is stored in the file related tables. If you need to do something with a file you only need its identifier, called fid.

So, in your form upload the file using Drupal Form API, and store the fid in your table. Whenever you need to do something with the file use the fid to get all the file information.

This question may be very interesing for you:
Managed file: the file used in the field may not be referenced

Check also the file_managed Form API element:
https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#managed_file


Print Drupal Statistics in node template? When the (core) statistics module is enabled, we get a '50 reads' at the bottom of each node.

Is there any way I can pull that '50' (the node view count) and print it in a node template?

I want to accomplish this without a contribute module.

Any ideas?

The statistics module provides that data through statistics_get(), which returns

An associative array containing:

totalcount: Integer for the total number of times the node has been viewed.
daycount: Integer for the total number of times the node has been viewed "today". For the daycount to be reset, cron must be enabled.
timestamp: Integer for the timestamp of when the node was last viewed.

e.g.
$stats = statistics_get($nid);
$total_count = $stats['totalcount'];
$day_count = $stats['daycount'];

To get it into a node template, implement hook_preprocess_node(), hook_node_view_alter(), or hook_node_view() (the latter will need to be in a custom module, the other 2 can go in a theme or module).
hook_preproces_node() example:
function MYTHEME_preprocess_node(&$vars) {
  $stats = statistics_get($vars['node']->nid);
  $vars['stats_total_count'] = $stats['totalcount'];
}

And in the template
<?php echo $stats_total_count; ?>

You'll need to clear Drupal's cache after adding the hook so the theme registry picks it up.


How to get order information on the checkout complete page? How do you get the order information such as user's name, address, e-mail and products he ordered, on the checkout complete page on Drupal Commerce for Drupal 7?

I've managed to complete this task.
First, you must get the order id from session or database using query.
Second, you must create an $order object like this

$order = commerce_order_load($orderId);

Define a new order sdtClass

$myOrder = new stdClass();

Wrap the order

$orderWrapper = entity_metadata_wrapper('commerce_order', $order);

And then you can get various order info like this:

// Get order number
$orderNumber = $order->order_number;

// Get user's e-mail address and encode properly encode it
$orderMail = drupal_json_encode($user->mail);

// Prepare an array to store products
$orderPurchasedItems = array();
// Create a foreach to loop through all the products and get the products info
foreach ($items as $item) {
    // Checks if the value is equal to product
    if ($item->type->value() === 'product') {
        // Get the unit price value per product
        $commerceUnitPrice = $item->commerce_unit_price->value();
        $entity = $item->value();
        if ($entity) {
            $orderPurchasedItems[] = array(
                "id" => $entity->nid,
                "quantity" => $item->quantity->value(),
                "price" => commerce_currency_format(
                    $commerceUnitPrice['amount'],
                    $commerceUnitPrice['currency_code']
                ), // this will result in $10
            );
            // Store all the ordered products in a new variable so we can use it later
            $myOrderProducts = $orderPurchasedItems;
        }
    }
}


How can I programatically load a group? I have written this code to render a list of profiles (using the Profile module). It works fine.

// render profiles
$accounts = \Drupal\user\Entity\User::loadMultiple($uids);
$storage = \Drupal::entityTypeManager()->getStorage('profile');
if (!empty($storage)) {
  foreach ($accounts as $account) {
    $profiles[] = $storage->loadByUser($account, 'profile');
  }
  if ($profiles) {
    $content = \Drupal::entityTypeManager()
      ->getViewBuilder('profile')
      ->viewMultiple($profiles, 'teaser');
  }
}

I have applied the same logic to rendering a list of groups (using the Group module). It fails with the error below.

// render groups
$groups = \Drupal\group\Entity\Group::loadMultiple($ids);
$storage = \Drupal::entityTypeManager()->getStorage('group');
if (!empty($storage)) {
  foreach ($groups as $group) {
    $test[] = $storage->loadByGroup($group, 'my_group');  // FAILS HERE
  }
  /* if ($groups) {
    $content = \Drupal::entityTypeManager()
      ->getViewBuilder('group')
      ->viewMultiple($group, 'teaser');
  } */
}

  Fatal error: Call to undefined method Drupal\Core\Entity\Sql\SqlContentEntityStorage::loadByGroup()

What method should I use to load a group? or how should I programatically load a group?

Thanks

Adding my comment as an answer:

$groups = \Drupal\group\Entity\Group::loadMultiple($ids); is all that is needed to load the groups based on IDs. Group::loadMultiple() does the storage bits already, so no need to duplicate the work.

So the full snippet would be something like:

<?php

$groups = \Drupal\group\Entity\Group::loadMultiple($ids);
if ($groups) {
  $content = \Drupal::entityTypeManager()
      ->getViewBuilder('group')
      ->viewMultiple($group, 'teaser');
}


Importing large flat-file data sources with Drupal 7 with Views 3 integration My goal is to produce a fast, reliable and automated method for accessing read-only data contained in several very large flat-file data sources (CSVs, Fixed Width and XML docs) using Drupal 7 that can be queried against using the Views 3 module.  I would prefer to use already available modules, but building a custom module is also an option.

To help rule out modules and methods not suited for the task, here are the stats on the files I'm working with:

Yearly Import: 8,500,000 line CSV file. (Purged and reloaded yearly. Has primary key.)
Weekly Import: 350,000 line fixed width file. (Purged and reloaded weekly. No primary key.)
Hourly Import: 3,400 line CSV file. (Would like to update and sync as often as possible, but no more than every 20 min. Has primary key)
Daily Import: 200 item XML file. (Purged and reloaded daily. Has primary key)

Converting between the three formats is not an issue and can be done if it will improve import performance or allow better tools to be made available. (AWK for Fixed Width to CSV, etc.) Retrieval and conversion automation is easy via cron and sh scripts, but still need to automate the Drupal 7 integration. The use of custom tables is also possible as long as vews can reference the data using relationships.

What would be the best practice to accomplish this type of data integration with Drupal 7?  Also, am I leaving out any important details regarding the data or what I'm trying to accomplish?

Here are a few projects I'm currently looking at to find a solution.  I would like to expand on this to help others decide which route to take when working with larger data imports.

Importing data into nodes:

Feeds (Currently Alpha for D7)

Feeds will import the data reliably.  Speed is reasonable for the smaller data sources but is too slow for the 300k+ tables.

Automation available using cron and Job Scheduler (Currently Alpha for D7).

Migrate

Not having an index or unique key available in the source data is making this difficult to use.  It is faster than feeds, but still slow to import the very large tables.

Automation is available via drush and cron.

Custom Tables Instead of Nodes

Data Module (Currently Alpha for D7)

The Data module looks very promising, but is very buggy for D7 at the moment. The automation and import speed requirements would be easily met using data, but reliability is lacking.  The views integration (link is for D6) looks very promising.

Table Wizard (Not available for D7)

Added this for reference.  There is no D7 candidate at this point, but could serve as a starting point for a custom module.

Views Schema (Abandoned, D6 only)

Added this for reference.  This seems to have been absorbed by Table Wizard in Drupal 6.  Again, added only for reference.

Importer (RC2 for D7)

Seems to require Table Wizard (D6 only) for Views integration.  Added for reference, but doesn't meet Views requirement.

@MPD - Added "Custom Tables" as a possible solution, and expanded modules.  Thank you for this addition.

My gut tell me that this plan will make your servers catch on fire...

Seriously, if you are churning that much data, then I think you need to keep the data in an external datasource and then integrate it with Drupal.

My initial thought would to use two databases for the external data, so that you can do the weekly import w/o disturbing things too much.  In other words, get database A up and running, and then import into B.  When the import is done, make B the live source.  Then wipe and import into A.

I have done a lot of integration of external datasources into Drupal, and it really isn't that hard.  I gave an overview in Transition plan for PHP5 abomination to Drupal.  That was for Drupal 6, but the same thing basically applies to Drupal 7.   Essentially, you simulate what CCK / Fields API does with your own interface.

Not having a UUID for the weekly database really throws a wrench in the works, though.  That part requires a lot of though, more that can be provided in a Q/A forum like this.

If you really do want to go down the import route, I would bail on Feeds and Migrate and write your own import script.  Basically, you do the initial bookstrap process from index.php, query your datasource, make your nodes, and then save them.  Programmatically making nodes is easy.

The best way to start out with this is to make a node with the UI, then print_r it, and replicate the object with code in your import script.  Taxonomy, files, and noderefs, are hard parts, but you just need to get familiar with these portions of the API to build up these object properties.  Once you have a valid node object, then you can just do a node_save().  Make sure you set a very large limit with set_time_limit() so your script runs.

EDIT BELOW TO ADDRESS CLARIFICATION/EXPANSION:

Personally, we stopped using the contrib module based approaches for data imports a while ago.  They do work mostly well, but we just ended up spending way too much time fighting them and decided the cost/benefit was too low.

If you really need the data in Drupal proper, then my opinion about a custom import script hasn't changed.   One of the modules you reference could be used as a starting point for how to build the node objects, then just loop through your data build nodes and save them.  If you have a PK, you can easily add in logic to search the database and node_load(), modify, and save.  An import script is really only a few hours work if you know the Drupal API.

If views integration is a key (and it sound like it is based on the edit) and you want to do the external tables approach, then your best option is do do a custom module and implement hook_views_data to get your data into views.  More than likely, you will custom module anyway to support your datasource, so adding this hook shouldn't be that much more work.  The TW and Data modules should have some example to get you going.

Personally, though, I have never found the views integration with external data to be really worthwhile.  In the cases where I have considered it, the data was just too "different" to work well with a views based approach.  I just end up using the method I described in the "abomination" link above.


Related node views - some elements with date field, some without. How to include elements with no date in results? I have a views block that displays related nodes based on tags. (See Entity Reference get nodes based on tags.) The comment links to the solution I found.

Now, I have to add another filter to the view.

Some of the related nodes have a date field (start and end date), and some do not. When I add a filter to exclude nodes where end dates have come and gone, no related nodes without the date field is shown.

How is it possible to filter out nodes where the end date is greater or equal to now on nodes with the date field, but still show nodes that do not have the date field?

Problem is in the very SQL. No date field in node means null value in result set. Any logical operation with null ends up returning null, see manual. And null is a logical false for conditions. So, each time you test a date to see what are OK, MySQL excludes them - lack of date is not a date in acceptable range.

If views would support negative filtering (exclude matching), it would be just as you want it. But views support only positive filtering (include only matching).

Enough of diagnosis, time for solution!
On the block's header Filter criteria you have a dropdown with add seelcted. Drop it down and use And / Or, rearrange. Make your filters OR, and after date limit add some other filter, one that will return true for no-end-date nodes. Here comes the tricky part - you can select the same field multiple times, but you cannot use null in place of date. If nodes without a date are simply of another content type, you are good. If they are of the same type, you have a problem - I'll add solution for that particular case if I'll find it.