Spam filter options for unregistered user to registered user email service I would like to give unregistered visitors the chance to send emails to node authors through a contact form. What would be the best and most efficient way to filter out spam?

1) Simply add a CAPTCHA to the contact form. However, I experienced CAPTCHA module to be not very reliable and I won't be able to afford Mollom.

2) Involve an external Gmail account and make use of their sophisticated spam filters. For example, when user A submits a contact form on a node created by user B, the email is first sent to an external Gmail account, filtered, and then - if spam free - forwarded to user B.

As an alternative for Mollom, perhaps Akismet could work? The service runs analysis on the comments/posts and determines whether they are spam from their content.

As an alternative for Captcha, perhaps Are You A Human could work? Rather than using wobbly text it asks you to complete a very simple game - causing less frustration to your users.

To properly answer your question: Given the two alternatives, I think the most efficient way to filter spam would be through Gmail, although it might violate their EULA.


Best way to change display for a field? I have a node display that shows about 20 different fields.
One of the fields is a list of years (multiple values). Instead of printing the list of years I would like to just show the first and last year, for example "1999-2005".

Views has a great formatter for those situations but I don't want to use views for the node display.

You might want to test the following simple formatter I put together for one of my projects - named mvspan (multivalue span). Soon after I wrote it, the specs of my client changed and I did not need it anymore, therefore it may need some more tests, therefore please accept it in its "as-is" shape.

It works for simple text or integer types, not date or datestamps, unfortunately. Feel free to shape it for your own needs.

It has two modes: displaying first/last values or min/max values. Plus, it allows you to set the delimiter to glue up the values.

mvspan.info:

name = Multi-value Span
description = "Formats multi-value fields to show first/last or min/max value spans."
core = 7.x
files[] = mvspan.module

mvspan.module:

<?php
 /**
 * Implements hook_field_formatter_info().
 */
function mvspan_field_formatter_info() {
  return array(
    // the key must be unique, so it's best to prefix with your module's name.
    'mvspan_formatter' => array(
      'label' => t('Multi-value Span'),
      'field types' => array('text', 'number_integer'),
      'multiple values' => FIELD_BEHAVIOR_DEFAULT,
      'settings' => array(
        'delimiter' => '...',
        'mode' => 'minmax',
      )
    ),
  );
}

/**
 * Implements hook_field_formatter_view().
 */
function mvspan_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();
  $settings = $display['settings'];

  $delimiter = check_plain($settings['delimiter']); // The delimiter string in the settings form

  switch($settings['mode']){
    case 'minmax':
      $minv = NULL;
      $maxv = NULL;

      foreach($items as $delta => $item) {
        if(is_null($minv) || $item['value'] < $minv){
          $minv = $item['value'];
        }
        if(is_null($maxv) || $item['value'] > $maxv){
          $maxv = $item['value'];
        }
      }

      if($minv === $maxv) {
        $element[0]['#markup'] = $minv;
      } else {
        $element[0]['#markup'] = implode($delimiter, array($minv, $maxv));
      }

      break;

    case 'firstlast':
      reset($items);
      $firstv = $items[key($items)]['value'];
      end($items);
      $lastv = $items[key($items)]['value'];

      $element[0]['#markup'] = implode($delimiter, array($firstv, $lastv));
      break;
  }
  return $element;
}

/**
 * Implements hook_field_formatter_settings_form().
 */
function mvspan_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state){
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  $element = array();

  // settings
  $element['delimiter'] = array(
    '#type' => 'textfield',
    '#title' => t('Delimiter'),
    '#description' => t('Delimiter string to be inserted between min and max values.'),
    '#default_value' => $settings['delimiter'],
  );
  $element['mode'] = array(
    '#type' => 'select',
    '#title' => t('Value handling'),
    '#description' => t('How multiple values will be managed: min/max or first/last'),
    '#default_value' => $settings['mode'],
    '#options' => array(
      'minmax' => t('Minimum/maximum'),
      'firstlast'  => t('First/last'),
    )
  );
  return $element;
}

/**
 * Implements hook_field_formatter_settings_summary().
 */
function mvspan_field_formatter_settings_summary($field, $instance, $view_mode) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  $summary = array();

  switch($settings['mode']){
    case 'minmax':
      $summary[] = t('Min/max values will be displayed');
      break;

    case 'firstlast':
      $summary[] = t('First/last values will be displayed');
      break;
  }
  $summary[] = t('using delimiter: "@delim"', array('@delim' => $settings['delimiter']));
  return implode('
', $summary);
}


How can I add a wrapper around my nodes? How can I wrap my nodes (output in teaser view) in a
 element?

My title

  //
 <--- add this

...

...

...

    ...
  //
 <--- add this

Copy the corresponding twig template of your view into your module/theme and name it properly after the view's display, fe. views--{type, fe. unformatted}--my-view-id--my-block.html.twig.


How can check if current user is node author in node template I am using Drupal 8. I would like to check if user (anonymous or logged user) is node author in node.html.twig, like below:

{# node.html.twig #}
  {% if is_author %}
    You are node author
  {% else %}
    You are not node author
  {% endif %}

Below codes not work:

/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHENE_preprocess_node(&$variables) {
  $global $user;
  if ($variables['node']->uid == $user->uid) {
    $variables['is_author'] = TRUE;
  }
  else {
    $variables['is_author'] = FALSE;
  }
}

How could I create variable 'is_author' in node.html.twig?

/**
 * Implements hook_preprocess_HOOK() for node.html.twig.
 */
function mytheme_preprocess_node(&$variables) {
   $uid = \Drupal::currentUser()->id();
   $author_id = $variables['node']->getOwner()->id();
   if ($author_id == $uid) {
     $variables['is_author'] = TRUE;
   }
   else {
     $variables['is_author'] = FALSE;
   }
}


How to enable Ckeditor for email templates? I have installed HTML Mail module, to send HTML emails and it is working fine and sending email in HTML format. Now i wanted to load CKeditor for email templates textarea, as html email will be handled now.

I have googled it, but didn't find any solution yet. Is there any way I can enable the ckeditor for system email templates and webform email templates.

-- Thanks for your time.

I recently had the same issue and was able to accomplish this through a hook_form_FORM_ID_form_alter(); in a custom module.

<?php

function MYMODULE_form_webform_email_edit_form_alter(&$form, &$form_state) {
  // This check will determine whether the form already has a ckeditor textarea on it, if not it will initialize ckeditor requirements.
  if (!function_exists('ckeditor_load_by_field')) {
    module_load_include('inc', 'ckeditor', 'includes/ckeditor.lib');
    $input_formats = ckeditor_profiles_compile();
    drupal_add_js(array('ckeditor' => array('input_formats' => $input_formats, 'plugins' => array())), 'setting');
  }

  // Set some vars.  Modify these as needed.
  $format_key = 'full_html';
  $element = $form['template']['template'];
  $element_id = 'edit-template--2';

  // The format array here is used within the ckeditor_load_by_field() function, without it things won't work.
  $format = array(
    '#options' => array(
      $format_key => $format_key,
    ),
    '#value' => $format_key,
  );

  // Both of the following keys are required for the textarea to become ckeditor-ified
  $element['#wysiwyg'] = TRUE;
  $element['#id'] = $element_id;

  // Run the ckeditor_load_by_field function which does all the magic.  Modify to match the $element var set above.
  $form['template']['template'] = ckeditor_load_by_field($element, $format);
}


file_field_widget_form error when programatically creating nodes I have a simple routine which I use to create nodes. The logic is something like this:

function make_node($node_type, $field_data) {
    foreach ($field_data as $k => $detail) {
        $field_key = _get_field_keys('field_' . $k);
        $field_key = $field_key[0];

        $node -> {'field_' . $k}[$node -> language][0][$field_key] = $detail;
        $form_state['values']['field_' . $k] = $detail;
    }
}

Then I run drupal_form_submit and it returns any errors from that and everything is great.

I'm having an issue with creating nodes which have a file upload field which uses the file u widget. I get the error:

Notice: Undefined offset: 0 in file_field_widget_form()

I had a look at the offending line (line 511 of modules/file/file.field.inc) and I can see why it occurs, the function file_field_widget_form has an argument called $element, which is supposed to have an index 0, but when I set up the form programatically, that index is not set up.

When I make a node of the same type using the web interface, I can see that the $elements array is set up with the 0 index before even submitting the form.

How do I rectify this issue, do I need to call something else before making my form programatically? I'm using Drupal 7 if it helps.

Looks like this is actually a problem in Drupal itself. In modules/file/file.field.inc the function field_form_get_state has a line like this near the bottom (just before the return statement):

$elements['#file_upload_description'] = theme('file_upload_help', array('description' => '', 'upload_validators' => $elements[0]['#upload_validators']));

The issue is a small if condition a few lines back which looks like this:

if (($field['cardinality'] == FIELD_CARDINALITY_UNLIMITED || $delta < $field['cardinality']) && empty($form_state['programmed'])) {
    $elements[$delta] = $element;
    ...
    some more stuff
}

Since I am submitting the form programmatically with drupal_form_submit(), it adds in $form_state['programmed']; thus, the control statement's condition fails, and $elements[0] does not exist.


Sessions / Cookies not working for user login, registration or shopping cart The Problem

One of our sites has recently broken. Users can't login or register, and the shopping cart isn't working either.

Drupal does not display any errors. Upon clicking the submit button for the forms, it simply refreshes the page as if nothing had happened.

It's just as if sessions have stopped working altogether, which is a little strange, no?

The rest of the site works perfectly well.

No Drupal updates have been performed and no new modules have been installed.

I've been reassured that this isn't a server problem, but I'm still (really) not sure about that. Since I don't have SSH access to the server, I'd like to be sure beforehand.

I'm just looking for possible causes/fixes, and if anyone has had experience with this before, great. Ultimately I will end up checking out the server, but is there any chance it could be caused by Drupal?

Things I've Tried:

I've checked /sites/default/settings.php for the $base_url and $cookiedomain variables, but they are set properly.

This is not a .htaccess problem, either. Regardless of whether I use clean urls or not (site/user or site/index.php?q=/user) it just doesn't work at all.

This is a very old question, but I stumbled on it while having the same issue.

In my case, the "rewrite" Apache module was turned off. I re-enabled it with:

a2enmod rewrite

I could access /user, but could not login (it would loop back, with no error message). I assumed that since I could access /user, my rewrites and htaccess were OK. I could login with "drush uli", but no form would work. Even weirder: in some pages that had query parameters (GET, ex: foo?test=1), the GET parameters would not be passed to PHP. I was searching all over the place, and the solution was pretty trivial :)


Is there any option to add file upload/attachment field in webform? Is there any option to add file upload/attachment field in webform for Drupal 8?

My webform version is 8.x-5.0-beta7+20-dev

Will need to define the private file system to get the web form upload fields. By default the private file system was not defined that's why the upload fields were not showing up. After defining the private file system through the settings.php file and clearing the cache I found several upload fields option to add in the form.


Path Auto Use Parent Tag, If it doesnt exist use current tag OK. I have Pathauto and Token

I have the following Tag Structure:

Drinks > Beer

I want to use path auto to make all nodes tagged with Drinks or Beer to have a URL of /Drinks/[Node:title]

So essentially I can use [node:field-tags:0:parent]/[Node:title] to get it to work correctly for all nodes tagged as Beer.

However if the node is tagged as Drinks then the parent does not exist and it will just return the node title. So in that case I would want to use [node:field-tags:0:name]/[Node:title]

So what I am looking for is something like this (if it exists):

[node:field-tags:0:parent ELSE node:field-tags:0:name]/[Node:title]

I have looked into custom tokens and can't figure it out. I was hoping there was a simple way to do this.

Ok I figured it out.
Use the Custom Token Module. Turn on PHP Filter in Core Drupal Modules
Create a new Custom Token in structure
Choose Nodeds in the Token Type
then use this code:

<?php
if (isset($data['node'])) {
    $parent = token_replace('[node:field-tags:0:parent]', $data);
    return ($parent != '[node:field-tags:0:parent]') ? token_replace('[node:field-tags:0:parent]', $data) : token_replace('[node:field-tags:0:name]', $data);
}
?>

It will return the parent tag of the first tag in the list and if none exist it will return the first tag in the list


Why are tokens added to image URLs? When I'm use the image_style_url(), function I got this token at the end of the URL: ?itok=yjoxJwQh.

Drupal uses a different token for styles and script, eg ?mk4o7m.

How does this affect caching and SEO?

This was a change that was introduced in Drupal 7.20, which addressed a denial of service vulnerability:

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

From the release notes:

  The security fixes in this release change all image derivative URLs generated by Drupal to append a token as a query string. ("Image derivatives" are copies of images which the Drupal Image module automatically creates based on configured image styles; for example, thumbnail, medium, large, etc.)

Drupal 7.21 revised this a little:

  Drupal 7.20 fixed a fundamental security flaw in the Drupal core Image module and therefore introduced incompatibilities with a number of contributed modules and sites (see the Drupal 7.20 release notes). To help mitigate the effect of these changes, an optional image_allow_insecure_derivatives variable was provided, which sites could use to turn off the security fix.

  Drupal 7.21 adds additional security protection for sites that use this variable. Although they will still not receive the full benefit of the security fix, they will now have protection against the most damaging and easiest-to-inflict vulnerabilities that were addressed in Drupal 7.20.


Any performance impact or reason to delete unused views? I have maybe 250 views on a site build and estimate that I use around 150 of them.

Is it ok to leave the extras there unused? It would take days trying to guarantee views aren't being used in custom blocks and in hooks for other views.

If they are never loaded/rendered, there should be no performance hit, except for the admin viewing the /admin/structure/views page since they get listed there.

Ok, maybe a slight performance hit, since the view table ID's in your DB is bigger, so it would take longer to find an ID, but if you're caching your Views you will be fine.


Why does external js only appear in header? D7, in a block, via custom module I'm trying to add a box.com file upload widget to certain pages in a block. The upload widget is an external js script. I'm adding it via a custom module, using hook_block_view,

switch ($delta) {
    case 'box_com_photo':
    $block['subject'] = t('Box File Uploads: Photography');
    $block['content'] = array(
        '#attached' => array(
        'js' => array(
            'scope' => 'content',
            'data' => 'https://app.box.com/embed/upload.js[custom widget code]',
            'type' => 'external',
          ),
        ),
      );
      break;

Regardless of the scope, it always shows up in the page header.

Suggestions??

Content isn't a valid region for scope, it can only be header or footer. See this documentation: https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_add_js/7

The render process runs drupal_add_js/css based on items inside of #attached.


Nested taxonomies in views I'm creating a site which has products, brands and affiliates. Products and brands are in the same taxonomy while affiliates are separate.

Products are terms that are children to brands. Affiliates are referenced in the brand term. I have the basic structure below for reference.

I'm trying to create a view that shows a users 10 favorite products along with the brand and url's for affiliates that carry the product. I've made my relationships in the view, but instead of displaying each brand with a link to the affiliates it duplicates the brand once per affiliate. In other words, if the brand has 3 affiliates it would show the brand 3 times with a single affiliate link under each.

How can I make my view combine the affiliates into a single result?

Product/brand taxonomy
-name
-affiliate(term reference to affiliates)

Affiliates taxonomy
-name
-logo
-url

For a quick fix you can make 'Distinct' in the view setting setting.


Programmatically changing theme after hook_custom_theme I'm trying to change the theme in code in drupal7.  hook_custom_theme is too early since I need spaces_init to have happened already.  The themekey module uses custom_theme so that's out.

The only method I've found so far is to change the theme callback using menu_alter.  What other options are there?

Both hook_custom_theme() and hook_init() are invoked from _drupal_bootstrap_full(), which contains the following code.

menu_set_custom_theme();   // It invokes hook_custom_theme().
drupal_theme_initialize();
module_invoke_all('init');

The reason of the order is explained in the comment before that code, which says:

  Prior to invoking hook_init(), initialize the theme (potentially a custom one for this page), so that:

  Modules with hook_init() implementations that call theme() or theme_get_registry() don't initialize the incorrect theme.
  The theme can have hook_*_alter() implementations affect page building (e.g., hook_form_alter(), hook_node_view_alter(), hook_page_alter()), ahead of when rendering starts.

It seems that your situation is a circular-reference situation, where an implementation of hook_custom_theme() depends from hook_init(), and an implementation of hook_init() could depend from the value returned from hook_custom_theme().

If you are sure that the result of hook_custom_theme() doesn't influence the code of spaces_init(), which doesn't need the theme to be initialized, then you could invoke spaces_init() in your hook_custom_theme() using module_invoke('spaces', 'init'), but that sounds like a hack, and subject of problems if spaces_init() is changed, and it actually needs a theme to be initialized before being executed.


Sorting Views by Day and Month only For a Birthday field using the Date module, Views sorts it by year.  This puts the dates in basically random order once you format it to display only the month and the day.  Could it sort by day and month only?

Extra bonus question: Could Views sort the Birthdays in context of the current day so the upcoming Birthdays float to the top?

Never used this module, might be worth looking into. It has Views integration.
Birthdays

The Birthdays module allows users to add their birthday to their profile. It also lists birthdays on a seperate page and in different blocks. Users can receive an e-mail on their birthday automatically, and the administrator can receive periodic reminders of who are having their birthday. Uses Profile module from core.


How to add/modify new taxonomy terms in node edit form? (taxonomy type is not tag) For example, when adding/editing a node, if a needed taxonomy term(category) doesn't exist, then for the user with right permission, he/she can then add a new term without leaving the node editing form? The term should be hierarchical not like tags, for example the category of the content.

I believe I saw a module which can handle this type of thing by providing a button to create new taxo

Thanks!

May be you are looking for Taxonomy Other module ?


How do I enable pagination on a taxonomy term page I have a taxonomy term page displaying node teasers. I would like to know how I can enable pagination on it?

Thanks

There is a default view for that. If you have installed Views module, you can just enable the view named 'Taxonomy Term', which is disabled by default.

Then you can adjust the pager settings in the view configuration interface.


Problems trapping AJAX'ed form input click event Using Drupal 7.x w/ jQuery 1.4x, I'm trying to trap the click event when I click on a submit input of an AJAX form generated from this Commerce AJAX Cart module.

In my custom.js behaviors file, I have the following code.

$(".form-submit").click(function(){
    alert('test');
});

The alert doesn't get displayed and I have no clue as to why. I load my custom.js file from template.php using the following code.

drupal_add_js(path_to_theme() . '/scripts/global.js', array('weight' => 200));

I tried lowering 200 down to insanely low levels just to test if weight had anything to do with any of this, but nothing I tried helped.

Any ideas as to why this click event isn't working would be helpful.

Because the form is being loaded via ajax, your click handler is not binding at the right time. You need to use Drupal.behaviors, the context argument, and possibly the one() method to attach this.

Or a less drupally (but better jQuery) solution would be to use delegated events like

$(document).click(function(event)) {
  if ($(event.target).is(".form-submit") {
    alert('test');
  }
});

Note: delegated events are way more elegant in modern jQuery, the on() method is great for this. But the above is probably the best you can do in jQuery 1.4.


Is there a product.tpl.php for ALL product types in Drupal Commerce? Or do you need product-type1.tpl.php, product-type2.tpl.php, etc? I would like to theme every single product on the site but there are multiple product types.

You could do the following in your theme processing...

function YOURTHEME_process_node(&$vars) {

    //dsm($vars);
    //dsm($vars['theme_hook_suggestions']);

    // If some node type then...
    if ($vars['node']->type) {
                // add a template suggestion
        $vars['theme_hook_suggestions'][] = 'node__product';

    }

}

Then you add a template file 'node--product.tpl.php'.


Add inline widget to product display I am trying to integrate our Drupal 7 Commerce install with Digital River's where-to-buy widget.

All I need to do is add a little JS to the product page, with a script variable set to the product sku.  On page load, this inline JS runs and adds a button that when clicked will pop-up a lightbox with where-to-buy information.  This script has a variable that requires a SKU to be entered.  If I add the snippet to my node-template it works fine.

HOWEVER, I have several products on each product display, and I have 2 product attributes that can be selected.  This, of course, refreshes the node/entity field values in my page, like the title, a product image and so forth.  This will not refresh the sku parameter of my javascript snippet though, so my WTB button does not update.  IE, if I did something like this:

<script type="text/javascript">
          pswtb.loader.show({
            widgetConfigurationId: "3a4acc53-216e-48da-8e92-bfaeb58168a7",
            sku: "US_<?php print trim($content['product:sku']['#markup']) ?>"
          });
        </script>

I discovered that it would initially load but the product:sku wouldn't change as I selected a new attribute.

So, I also discovered that my values would update if they were displayed via the render() function.  So, if I just did this:

<?php print render($content['product:sku']) ?>

I would get an element that updates 'properly' when a product attribute is selected.  It does, however come with a lot of div's wrapping it, so I can't use it as a parameter in my script,and I didn't want to override the 'sku' field template because I need that sku elsewhere on the page, and even overriding the template, I would still get a wrapper around it.

Ok, so my next attempt was to create a 'virtual' field, using the virtual_field module.  This just lets you have a dummy field that doesn't get stored anywhere but still lets you create custom templates and specify display formatters.  I created a dummy field that just contains the product sku.

Using this, I created a custom field template (field--field-product-wtb.tpl.php) for this virtual field like so:

this will update: <?php print render($item); ?>
but this gets stripped out:
<script type="text/javascript">
   pswtb.loader.show({
     widgetConfigurationId: "3a4acc53-216e-48da-8e92-bfaeb58168a7",
     sku: "US_<?php print render($item); ?>"
   });
</script>

And then in my node template, I just do this:

<?php print render($content['product:field_product_wtb']) ?>

It works on initial load, and when a product attribute is selected, the sku does change (the 'this will update' part) but the entire script tag gets stripped out and my button disappears.  I guess because it gets filtered via some xss protection, but I haven't tracked it down.  As near as I can tell, this is because when content on a page is updated via ajax, the HTML returned from a tpl file is sanitized and things like script tags are filtered out.

Now I'm at a loss as to how to get this to work.

You could probably do something like this:

Add hidden form element with product SKU
Read the SKU in a JavaScript Drupal.behavior

The key is making the SKU available in the DOM and using Drupal.behaviors to read it, as they run / are reattached after the AJAX form update.

i.e:

/**
 * Implements hook_form_FORM_ID_alter
 */
function MYMODULE_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state){

  // Add a hidden SKU element to the add to cart form
  if (isset($form_state['default_product']->sku)){
    $form['product_sku'] = array(
      '#type' => 'hidden',
      '#value' => $form_state['default_product']->sku,
    );
  }

}

Then in your JS file

(function ($) {

  Drupal.behaviors.pswtb_loader = {
    attach: function (context, settings) {
     if($('input[name=product_sku]').length > 0){
       pswtb.loader.show({
         widgetConfigurationId: "3a4acc53-216e-48da-8e92-bfaeb58168a7",
         sku: "US_" +  $('input[name=product_sku]').val();
       });
     }
    }
  };

})(jQuery);


How to sort Apache Solr search results? I want to make possible for the user to SORT Apache Solr results based on some taxonomy terms.How can I do that?
I also want to make possible for a user to change the number of the results on the page.
How can I achieve both of them?
Thanks in advance

I good way to utilize Solr for search with Drupal, is to use the Search API, is has a Solr integration module, which will allow you to setup a View with exposed filters and full text search. With the flexibility of Views, you should be able to setup the view to allow the users to sort as they wish.


Sort with entityTypeManager I'm running an app where I am searching for every nodes of a given content type.

$nids = \Drupal::entityTypeManager()
  ->getListBuilder('node')
  ->getStorage()
  ->loadByProperties([
    'type' => 'courses',
    'status' => 1,
]);

I'm searching for a way to sort the results among a custom field of my nodes.

EDIT:
I do not understand what's going on.
Thanks to @4k4, I wrote this query:

$query = \Drupal::entityTypeManager()
    ->getListBuilder('node')
    ->getStorage()
    ->getQuery();
$query->condition('type', 'post');
$query->condition('status', 1);
$query->condition('field_category', $k);
$query->sort('field_ordering', 'ASC');

$nids = $query->execute();
$nids = Node::loadMultiple($nids);

A var_dump on $r[1] prints nothing. Same for $r[2]. But $results contains my results. What's going on ?
The sorting doesn't work by the way.

The change record says if you have entityTypeManager injected, use

$query = $this->entityTypeManager->getStorage('node')->getQuery();

For non-OOP code, $query = \Drupal::entityQuery(); is not deprecated and can still be used.

The linked example for sorting an entity query by using $query:

$query->condition('type', 'blog_post')
  ->sort('field', 'DESC');
$nids = $query->execute();


URLs aren't working after site migration My problem is two fold:

After migrating my site, many of the URLs aren't working, and producing 404 errors. But the main landing page is working, and so are most/all of the features on the main page.
My configuration for custom 404 error pages are being ignored, and were working before copying the root of the web server files over. This I'm not so worried about.

These are the steps I used to migrate the site:

mysqldump the database from the originating server.
Import the database to the new server, using the same mysql credentials.
Copy the root of the web server files over to the new location.

This is my setup:
CentOS6
nginx
MySQL
php, php-fpm
Drupal 7

The only real difference between the originating server and the target server is that the originating server is centos5.

I am not a drupal expert, but I did some searching and I keep coming across "clean urls". I'm not exactly sure what that is.

Is there a better way to migrate a drupal site, or is there something I did wrong?

This indeed sounds like a clean URL problem.

Standard Drupal URLs use query strings like: www.example.com/?q=string/string/site
Clean URLs rewrite this to www.example.com/string/string/site which is better for SEO.

Check the browser's adress bar to see if clean URLs are working. If not and if you used them on the previous install, you need to either deactivate them in drupal or get them working again. You need to activate it in settings and use correct .htaccess with Clean URLs rewrite rule.

The reason why the home page is working is that there is no query string in www.example.com/


Hide block if no submenu in Twig I'm creating a node--page.html.twig and I'm using twig_tweak to help render a block for my sidebar to display the sub-menus. Is there a way to hide it if the page doesn't have any submenus?
Here's my code:

    {{ drupal_entity('block', 'mainmenu', check_access=false) }}

Is there some sort of if statement I could use to hide the block if the page has no submenu?
Thank you!

I generally handle this sort of thing like:
// First render my content and set it to a variable.
{% set submenu = drupal_entity('block', 'mainmenu', check_access=false)|render %}
// Next, check if the variable have content.
{% if submenu %}
  // If variable has content, render with wrapping div(s).
  <div class="my-wrapping-div">
    {{ submenu }}
  </div>
{% endif %}

It's important to render the submenu whether or not it has any displayable content to make sure it's cache settings are bubbled up.
Note: this will only work if whatever your rendering returns no html. If you're seeing some wrapping divs, etc return, but no content, you can alter your if statement like {% if submenu|striptags|trim %} to strip html and check for only content.


Drupal CSS is not loading after server move After moving the server, my CSS files don't work. When I open them in a browser, an error shows up:

  SmartOptimizer Error: Could not create cache file(cache/so_11966173eab0271ad5607eadd11bf298.css.gz).

I have SmartOptimizer Installed, and I don't know if I need to change the settings.

How can I fix this?

This doesn't really sound like a Drupal-specific question. That link doesn't even point to a Drupal contrib module.. Have you tried running through the install instructions again?

If you haven't "SmartOptimizer needs write access to smartoptimzer/cache folder. Make sure it's writable." looks pretty telling.


hook_views_pre_render() to override results of a view I have a view used on a site to show the latest 4 nodes (in teaser mode) of a content type of 'article'.

On some Article pages the administrator can override some or all of the 4 nodes to be shown in this view.

I have an entity reference field in this content type where they can optionally select up to 4 nodes to feature instead, then in my template.php I have the following code:

function adaptivetheme_subtheme_views_pre_render(&$view) {
    if($view->name == "related_articles") {

        if ((arg(0) == 'node') && is_numeric(arg(1))) {
            $node = node_load(arg(1));
        }

        if(isset($node) && $node->type == 'article') {

            foreach($node->field_related_articles['und'] as $key=>$override) {
                if(!empty($override)) {
                    $view->result[$key]->nid = $override['target_id'];
                }
            }

            dsm($view);
         }

       }
}

I can see in the DSM output that the values in the results array of the view are changed correctly, but the actual rendered view has blank spaces in place of the inserted nodes.

Where am I going wrong?

Per the first two comments here you should probably use hook_views_post_execute. If you have paged data this will cause issues.


How to create page of multiple entity reference fields I'm making a kickboxing archive. I would like to create a content type 'Fights'. But something isn't working.

A fight takes place between 2 fighters (content type 'Fighters'), at an event (content type 'Events'), in a venue (content type='Venues').

I need to select two fighters. I have added an entity reference of 'field_fighters'. Now I want to add another entity reference of the same field for fighter 2, but I can only refer to this field once. How can I do this?

In the parameter of your entity reference field, you can set the number of values allowed. Just set it to 2 to answer your needs.


How to conditionally load JavaScript with template.php I have a content type that has involves some js magic for every node. How can I code it into template.php so that it is loaded only on display of the content type? I don't want the js to load uselessly on every page. My php skills are pretty shallow.

js_injector module lets you control which pages you want to include your code.

CSS_injector does the same for css.


How to add title of node (where order form was placed) to custom line item order in commerce Alright I added a custom line item order form to a node. I read that somewhere the link to the node on which the order form was used gets saved within the order, but I need the title of the node where the order form was used to place the order. Currently I added a entity reference field which uses a view to just display the title of the actual node and the user needs to select the value manually. But I want this to be automatic and hidden if possible, how could I go about it?

Actual try: I tried to setup a rule to make this possible, but I am not able to do it since I am not able to access the data of of my content node and the form at the same time. I tried it with a simple rule, a component and last but not least through the rules forms module

I found a pretty bad solution: I added to the node template the following jquery, which really just writes the node title of the current node to a field in the line item.

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script>
    $(document).ready(function(){
        var title= $('#page-title').text();
        $('#your-line-item-field-id').val(title );
        $('#your-line-item-field-id').prop('disabled', true);
});
</script>


Correct way to render a modules output through a template? I usually do exclusively functionality on a site, and as such I'm familiar with php and Drupals APIs, but I'm mostly lost in the theming layers.

I find myself with these pieces of code, that "work", but doesn't look quite right to me.

// ------ Actual USE of #theme -------
$block->content = array(
  '#theme' => 'MODULE_more_information',
  'dataA' => $dataA,
  'dataB' => $dataB,
  'dataC' => $dataC,
);
return $block;

// ------ hook_theme to attach the #theme to a template -------
function HOOK_theme($existing, $type, $theme, $path) {
  $base = array(
    'render element' => 'element',
    'path' => drupal_get_path('module', 'HOOK') . '/templates',
  );
  $theme = array(
    'MODULE_more_information' => array(
      'template' => 'MODULE-more-information',
    ) + $base,
  );
  return $theme;
}

// ------ Actual template -------
<?php
extract($element);
?>

<?php print $dataA ?>

<?php print $dataB ?>

<?php print $dataC ?>

What gives me the idea that something is amiss is that the author manually runs extract(), which I've never seen a template do before.

Canonical examples of how to do this "right"?

To be honest, aside from the use of extract() (which is obviously bad in and of itself), I think the code is perfectly valid, and respectful of Drupal's processes/conventions.
There are two different ways to pass variables to theme functions in Drupal 7, both provided as an argument to a theme definition in hook_theme(). They are variables and render element.
I can't possibly explain the difference between these two better than the hook_theme() docs:

Use 'render element' if you are theming a single element or element tree composed of elements, such as a form array, a page array, or a single checkbox element.
Use 'variables' if your theme implementation is intended to be called directly through theme() and has multiple arguments for the data and style; in this case, the variables not supplied by the calling function will be given default values and passed to the template or theme function.

In your case you're theming a render array, rather than calling theme() directly, so render element is the one to use.
When you use a #theme property on a render array, the entire element (in your case $block['content']) is passed through to the theme function/template file. The name of the variable that you have access to in the template file is the name you have given to render element in the hook_theme() definition.
So if your hook_theme() defines 'render element' => 'my_lovely_var', you'll have access to the render array as $my_lovely_var in the template file.
I suspect that the author of your code was just taking a small shortcut so he/she didn't have to access the $element array directly with code. Without the use of extract() the template file would/should have looked like this:

<?php print $element['dataA'] ?>

<?php print $element['dataB'] ?>

<?php print $element['dataC'] ?>

Just for posterity, this is the same code re-written to make use of variables instead:
The same code using variables would look like this:
// ------ Actual USE of #theme -------
$args = array('dataA' => $dataA, 'dataB' => $dataB, 'dataC' => $dataC);
$block->content = array(
  '#markup' => theme('MODULE_more_information', $args)
);
return $block;

// ------ hook_theme to attach the #theme to a template -------
function HOOK_theme($existing, $type, $theme, $path) {
  return array(
    'MODULE_more_information' => array(
      'template' => 'MODULE-more-information',
      'variables' => array('dataA' => '', 'dataB' => '', 'dataC' => ''),
      'path' => drupal_get_path('module', 'HOOK') . '/templates'
    )
  );
}

// ------ Actual template -------

<?php print $dataA ?>

<?php print $dataB ?>

<?php print $dataC ?>

You could even use the following, slightly different, method to build up the block content when using variables:
$block->content = array(
  '#theme' => 'MODULE_more_information',
  '#dataA' => $dataA,
  '#dataB' => $dataB,
  '#dataC' => $dataC,
);
return $block;

This second method makes the block more re-usable as the theme function hasn't already been called, and other parts of the system can still alter the individual elements of the block.


Programmatically Change Administrative Area in AddressField I have some external data that I have introduced to Drupal for a users address (not in an address field). I am setting it so that when a user loads the checkout page in commerce their info is populated as the default field values.

How do I change the State (administrative area) to match the country that is set? Right now, if I have it set to Australia for instance, the State field is still set to United States relevant states.

Code Example:

    $form['customer_profile_billing']['commerce_customer_address']['und'][0]['#address']['first_name'] = $firstname;
    $form['customer_profile_billing']['commerce_customer_address']['und'][0]['#address']['last_name'] = $lastname;
    $form['customer_profile_billing']['commerce_customer_address']['und'][0]['#address']['thoroughfare'] = $street;
    $form['customer_profile_billing']['commerce_customer_address']['und'][0]['#address']['locality'] = $city;
    $form['customer_profile_billing']['commerce_customer_address']['und'][0]['#address']['administrative_area'] = $state;
    $form['customer_profile_billing']['commerce_customer_address']['und'][0]['#address']['postal_code'] = $zipcode;
    $form['customer_profile_billing']['commerce_customer_address']['und'][0]['#address']['country'] = $country;
    $form['customer_profile_billing']['commerce_firstdata_billing_phone']['und'][0]['value']['#default_value'] = $phone;

Here is an example, You need to use ajax. I think you will just need to alter the form structure a bit from what I have but the basic logic is there.

$country_list = array(0=>'USA',1=>'Canada');
$value_country = isset($form_state['values']['country']) ? $form_state['values']['country'] : key($country_list);

$form['country'] = array(
    '#type' => 'select',
    '#title' => t('Select Country'),
    '#options' =>  $country_list,
    '#ajax' => array(
        'event' => 'change',
        'callback' => 'mymodule_ajax_callback',
        'wrapper' => 'name_replace',
        ),
 );

$form['state'] = array(
    '#type' => 'select',
    '#title' => t('Select State'),
    '#prefix' => '
',
    '#suffix' => '
',
    '#options' =>  mymodule_find_states($value_country), //pass country, run query, return correct states
    '#default_value' => isset($form_state['values']['country']) ? $form_state['values']['country'] : '',
 );

Add this function make sure this function is NOT inside form_alter function

function mymodule_ajax_callback($form, $form_state) {
    return $form['state'];
}


How to integrate the link embedded in custome HTML(using ) to breadcrums? Home >>

On the Home page I have created a div and inserted some text there and  one of word I have added in Text area using CKeditor is Link to page-1, so if i click that link it leads to me to page-1, so breadcrumb shows,

Home >> page-1

Now in the text area(body) of page 1 I have added another word Link to Page-2, page-2 is a page created using the views. so after clicking this second link breadcrumbs shows,

Home >> page-2

But I want Home >> page-1 >> page-2 which is the sequence in which I arrived on that page

although I have added this all links in the Body of text area using , what I can do so breadcrumbs read this and make in the sequence as I want, In short how can we customize the breadcrumbs.

you can either extend the breadcrumb array with your link in your theme with theme_breadcrumb  (further information here) or drupal_set_breadcrumb in your module, or use one of the many modules around breadcrumb. maybe custom breadcrumbs fits your needs.

you can extend the breadcrumb array with html, like:

$breadcrumb[] = l(t('My first page'), 'node/x');

or push it to the second postion with array_splice, like:

array_splice($breadcrumb, 2, 0, l(t('My first page'), 'node/x'));


The website encountered an unexpected error due to installing custom module I have created and installed custom module without additional code[with mymodule.info and mymodule.module].But after I created

  mymodule.links.menu.yml and mymodule.routing.yml i am grtting error like "The website encountered an unexpected error" code mymodule.links.menu.yml

   mymodule.admin_form
     title: Upload IELTS Test Dates
     parent: cedar.admin_index
     weight: 100
     route_name : mymodule.admin_form

and code inside mymodule.routing.yml

 mymodule.settings:
   path: '/admin/config/services/migs'
   defaults:
     _controller: '\Drupal\quotesapi\Controller\MymoduleController::settings'
     _title: 'My module settings'
   requirements:
     _permission: 'administer site configuration'

I checked the watchdog and found a RouteNotFoundException. How do I fix this?

It looks like a simple naming error. Your route name in the links file is:

route_name : mymodule.admin_form

But in your routing.yml you have:

 mymodule.settings:

Update one or the other so they both match, clear the cache, and it should work.


Display a block on front page only How do I only show a block on the front page. I have  on only listed pages under block settings and it won't disappear on the second page. I've also added

$is_front
drupal_is_front_page

around the block and those don't work either. Renaming page to page--front.tpl.php didn't work either. Any suggestions on how to fix this? Also please be specific with your answers as I have no idea what to do and I hope this doesn't need a moldule as I'm trying to run a site with little running modules as possible.

Thanks,
Gregory S.

Your setup is correct.
On visibility settings > Show block on specific pages.
Selected: Only the listed pages:

<front>

Your problem might be that the second page is caching. And it is still showing on that page. Or you have another module conflicting and displaying the blocks.
Is your site publicly visible. Can you provide a URL?


How to lock in the Sort Order for view display? I've got a View of 10 images displaying inline, the first and last images are different (have rounded corners), and it is really important that the order for all 10 images is locked in. Is there a way to do this, without having to edit all the nodes in order to get them displaying in the correct order?

You want the Nodequeue module.

You can make a queue and add nodes to it an arbitrary order. All queues have an associated view that gets created, and can be used anywhere you use a view.


D7 Form Builder and Comment Forms I need to create a post/comment structure almost exactly like what you're looking at right now: original post with comments, subsequent 'answer' posts with their own comments. In response, I'm displaying a views page with a custom path displaying the original post (content type) and the subsequent answers (also content types). The issue lies with printing comment forms for each of the following nodes.

So far, I'm attempting to use the Views PHP field to print the comment form and failing pretty hard. There is D7 comment form doesn't submit relating to this, and Nikit's solution did produce a comment form on demand. However, this form does not submit or preview, submission just redirects the user to the node's comment reply page. Even now I do not understand how this method of calling drupal_get_form() works with two arguments.

So I turned to the trusty Drupal API to reference the drupal_get_form() function and saw that it doesn't take two arguments and returns drupal_build_form() instead. I thought that calling drupal_build_form() straight up might be more appropriate, since from what I could gleam off of the scarce user feedback said I needed to use a form_state['redirect'] of some sort to get users back to the original node page they posted their comments from. As expected however, everything I try returns a pile of errors and gets me nowhere.

The one spot of success was with the Commentsblock module that allowed me to place a real live comment form on a page and actually have the stupid thing submit a comment. While this works for the main content, I'm still at a loss for the subsequent 'answer' comments/forms. In ripping through the source code for the module I discovered comment_node_page_additions($node);, but this does not turn out any valid results either.

There are so many questions here:

How does one actually USE the Forms API (and to print comments)?
Should I be doing this in a .tpl file instead of Views?
Where does the second argument of drupal_get_form() go?
What exactly is the difference between drupal_get_form and drupal_build_form and how are they used?
Is $form_state['redirect'] called before either of these API calls or after?

This might seem like 'too much' of a question for a single thread, but I'm tired of posting partial questions and getting partial answers. In the interest of education, I would like to build some sort of tutorial either on Drupal.org or elsewhere so that this information can be made available to others in the same situation. Obviously I am not the best person to undertake this due to my massive lack of understanding, but maybe, just maybe with your help this can become a reality.

If you select the 'forms' tag and select its mini menu option 'info', you will see a link to the Drupal pages for the form API and a great basic explanation on how it is used.
You should not use PHP in the view. PHP in content of any sort presents a security risk. The best place to do this is in a custom module.
The form API provides documentation on both.
$form_state is used as central storage for all information about the form. Any part of the $form_state array can be read and written to by any function at any time.


After publish node send email to someone Let's say i have a custom module in D7 , i want to add a feature to  this .

the feature is : when a user publish a node send an email to someone .

   function sending_email_node_update($node){
    if (isset($node->original->status) && $node->original->status == 0 && $node->status == 1){
        drupal_mail('sending_email','email_action','soheilsadeghbayan@yahoo.com',language_default());
  }
}

function sending_mail_mail($key, &$message, $params) {
switch ($key){
    case 'sending_email_node_update':
        $message['subject'] = t('this is my action report');
        $message['body'][] = t('this is a reporting from sending email made by soheil') ;

        break;
}
}

Could you please help me how to do this ?

Why not just use Rules to do this. You'll have to watch a few tutorials to wrap your head around rules, but you won't have to re-invent the wheel or maintain any code.

If you need the custom module solution, check these out.

Check if node is being published:
How can I detect when a node is changed from 'Published' to 'Unpublished'?

Then, use drupal_mail() to send your emails.


Why should I not put content in the development environment? I've previously been told that I should not put content on Pantheon in the development environment.

The reason was not explained.

Can anyone think of any reason that this should be advised?

I can see that pulling/pushing a lot of content form the /files directory could be and issue but is there any other reason that anyone can think of?

I think that either what you were told was not explained correctly, or that you misunderstood.

You can put content on development environments. And you should, to test.

But that content won't be migrated to production. If you want that content on production, you'll need to create it on production. Or, you can create a migration strategy (using the Migrate UI for example) to migrate content between environments. But this generally takes a good bit of work, and isn't usually done.


How to set the path to images in ckeditor? I have a recurrent problem I can't solve.

when working in localhost I use ckeditor to upload images to the body field. These images are shown correctly.

Then after, I upload the site to the remote host and all those images links are broken.

The problem is that the drupal installation on my localhost is inside a folder in localhost like: http://localhost/mysite.com/

In the remote host all the images links have the mysite.compart of the url which of course is wrong. This is not solved by clearing caches.

Localhost (works fine)

http://localhost/mysite.com/sites/default/files/resize/icon-questions-180x127.png

Remote (with the wrong "mysite.com")

http://mysite.dde.oneserver.com/mysite.com/sites/default/files/resize/icon-questions-180x127.png

With no luck I tried with several configurations at: admin/config/content/ckeditor/edit/Full

UPDATE (trying with Pathologic module)
I added these lines in "All base paths for this site" in Pathologic setting at admin/config/content/formats/full_html:

http://localhost/mysite.com/ (this one is where the site was developed)
http://mysite.dde.oneserver.com (this one is where the site lives now)

I ALSO tried adding:

http://mysite.dde.oneserver.com/mysite.com

look the capture:

You might want to try Pathologic module to see if that works for you.

  Pathologic is an input filter which can correct paths in links and images in your Drupal content in situations which would otherwise cause them to “break;” for example, if the URL of the site changes, or the content was moved to a different server. Pathologic can also solve the problem of missing images and broken links in your site’s RSS feeds.


How to assign permissions to roles programmatically? I have some permissions that I would like to assign to some roles programmatically for easier installation.

Because I'm installing the module and creating both permission and roles, I don't have the role id's, where I want to set the permissions. So far I have only found ways to assign roles programmatically that need the role ID.

I wonder if I somehow could look up the roles with their name (string), retrieve the role ID and then assign permission. It just doesn't feel right.

Features is pretty handy for stuff like this. However, if you do need to create roles and add permissions programmatically, you don't have to go digging through the database on your own.

When you create a new user role with user_role_save(), it will update the object you passed in with the new user role id that was assigned. You can see an example of this in the standard_install() function in the Standard installation profile.

$admin_role = new stdClass();
$admin_role->name = 'administrator';
...
user_role_save($admin_role);
user_role_grant_permissions($admin_role->rid, array_keys(module_invoke_all('permission')));

This example shows that you can create a new user role, then access its rid property, which was filled in by user_role_save(). It also shows how to add permissions to that role with user_role_grant_permissions(). In this case, it's granting the 'administrator' role all available permissions.

If you need to get the id of a user role created by someone else, you can use user_role_load_by_name() to get the object for that user role. Then you just grab the id with $role->rid.


Modifying behavior of "You Saved..." info in cart when attributes are chosen I'd like to modify/eliminate the "you saved" text/info on the Cart page when a certain attribute (or attributes) has been chosen for the product in the cart.

This is the code from uc_cart.module that appears to handle the "you saved" info:

      $totalfield = '
'.uc_price($display_item['#total'], $context).'
';
  if ($item->list_price > $item->price) {
    $savings = $item->list_price - $item->price;
    $savings = $savings * $item->qty;
    $totalsavings += $savings;
    $totalfield .= '
You saved '.uc_price($savings, $context).'!
';
  }

And I'd like to add something like "Do not display the 'You Saved' div if Option X, Option Y, or Option Z have been chosen".

Can anyone here direct me on how to accomplish that? Or could a jquery snippet such as this provide the same "hide" functionality?

(function($) {
 $(document).ready(function(){
if ($('.item-list > li:contains("sometexthere")').length > 0) {
    $(".cart-savings").addClass("newclass");
}
});
 })(jQuery);

The "newclass" would have a CSS display:none property that would hide the cart-savings div if the item-list (attribute options listing) div contained one of the words that is only used in these options. Or, it could be flip-flopped, where the div is already hidden via CSS, and the jquery adds a new css class that unhides it via "display:block".

Thanks!

Doing this in jquery is probably going to be the quickest way to achieve this, especially since you're dealing with custom code. The jquery code you posted is close, but you need a different approach to test if the list-item contains text:

$(document).ready(function(){
    if ($('.item-list' + ':contains("someothertext")').length != 0 ) {
        $(".cart-savings").toggle();
    }
});

Also, note I used the toggle() function here which is a quicker way to determine visibility than adding / unadding a visibility class.

You can verify the above code here: http://jsfiddle.net/JZnPq/


Drupal 7 adding rel to the href's of Login and Registration I'm using Lightbox as a modal box solution and have been having
an issue trying to get modal windows for the default Login and
Registration links. I'm trying to access from inside a module that
I"m currently using to make all the changes. I've tried several
other "Box" solutions and Lightbox seems to be what I'm looking for,
but I cannot figure out the hook to add rel='lightbox' to login and
reg. Could someone point out what it is for me?

EDIT I tried using this in my base theme, which will give me a
modal on both reg and login, but shows an empty form?

function spti_base_preprocess_page(&$variables) {

/* .....stuff..... */

    // add the system user-menu into the page as its own thing
    $variables['platform_user_menu'] = menu_navigation_links('menu-platform-user-menu');

    foreach($variables['platform_user_menu'] as &$hijackLinks) { $hijackLinks['attributes']['rel'] = 'lightframe'; }

    $variables['page']['platform_user_menu'] = array(
      '#theme' => 'links__system_user_menu',
      '#links' =>   $variables['platform_user_menu'],
      '#attributes' => array(
        'id' => 'platform-user-menu',
        'class' => array('links', 'inline', 'clearfix'),
      ),
  );

/* .....stuff..... */

}

Yes you could spend time tearing apart templates, and hacking in the required code, I would say the cleaner, 'more drupal' solution would be to use a combination of

Menu and menu items
The module menu attributes

From the project page:

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


Module for cropping user picture immediately I'd like users to be able to crop their user pictures immediately. That means:

After selecting the image file, it gets uploaded immediately (as opposed to waiting for the user to submit the entire profile edit form) and some kind of overlay, div, etc. appears that allows the cropping to be done.

As far as I can tell, a module does not exist that provides this functionality. If I'm wrong, please direct me to the module I'm looking for. If I'm right that it doesn't exist, what tips would you offer? Is there a module that will help get me part of the way, i.e. immediate upload, and then I can implement the rest (like just the cropping)?

The best solution I found is to use the Imagefield Crop module. This does NOT work on profile pictures, so simply disable user pictures and then add an image field to the user account fields. It will work with that.


Hook_node_view() to print a table? I'm working on my first module. What I'd like to do is add this table http://pastebin.com/A1cbya5m function's output to the bottom of nodes. I'm not sure how to do this using hook_node_view()'s '#markup' field. I can do one line but nothing this complicated. I tried doing '#markup' => print_payment_table(), but it didn't work.

Any ideas?

Your function isn't actually returning anything. So

'#markup' => print_payment_table()

will result in markup being empty. I've noticed in your function you have a lot of print statements. It would better to build a string variable in your table construction. Like:

$string = "
";
$string .= "
".$stuff"
";
$string .=
;

then at the end of the function, return $string.

EDIT: -----------------------
your functions should be seperated, not defined iside of each other.

So:

function table_builder($node){
//do stuff
   return $stuff;
}

function *my_mod*_node_view($node, $view_mode, $langcode){
   $node->'#markup' .= table_builder($node);
}


Detecting jQuery UI version in module I am developing a module in Drupal 7.56 that is going to rely on jQuery UI 1.12.1. I want my module to check to see if that version is installed on the site, if it is not I am going to use drupal_add_js() to add the correct version. I don't want to just add the js file if it already exists in the system.

I do not have access to the site the module is going to be installed on. I want this module to be used on many different sites and don't want the module to add the js if it is already there.

What is the best way to do this?

If you call drupal_add_js() without parameters it will return an array of all the JavaScript already installed. You can iterate over the elements to look for the jQuery UI version you need. For example

  $installed_js = drupal_add_js();
  foreach ($installed_js as $file => $details) {
    if (preg_match('/jquery\.ui/', $file)) {
      $version = $details['version'];
      break;
    }
  }
  list($major, $minor, $update) = explode('.', $version);
  if ($major != '1' && $minor != '12' && $update != '1') {
    // Add drupal_add_js call here
  }

You might need a more robust regex to check for a wider variety of possible filenames but the above code should work in principle. I should also point out, it's not totally robust - if for some bizarre reason the file was named blah.js, this approach would not find it, so your module's jQuery code should also check to make sure the right version is loaded.


Views content pane not showing in panel for some users I have a view content pane displaying a node of a certain content type. This content type contains entity reference fields which are rendered as nodes on in the view field settings. On this view, I have a contextual filter of type "Content: NID" with "Provide default value" selected and "Content ID from URL" selected in the drop-down.

I created a panel page over-riding the node template, and a variant with 2 selection rules:
1) Node being viewed is this content type, and
2) "Node: accessible - Logged in user can view Node being viewed."

I am using two users to test - the admin user, and a test user.

When I view this panel page as an admin, with 'bypass node access' permission, I can see the panel with the content pane, and the node and the referenced nodes that are present in the view.
In the node access table, the node is listed with the correct realm and gid.
Debugging output shows that my test user has the correct grants (at least one grant contains realm and gid that matches the node_access records), and should be able to view the node.
If I disable the panel, my test user CAN access the node directly, as well as the nodes referenced in the entity reference fields.
I made a copy of the content pane display (as a view page, with url), and my test user CAN access the view, and all nodes on the view.
When my test user tries to view the panel page, he sees the OTHER panes on the panel (which I assume tells me that "logged in user can view node being viewed" is TRUE, as the variant IS being displayed).
One strange thing that I noticed, is that when I try to preview the view by manually adding the NID argument, I get nothing - no query being displayed, and no content being rendered, but this is for the content pane, not the view page display with url.

However, the test user can NOT see the views content pane embedded in the panel, while the admin user can. The pane simply does not render, and the "No results behaviour" of the view, which is set to display a message, does not render, either. It is just blank.

Anyone know why the content pane would not render? Is there some permission that I'm missing, or some setting on the views content pane screen? Or some setting on the panel variant configuration, or the pane configuration? I don't see anything that should hide this pane.

The issue that I was having had to do with the fact that I was using Views PHP to enter PHP code as the contextual filter validator. It should have been on only one display, but it was saved in the master, and was added to all displays, including ones which were over-ridden. I removed it entirely, from the master, but it still didn't fix it. It appears that there is a bug in either the views php module, or the view module (or possibly ctools), in which the validation stayed in the views cache, even after removing it, saving the view, and clearing cache.

To fix this, I exported the view, manually removed the validation code, and re-imported.

Hope that helps the next person who might run into this very obscure problem.


How do I clear cache? On my new site all works fine so far, except that when I try to clear cache (e.g. class cache or table cache or just flush all caches) from the UI. I sometimes get an error about exhausted memory (64M on production, 128M on test site).

Are there any alternatives to clearing cache from the UI? Can I just delete all records from the database tables starting with "cache" and obtain the same result?

You can manually DELETE FROM the cache tables, though doing this with cache_form can result in wonky behavior with people in the middle of form submissions.

However, I suspect the problem isn't with clearing the cache, rather with all of the activity involved in rebuilding everything that gets cached.

Long term, you would be safest to

Disable modules you don't need
Bump up memory_limit for PHP

64M is likely on the low end if you have a lot of modules enabled.  You should really download  the Performance module, enable Summary Logging, run your site for a while, and see where you land on memory stats.  Also note where these go when you clear caches and perform other admin functions.


Switching from Panopoly I'm wondering if anyone has experience switching a Drupal installation away from Panopoly. I have a site built on Panopoly, but I'm finding the upgrade situation stifling. I'd rather have independent control of which modules are installed. So I'm looking to move to a vanilla core installation and do all the modules by hand. Anyone with firsthand experience doing this? I'm just going to give it a whirl and see how it goes, but any tips would be appreciated. Thanks!

You can use Profile Switcher

  Used to switch between install profiles found in /profile directory.
  This module is useful for moving an existing site to distribution.

I had the same problem last year you can check it out at - Changing from a Profile to Standard profile after the installation


How to create charts in Drupal while working offline that integrate with the Quiz module? I'm now working on a local offline network website, which needs a graphical chart report for their quiz. But since it's offline I cannot use the (interactive) Google Charts API as a charting engine.

I tried FusionCharts already for the Webform Report module, but it has no integration with Quiz.

Any suggestions would be great.

You can use Flot since it has views integration as Quiz.
Flot can be used offline while Google charts can't because of their TOS.


How to add unique class to each checkbox elements I am displaying checkboxes using form API in Drupal 8. For functional and theming purpose I need to add unique custom class to each checkbox element. Is there any way to add classes to each checkbox elements on wrapper/label/input level?

Here is my form API for checkbox element.

  public function buildForm(array $form, FormStateInterface $form_state,
   $items = array()) {
    $tids = [5,8,7,9,3,1,45];
    $terms = Term::loadMultiple($tids);
    foreach($terms as $term) {
        $name = $term->getName();
        $options[$term->id()] = $term->getName();
    }
    $default= [5];

    $form['category_type'] = [
        '#type' => 'checkboxes',
        '#options' => $options,
        '#default_value' => $default,
        '#ajax' => [
            'callback' => '::searchCallback',
            'method' => 'replace',
            'effect' => 'fade',
        ],
    ];

    return $form;
 }

I have tried to theme through hook_prepeocess_HOOK() but its not rendering in final my custom class.

   function mytheme_preprocess_input(&$variables) {
      $element = $variables['element'];
      if (isset($element['#id']) && $element['#type'] == 'checkbox') {
        $variables['element']['#attributes']['class'][] = 'my-custom-class';
      }
    }

Any help on this will be highly appreciated. Thanks in advance

I think the Form Options Attribute module will solve this for you.  It allows you to add option attributes in the form element render array.  Below is the example from the module page.  It also supports checkboxes as well.

$form['states'] = array(
  '#type' => 'select',
  '#title' => t('States'),
  '#options' => array(
    'AL' => t('Alabama'),
    'AK' => t('Alaska'),
    'AZ' => t('Arizona'),
    'AR' => t('Arkansas'),
    // ..
    'WI' => t('Wisconsin'),
    'WY' => t('Wyoming'),
  ),
  '#options_attributes' => array(
    'AL' => array('class' => array('southeast'), 'data-bbq-meat' => 'pork'),
    'AK' => array('class' => array('non-contiguous'), 'data-bbq-meat' => 'salmon'),
    'AZ' => array('class' => array('southwest'), 'data-bbq-meat' => 'rattlesnake'),
    'AR' => array('class' => array('south'), 'data-bbq-meat' => 'beef'),
    // ...
    'WI' => array('class' => array('midwest'), 'data-bbq-meat' => 'cheese'),
    'WY' => array('class' => array('flyover'), 'data-bbq-meat' => 'bison'),
    ),
  '#attributes' => array('class' => array('states-bbq-selector')),
);


Featured Content block inside node I'm using Drupal 7 and trying to include the Featured Content block between the write up and the comments, i.e. I want it inside a node.

I tried the method explained here, but am not getting the block appear.

This is the code I've used in my node.tpl.php

$block = module_invoke('featured_content', 'block_view', '1');
print render($block);

The featured content block's URL contains this:

admin/structure/block/manage/featured_content/1/configure

Any suggestions? What could I be missing out?

As suggested in another post, I used this code:

$block = block_load('featured_content', '1');
$output = drupal_render(_block_get_renderable_array(_block_render_blocks(array($block))));
print $output;

This worked perfectly!


How do I cache the result of db_query()? I used views_get_view_result() to get results from a view because it was convenient at that time. The query result rarely changes; I could use views caching for 6 days.

If I wanted to convert it to a call to db_query() how could I enable caching?

Doesn't mattter for caching if you use views or db_query(). Caching works always the same, how the data is fetched when the cache misses is completely up to you.

Build a cache ID to identify your cache entry. Can be a simple, hardcoded string or something complex based on arguments and so on.
Check if can load from the cache.
If not, rebuild data and put it into the cache with the desired expiration time.

To see some examples, you can look at the functions that use cache_get(), for example variable_initialize().

If your function is called multiple times then you probably want to combine it with a static cache, see for example archiver_get_info(). And if the data rebuilding is really slow, you can prevent it from happening multiple times by using the locking framework as variable_initialize() does.

Note that caching a single query only makes sense if it's a slow one, because a cache_get() is also a db query unless you use an alternative cache backend like Memcache.

And lastly, Views has caching already built-in and can be configured in your view. So that might be an option as well.


Not possible to drush sql-sync sqlite to mysql pragma I have a local testing setup where I can create drupal sites easily, all running with a sqlite DB.

I want to (firstly) publish the site to a remote server using a script that calls

drush sql-sync @blah.livesite.local @blah.livesite.com --create-db

The problem i ran into is that drush sql-sync does not like to migrate a sqlite DB to a mysql DB as some structural deficites block the transfer. The error message is:

ERROR 1064 (42000) at line 1: You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for
the right syntax to use near 'PRAGMA foreign_keys=OFF' at line 1

I know I maybe can do a sql-dump first, edit some of the lines manually and import that filt into the remote db then.
But I need this procedure quite often and have an automation script for the transfer - it should work fast with no manual editing involved.

Is it not possible to sql-sync from sqlite to mysql generally?

Yes, and I tried dbtng-migrate as well, with help of there. It did not work, I ran into all kind of errors, and I don't want to create another mysql db locally and sync then.

All I want is a simple way to sync my local sqlite drupal install to a remote  mysql one.

Drush sql-sync cannot convert and sync databases in one step; however, you can use drush dbtng migrator to convert the database locally into mysql format, and then use sql-sync to copy it to the final destination.


How do I build the node title from field values when saving the node? I have a content type (supertest) with the Category and Section fields, which are taxonomy term references. Every user has a Display name field.
I need to update the node titles when saving the nodes using [category] - [section]: [author.display_name] as format.
I've tried to add a rule, Display message action (just to test) on Before content save event, but it doesn't work. I can't figure out how to use the category field value to set the node title.
How can I make rules to change the node title?

Could be a job for Automatic Entity Label. Actually I'm using it that way – in production (though it has no stable release yet it works just fine).

  "Automatic Entity Label" is a small and efficient module that allows
  hiding of entity label fields. To prevent empty labels it can be
  configured to generate the label automatically by a given pattern.

You can define tokens from which the title will be built. An you can optionally set the title field to be always hidden on the node form. I'd also recommend to make the fields mandatory (required) that you use to build the title.


Anonymous users randomly get 404 errors on front page I have a drupal 6 site that will occasionally serve up a 404 error to anonymous users on the home page only.  It happens 2 or 3 times a day and I cannot figure out what is causing it.  I can clear it by logging in and flushing the cache, or going to site information and re-saving that form.

We are using the mobile tools module which I thought might be conflicting somehow, but I can't find any issues in the issue queue related to this.  We are using caching, but it's just standard drupal caching.

I've also tried checking the server logs and watchdog and I can't find anything useful.  Does anyone have any ideas?

It looks like it was due to a permissions issue.  I set all files and folders to the correct permissions and it seem to fix the issue.

I also updated to the latest dev version of the mobile tools module.


Replacing menu link text with image: overriding the right function? I try to use images instead of text in main menu, in a theme I'm building. Used different solutions in my template.php, without any luck. Drupal prints the link to the image and not the image itself. I even use the suggested Drupal modules (menuicon and menuimage). But I got the same bad result.

Same kind of questions was asked here around but with no working solution for me, as far as I tried.

Yesterday, a similar question was asked on Stackoverflow and get a comment from Clive (https://stackoverflow.com/questions/19788449/overridden-theme-menu-link-is-not-used). Clive gave a hint on maybe this user is overriding the wrong function. But unfortunately, the question was removed by the user last night. Yes, I'm that kind of unlucky guy :-)

So, I will try to ask it myself with some posted code, hoping that someone can give me a clue to solve the issue.

Here is the code in my template.php:

    function caracole_menu_link($link) {
       $element = $link['element'];
       // Allows for images as menu items. Just supply the path to the image as the title
       if ( strpos($element ['#title'], '.png') !== false || strpos($element ['#title'], '.jpg') !== false || strpos($element ['#title'], '.gif') !== false) {
       $link['element']['#title'] =  '<img alt="'. $element['#original_link']['description'].'" src="'. url($link['element']['#title']) .'" title="'. $element['#original_link']['description'] .'">';
       $link['element']['#localized_options']['html'] = TRUE;
    }
    return theme_menu_link($link);
    }

It's one of the solutions provided on forums. But I can't get it to work for me...

best regards,

plouf

Consider using hook_preprocess_link().

Here's a snippet:

/**
 * Implements hook_preprocess_link().
 */
function example_preprocess_link(&$variables) {
  if ($variables['path'] == 'path/of/link/to/change') {
    $variables['options']['attributes']['class'][] = 'class-use-image';
  }
}

Then in your CSS file, define the class that replaces the text with the image:

.class-use-image {
  width: 350px;
  height: 75px;
  background: url("images/<your-iamge>");
  text-indent: -9999px;
}

More techniques on replacing text with image here.


Load order of JS files Hey I have added the following libraries:

my-google-maps:
  js:
    https://maps.googleapis.com/maps/api/js?key=my_funkey_key&: {type: external, weight: -400, attributes: {defer: true,async: true}}
my_other_lib:
  header: true
  js:
    js/mylib.js: { }
  dependencies:
    - core/drupal
    - core/drupalSettings

I have tried multiple ways to attach these files in a specific order(first google and then my custom js:

{{ attach_library('my_module/my-google-maps') }}
{{ attach_library('my_module/my_other_lib') }}

If it is not in the specific order the map is undefined.How can I specific the load order?

The libraries are loaded by weight, not in the order they are defined.

You already had figured that out. You have set a weight of -400 for the external library. This will be the first library loaded, because in drupal the lowest weight for a library is -22. But most times you would want to be above -20, because this is the weight of jquery, on which most libraries depend.

The problem in your case is, that the library mylib.js is specified to be loaded in head. So the external library will never be able to come ahead. It's loaded at top of all other libraries because of the low weight, but still with the bunch of all the other libraries at the end of the document.


How to remove duplicate nodes in a view with taxonomy relationship (1 node per term)? I have a fairly straightforward view. Ie. Display nodes that are published & of content type X. Then sort by date.

It does however, have a relationship to a Vocabulary so that I can get access to the taxonomy image to display.

The result is a view that displays duplicate nodes if there is more than one taxonomy term of that vocab tagged on it.

How can I remove these duplicates?

I've tried the Query settings Distinct/Pure Distinct to no avail.

I'm also looking at this, but I'm hoping for a different solution.
Views relationship outputting duplicate nodes?

Update I had seen the Views distinct module (suggested in an answer now) and should have added it to the possible solutions. I'm still hoping for a "I just didn't know how to configure the view properly" kind of solution, as it feels like there must be a way to do this in Views instead of adding another module.

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

use this module and configure the settings in the view Field.

This will remove those duplicates from your view.
do this for the duplicated field items.


Purchases with points occupying ubercart I want to use ubercart to create a site for online purchases but I would like to know if you can use points as a form of payment, I mean that users are placed points with which they can buy items and their points are discounted for each purchase.

Yes you can use userpoints and userpoints ubercart. I did this in the past using drupal7. If you want to use drupal8, you need to check if the modules have been converted.

users can be allocated points by the admin person. the alternative is you have a product for purchasing points.
on checkout, points is presented as a payment option.
users can see their points balance and orders via their account page.

Another alternative is to use commerce_userpoints with its dependent modules (commerce, userpoints). But I believe this approach has a few outstanding bugs on the issues queue.


Does using Drupal.ajax() offer any benefits over jQuery.ajax()? I'm updating a node's references (list of them - rendered entities) manually with AJAX and experiencing performance problems.

$.ajax() is used to call a view rendered with the simplest page.tpl.php ever: print render($page['content']).

The filters are simple exposed filters that I pre-handle in the URL level so the url looks like this: /url-of-view?argone=foo&argtwo=bar&template=minimal. The view is then built up, rendered, and returned to the client.

The problem is when the site is at it's peak hours this URL (normally) is being bombarded and the server becomes slow to borderline unresponsive.

Will using Drupal.ajax() instead of jQuery.ajax() give me a performance boost here, or should I look at querying the node data manually instead of relying on Views?

There isn't really any difference in this context; at the lowest level both will use a standard XHR, so I reckon there's a good chance the bottleneck is the server-side building of the View.

You can test that by profiling, or in a pinch, returning a static string from the AJAX callback temporarily and stress testing the server. If you don't see the bottleneck, you know that building the View is the expensive bit.

If you're able to build up a query for the node data, and render the HTML manually, you should definitely see a performance improvement. A that point, though, you might want to question if using Views is the right thing in the first place :)


Responsive Superfish module? I'm trying to make responsive the menu generated by the superfish module and using the Omega theme by using this appoach:

Demo (try resizing your browser)

Script on Github

I also found a theme for joomla which include a superfish responsive menu: here

Before wasting time... Is there any other tested solution out there?


How do I turn off full html in comments only in drupal 7 Okay, I have set all content editing for admins on full html in drupal 7. I have also enabled wysiwyg and ckeditor. All is good, except I just want plain text and no ckeditor for the comments sections but want to allow automatic converting of links on it. How do I fix this? thanks guys.

I've always got on well with the Better Formats module, which allows complete control of input formats per type (comment/block/node), role and content type.

Others have answered this too, have a look at these:

Limiting allowed HTML tags in comments only
Disabling CKEditor in comments
Related: Removing the Text Format selection


Warnings still show on page even after setting Error messages to None in Logging and Errors I have set the Error messages to display to None

but still the website shows warning messages on top.

Also cleared the cache after this but the anonymous user can still see warning messages.

Is there anything else to be changed?

That's a pretty specific error message, and google says it is coming from this module:

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

at these lines: 808-812

  catch (Exception $e) {
    if (isset($cache_max)) { //this implies that we went even further back in the cache and could not connect, so call it quits
      if (variable_get('netforum_hide_error_messages', 0) == 0 || user_access('administer site configuration')) {
        drupal_set_message(t('Could not retreive data from server or cache.'), 'error');
      }

More specifically to your question, because the above module is using drupal_set_message it is not going to be effected by the 'error_reporting' level since that only impacts errors that would go to the logs. This makes sense as you would want to be able to suppress syntax or PHP errors while still letting system messages like "node was saved" or "subscription processed" still appear to the screen.

Your options to suppress this are to deal with the underlying cause of the error from the module (best case), or remove the 'messages' functionality from your theme, i.e. remove where ever it is that it says:

print $messages;

but again, that is probably not the best course of action here.


All instances of block are not getting removed This question is a continuation of this Block in Drupal 8, The second problem I am facing is that suppose I select block made for comment section and place it under Sidebar second section and afterwards deselect comment from configuration setting then after clearing cache the label for comment from block section is removed but block placed under Sidebar section still remains with default message for broken blocks "This block is broken or missing. You may be missing content or you might need to enable the original module.".What changes should I make so that this message is removed ? Thanks.

As mentioned in the other question, what you need to do is query for the blocks that no longer exist and delete them.

BlockContent::delete()/getInstances() is an example for that. You can do a similar query, either by using entity_load_by_properties() for the plugin ID that those blocks would have. Or you can run an entity query, which has more options.

You don't have an entity, so in your submit, you need to build a list of all unchecked options and then query for those. The advantage of doing an entity query is that you can do an IN condition, so you probably want to use that.

A more complicated example, that looks at settings and either updates or deletes the affected blocks can be found in simplenews.module's Newsletter::postDelete():

if (\Drupal::moduleHandler()->moduleExists('block')) {
  // Make sure there are no active blocks for these newsletters.
  $ids = \Drupal::entityQuery('block')
    ->condition('plugin', 'simplenews_subscription_block')
    ->condition('settings.newsletters.*', array_keys($entities), 'IN')
    ->execute();
  if ($ids) {
    $blocks = Block::loadMultiple($ids);
    foreach ($blocks as $block) {
      $settings = $block->get('settings');
      foreach ($entities as $newsletter) {
        if (in_array($newsletter->id(), $settings['newsletters'])) {
          unset($settings['newsletters'][array_search($newsletter->id(), $settings['newsletters'])]);
        }
      }
      // If there are no enabled newsletters left, delete the block.
      if (empty($settings['newsletters'])) {
        $block->delete();
      }
      else {
        // otherwise, update the settings and save.
        $block->set('settings', $settings);
        $block->save();
      }
    }
  }
}


Action links available options / caching I have some action links defined in module.links.actions.yml which uses a custom "create entity" route. For entity creation I set up some restrictions and at some point the access is denied. The problem is that whilst the access to the page is denied, the action link is still visible until I clear all caches.

Is there a way to tell Drupal not to cache the links or to programmatically clear the links cache? Or some options I can add in the yml file to prevent caching?

Thanks.

The following example implements an action link in Drupal 8 with the requirement of user-specific caching. This should allow you to hide/display the action link for the different users on your page. Providing different titles for different users should also work.

mymodule.links.action.yml:

entity.mymodule.add_form:
  class: Drupal\mymodule\Plugin\Menu\LocalAction\UserAction
  route_name: entity.mymodule.add_form
  title: 'Link to Add Form'
  appears_on:
    - entity.mymodule.collection

mymodule/src/Plugin/Menu/LocalAction/UserAction.php:

<?php

namespace Drupal\randomintro\Plugin\Menu\LocalAction;

use Drupal\Core\Menu\LocalActionDefault;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Routing\RouteProviderInterface;
use Drupal\Core\Routing\RouteMatchInterface;

/**
 * Defines a test local action plugin class.
 */
class UserAction extends LocalActionDefault {

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, RouteProviderInterface $route_provider, AccountInterface $current_user) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $route_provider);

    $this->currentUser = $current_user;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('router.route_provider'),
      $container->get('current_user')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheContexts() {
    return parent::getCacheContexts() + ['user'];
  }

  /**
   * {@inheritdoc}
   */
  public function getRouteParameters(RouteMatchInterface $route_match) {
    // If the user is not Anonymous.
    if (!$this->currentUser->isAnonymous()) {
      // Getting the uid.
      $uid = $this->currentUser->id();
      // Adding the link.
      return ['user' => $uid];
    }
    return [];
  }

}


Redeclare issue user_has_role following upgrade from Drupal 7.34 to Drupal 7.36 Precise error is "Fatal error: Cannot redeclare user_has_role() (previously declared in /usr/home/adpca/public_html/adpca.org.736/modules/user/user.module:863) in /usr/home/adpca/public_html/adpca.org.736/modules/php/php.module(80) : eval()'d code on line 23"

This is in an eval statement I've been through through code base looking for any duplication of the function user_has_role and can't find any. Also been through the databases looking for anything that might trigger the duplicate eval but no joy so far. Anybody got any pointers on what to look for?

The user_has_role() function has been introduced with Drupal 7.36, as stated here, and detailed here.

Following information given by the error message you received we see that:

the function is primarily declared in modules/user/user.module:863: looking at the code of the user module confirm this, ok
the new declaration is said to happen through modules/php/php.module(80): again, looking at the code of the php module confirms that line 80 executes eval('?> . $code);, ok
so the culpry supplemental declaration should be found at line 23 of the PHP content of a field which uses a format where the (not so usual) PHP evaluator filter has been enabled

IMO you should:

review all of your defined text formats, in order to select which of them have PHP evaluator filter enabled
from this reduced list, look for any node or block using these text formats (should not be as many)
then review the corresponding contents, where you'll probably find that somebody had created its own user_has_role() function for its needs, since it didn't exist yet before 7.36

HTH


Access entity reference in Block Plugin I have a content type that has an entity reference field. It's a content type for news articles with a field for tagging the article with taxonomy terms.

I'm attempting to access these terms in a block plugin, however I'm having difficulty. Getting other fields like text fields, and dates work just fine. For example

    $node = \Drupal::routeMatch()->getParameter('node');
    $node->get('body')->value

Successfully returns the contents of the node's body
 but when I use:

    $node = \Drupal::routeMatch()->getParameter('node');
    $tags = $node->get('field_tags')->value;

$tags comes up empty.

 die(print_r($tags));

Does not display anything.
I know it's in there somewhere though because when I use

die(print_r($node));

I do see the tag id's in there.

Is there a way to display the value of an entity reference field for taxonomy terms, in a block plugin?

I found that in order to get the values I had to use getValue() instead of ->value like so:

$tags = $node->get('field_tags')->getValue();


Unable to render fields in node.html.twig I'm trying to get individual fields printed on my node template, but am unable to get anything other than {{ content }} to work.

I'm using 8.5.0 and I'm not seeing any errors in the log. The page renders my markup so I know the template is being called.

Here's my node.html.twig markup:

    {%
     set classes = [
    'main-article',
    'main-article-page',
    ]
    %}
    {{ attach_library('classy/node') }}

    {{ content.field_image }}

    {{ content.body }}

Perhaps I've missed something in the setup of my theme?

This was an issue to do with the Field Layout module. Once that was uninstalled my markup worked as it should.

Field Layout (and also Layout Builder module) moves Drupal towards theming within the UI, so if you're looking to theme with twig files, I'd recommend not installing them.


How can I sort the order of status messages? I add my own validations to forms, for example the user registration. The errors I set with form_set_error are added below the drupal generated errors.
I would like to show them in the same order of my form fields on the page.

I thought I can use theme_status_messages($variables). When I do a dpm($variables) on a from with status messages it just shows an empty array.

$variables['display'], passed to the theme function is optional, and its purpose is only to limit the type of messages being shown; for example, if its value is "error," only the error messages should be shown. The list of messages is returned from drupal_get_messages(), which should be called as drupal_get_messages($variables['display']).

To answer to your comment, you can avoid duplicating all the code used by theme_status_messages() if you follow these steps:

obtain the array of messages from drupal_get_messages()
sort the obtained array of messages
use the array to set the content of $_SESSION['messages'], which is the session variable used to contain all the messages set from the modules
call theme_status_messages(), passing the same argument passed to your theme function (not the array obtained from drupal_get_messages())

This method seems half of a hack, to me. What happens if Drupal would change how the list of messages are saved? It could be that future Drupal versions will not use a session variable for this purpose.
It also take the assumption that other modules didn't override the theme function, but it would be easy in the implementation of hook_theme_registry_alter() to save the previously defined theme function, and call that function instead of assuming that function is theme_status_messages().


adding or remove multiple classes with attributes.addClass In my page template I can add a single class and remove a single class like this
<aside{{attributes.addClass(sidebar_first_classes).removeClass('content_classes') }}> But now I want to add a single class and remove two classes, and this does not work
 <asideright{{attributes.addClass(sidebar_second_classes).removeClass('content_classes','sidebar_first_classes') }}>

From the documentation for addClass and removeClass:

  attributes.removeClass()

  Removes a class from an Attribute object. Used similarly to addClass.
  Let's say you get the classes variable from somewhere else like a
  preprocess function.

  {% set classes = [ 'red', 'green', 'blue' ] %}

 outputs

.

So either you need to use an array to remove multiple classes or make multiple calls the removeClass and a single class.


Views AJAX functionality works, but nothing changes at all All AJAX functionality doesn't work properly.

Response body:

[{"command":"settings","settings":{"basePath":"\/","pathPrefix":"","ajaxPageState":{"theme":"my_theme"
,"theme_token":"BFQaFl_B7dBeJNtQvTMFxfKldHEJmDp3o5nAOEBhS1E"}},"merge":true}]

Pagination, sorting - nothing is working as supposed to work.

Any ideas?

Solved. View used permission that whas removed. Internally Drupal used different (admin related) to access this View. Strange that View was rendered, IMO exception should be thrown (in case of missing permission)


Is there a way to have two aliases to a user's profile page? Is there a way to have two aliases to a user's profile page?

We are currently using the user paths setting at admin/build/path/pathauto - but we would like to have another path set up for the same page if that is possible.

Currently we have one path set to be:
users/[content-profile-directory-preferred_first_name-raw]-[content-profile-directory-lastname-raw]

We would like to setup a second path to the same user's profile page that would be just:
users/[user-raw]

Thanks,
Greg

Assuming you don't want to manually maintaing the second alias - since pathauto only allows you to generate a single automatic alias - then perhaps the easiest way is to use Rules, instead of pathauto. It's been a few years since I did this, and it was for node aliases, not user page aliases, but I don't see why it wouldn't work.

Setup a Rule with multiple steps to create the aliases you need - you can use all the same token substitutions in Rules as you can in pathauto
Run the rule when a user is created