How do I manage breadcrumbs when the node uses multiple vocabularies? I have a blog in Drupal 8 and it uses the Categories vocabulary to display breadcrumbs as Home > Blog > [Category] > Post title.
I added taxonomies from the Tags vocabulary, which means every post can have one category, and multiple tags. Since I added the Tags vocabulary, it has taken over the breadcrumbs on individual blog posts, which are now Home > Blog > [Tag] > Post title.
Is it possible to control which vocabulary should have priority when it comes to displaying breadcrumbs?
Is it possible to control which vocabulary is displayed on blog posts based on where the user came from? For example, if the user is on the individual Tag page (Home > Blog > [Tag]) and clicks on a blog post belonging to that tag, the blog post should display the breadcrumbs using the Tags vocabulary (Home > Blog > [Tag] > Post title). However, if the user is on the individual Category page (Home > Blog > [Category]) and clicks on a blog post belonging to that category, the blog post should display the breadcrumbs using the Category vocabulary (Home > Blog > [Category] > Post title).

Here's my solution. Keep in mind that I'm very new to Drupal, so this might be a bit over-complicated, but hopefully it gives someone with a similar problem some direction. I will likely refactor this class in upcoming days, but right now I just need a break from all this mess.
function [YOUR-MODULE-NAME]_system_breadcrumb_alter(\Drupal\Core\Breadcrumb\Breadcrumb &$breadcrumb, \Drupal\Core\Routing\RouteMatchInterface $route_match, array $context) {

  // Control Blog Post Breadcrumb Taxonomy Trail
  $blogPostBreadcrumb = new BlogPostBreadcrumb();
  $blogPostBreadcrumb->alter($breadcrumb);
}

use Drupal\Core\Breadcrumb\Breadcrumb;
use Drupal\Core\Entity\EntityBase;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Url;
use Drupal\node\Entity\Node;
use Drupal\taxonomy\Entity\Term;
use Exception;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class BlogPostBreadcrumb
 *
 * The purpose of this class is to control Blog post breadcrumbs, as described here:
 *
 * RULE 1:
 * When the user is on the Tag page (Home > Blog > Tag) and clicks on a blog post, the blog post breadcrumbs will
 * display: Home > Blog > [Tag Name] > Blog Post Title
 *
 * RULE 2:
 * When the user is on the Category page (Home > Blog > Category) and clicks on a blog post, the blog post breadcrumbs
 * will display: Home > Blog > [Category Name] > Blog Post Title
 *
 * RULE 3:
 * When the user loads the blog post directly (i.e. Home > Blog, or comes from other sources unrelated to
 * Category or Tag), the blog post breadcrumbs should default to Category:
 * Home > Blog > [Category Name] > Blog Post Title
 *
 */
class BlogPostBreadcrumb
{
  /**
   * @param Breadcrumb $breadcrumb
   */
  public function alter(Breadcrumb &$breadcrumb): void
  {
    try {
      // current node
      $current_node = $this->currentNode();

      // nothing found, nothing to do
      if (empty($current_node)) {
        return;
      }

      // what is the current content type
      $content_type = $this->getField($current_node, 'type');

      // apply rule only to blog_post content type, otherwise let's stop the madness right here
      if ($content_type !== 'blog_post') {
        return;
      }

      // determine if the tag can be extracted from referrer. If not, default it to college_tag
      $altered_breadcrumb = $this->getTaxonomyLabelAndUrlByReferrer()
        ?? $this->getTaxonomyLabelAndUrlByCollege($current_node);

      // nothing matched - just let it be. Display blog_tags rather than nothing.
      if (empty($altered_breadcrumb)) {
        return;
      }

      // modify existing breadcrumb list by replacing the third link with proper tag
      // (Home > Blog > [college_tag/blog_tag] > Blog Title)
      $breadcrumb->getLinks()[2]->setText($altered_breadcrumb['label']);
      $breadcrumb->getLinks()[2]->setUrl($altered_breadcrumb['url']);

      // we have to disable caching, otherwise whichever taxonomy opens first, it will get cached!
      // load menu_link_content entity
      $entity =  \Drupal::entityTypeManager()
        ->getStorage('menu_link_content')
        ->load($current_node->getEntityTypeId());
      // disable caching
      $breadcrumb->addCacheableDependency($entity);
    } catch (Exception $e) {
      // if any exception is thrown, we don't want to stop the page from loading.
      // Worse case scenario, it will load blog_tags into breadcrumbs.
    }

  }

  /**
   * Get Field from node
   * Helper method for retrieving field value from given node.
   *
   * @param EntityInterface $node
   * @param string $fieldName
   * @return mixed|null
   */
  protected function getField(EntityInterface $node, string $fieldName)
  {
    return $node->get($fieldName)->getValue()[0]['target_id'] ?? null;
  }

  /**
   * Load node from current url
   *
   * @return EntityBase|null
   */
  protected function currentNode():? EntityBase
  {
    if ($nid = \Drupal::routeMatch()->getParameter('node')) {
      return Node::load($nid->id()) ?? null;
    }
    return null;
  }

  /**
   * Determine Taxonomy Breadcrumb Label and Url by referrer
   * We want to display Breadcrumb category depending from where the user is coming from:
   * Blog College (category) or Blog tag page
   *
   * @return array|null
   */
  protected function getTaxonomyLabelAndUrlByReferrer():? array
  {
    // capture referrer the "Drupal way"
    $route_parameters = $this->referrer();

    // if type is not a taxonomy term, it's not used to us
    if (empty($route_parameters['taxonomy_term'])) {
      return null;
    }

    // load node (taxonomy term)
    $term = Term::load($route_parameters['taxonomy_term']);

    // get taxonomy type
    $taxonomy = $this->getField($term, 'vid');

    // check if taxonomy belongs to college_tags or blog_tags
    if (empty($taxonomy) && !in_array($taxonomy, ['college_tags', 'blog_tags'])) {
      return null;
    }

    // if we can't find the url or the label
    if (empty($term->url() || empty($term->label()))) {
      return null;
    }

    return [
      'label' => $term->label(),
      'url' => Url::fromUserInput($term->url())
    ];
  }

  /**
   * Determine Taxonomy Breadcrumb Label and Url by college
   * This method will be used when referrer page doesn't exist, or the referrer is not Blog Category or Blog Tag page
   *
   * @param EntityInterface $node
   * @return array|null
   */
  protected function getTaxonomyLabelAndUrlByCollege(EntityInterface $node):? array
  {
    // blog can have one college tag (category)
    $taxonomy_id = $this->getField($node, 'field_college');
    $term = Term::load($taxonomy_id);

    // if we can't find the url or the label
    if (empty($term->url() || empty($term->label()))) {
      return null;
    }

    return [
      'label' => $term->label(),
      'url' => Url::fromUserInput($term->url())
    ];
  }

  /**
   * Referrer node
   * Load referrer node the "drupal way"
   *
   * @return mixed
   */
  protected function referrer()
  {
    // this would be college_tag or blog_tag page
    $previousUrl = \Drupal::request()->server->get('HTTP_REFERER');
    // fake the request to previous page, so we can get more info
    $fake_request = Request::create($previousUrl);
    // build url object.
    $url_object = \Drupal::service('path.validator')->getUrlIfValid($fake_request->getRequestUri());
    if ($url_object) {
      return $url_object->getRouteParameters();
    } else {
      return null;
    }
  }
}


How to append css class to menu link? We have a custom menu mymenu where we use menu_link_attributes to add CSS classes per menu link.

The problem we are running into is that we have one generic css class that we always want added regardless of whether it is entered through the Menu link attributes. In the twig template, it is using {{ link(item.title, item.url) }}.

We tried the following, but it will only replace myCssClass with whatever was their before and I cannot seem to find the right array when calling mymodule_preprocess_menu().

{{ link(item.title, item.url, item.attributes.addClass('myCssClass')) }}

How can I append a CSS class to a menu link to the item.attributes array?

menu--mymenu.html.twig

{{ menus.menu_links(items, attributes, 0) }}

{% macro menu_links(items, attributes, menu_level) %}
  {% import _self as menus %}
  {% if items %}
    {% if menu_level == 0 %}
      <ul{{ attributes.addClass('menu') }}>
    {% else %}
      <ul class="menu">
    {% endif %}
    {% for item in items %}
      {%
        set classes = [
          'menu-item',
          item.is_expanded ? 'menu-item--expanded',
          item.is_collapsed ? 'menu-item--collapsed',
          item.in_active_trail ? 'menu-item--active-trail',
        ]
      %}
      <li{{ item.attributes.addClass(classes) }}>
        {{ link(item.title, item.url) }}
        {% if item.below %}
          {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
        {% endif %}
      </li>
    {% endfor %}
    </ul>
  {% endif %}
{% endmacro %}

This is an easy one, I'm pretty sure you might have figured out yourself in a short while.

You see that set classes directive?

{%
  set classes = [
    'menu-item',
    item.is_expanded ? 'menu-item--expanded',
    item.is_collapsed ? 'menu-item--collapsed',
    item.in_active_trail ? 'menu-item--active-trail',
  ]
%}

This is where the magic happens and the classes array is built for all CSS classes to attach to your link item(s).

And this is also the place where you should add your additional CSS class that should be used in every link item, like so:

{%
  set classes = [
    'myCssClass',
    'menu-item',
    item.is_expanded ? 'menu-item--expanded',
    item.is_collapsed ? 'menu-item--collapsed',
    item.in_active_trail ? 'menu-item--active-trail',
  ]
%}

Leaving the rest of the template untouched (especially the {{ item.attributes.addClass(classes) }}) gives you the desired behavior.

Some further reading, that might be of interest for you: https://www.drupal.org/docs/8/theming-drupal-8/using-attributes-in-templates


How can I add additional query parameters to a view title linked to a node? I have a view (using the calendar module), which displays a title field for each displayed event. The title field is set to "link this field to the original piece of content".

I'd like to rewrite that link to add some additional parameters, e.g. ?return_view=myview, so that I can link back to the view page from the content. The content might be linked to from any one of several different views, so it needs to take some parameter (i.e. return_view) to tell it what to link back to.

I've tried adding a hook_views_pre_render:

function mymodule_views_pre_render(&$view) {
    if ($view->name == 'myview') {
        foreach ($view->result as &$r) {
            $r->node_title = array(
                '#theme' => 'link',
                '#text' => 'xyz',
                '#path' => 'node/' . 123,
                '#options' => array(
                    'query' => array(
                        'rv' => $view->name,
                        'rvd' => $view->current_display
                    ),
                    'attributes' => array(),
                    'html' => FALSE
                )
            );
        }
    }
}

But that just leads to Drupal complaining that "warning: htmlspecialchars() expects parameter 1 to be string, array given in check_plain()" - I'm assuming because some rendering function somewhere expects to get a plain string.

What's the cleanest way to add additional query parameters to a node title rendered by views?

You can do this in Views.

Add a new field to the View "Content: Path".
Check Exclude from display.
Click on Rewrite Results and the check "Use absolute link".
Click Apply button to Save.
Rearrange your fields so "Content: Path" is above "Content: Title".
Click on the "Content: Title" field.
Uncheck "Link this field to the original piece of content".
Click on Rewrite Results and check "Output this field as a link".
In the Link path textbox enter "[path]?return_view=myview".  (You can use the path replacement pattern because it is above the title field in the field order)
Click Apply.


How to print page/node templates being used on a page? I'm using Drupal 6.19 and trying to debug why a custom page template for my login page isn't being picked up.
I've tried to use devel themer, but I don't see the "widget" when I'm not logged in, and of course I can't see the login page when I am.

I'm hoping for a script that I can drop in on my page tpl that will print the current template being used. Or maybe there are other suggestions?

For Drupal 7, there's a new 'theme debug mode'. This eliminates the need for installing the Theme Developer module and its dependencies, if all you want is to see the templates being used on a page.

  As of Drupal 7.33, Drupal core has a theme debug mode that can be
  enabled and disabled via the theme_debug variable. Theme debug mode
  can be used to see possible template suggestions and the locations of
  template files right in your HTML markup (as HTML comments). To enable
  it, add this line to your settings.php:

$conf['theme_debug'] = TRUE;

see https://www.drupal.org/node/223440


Display the user avatar in  a user panel Is there an alternative to make the login box that turns into the default user panel (My Account, Administer etc.) display the user's profile picture above the username?

There are actually two separate blocks, User login that is displayed only to anonymous users and Navigation that only gets displayed once user has logged in. You are interested in modifying the latter one.

Unfortunately, there's no hook_block_alter() around that you could use to modify the block from a custom module. However, you can do so from within your theme just before the block gets displayed.

Just pop the following function into YOURTHEME's template.php and it should work. Please, note, this adds the user picture to the top of the block content, just below the user name.

function YOURTHEME_preprocess_block(&$vars) {
  $block =& $vars['block'];
  if ($block->module == 'user' && $block->delta == 1) {
    // Navigation block.
    $block->content = theme('user_picture', $vars['user']) . $block->content;
  }
}

If you want it above the username, just replace $block->content with $block->subject.

Or, even better, just create another block, place it above the Navigation, make it only visible specifically to authenticated user role, set the Body title to <none>, and Block body to:

<?php
global $user;
print theme('user_picture', $user);
?>

Make sure to enable the PHP filter module first and use PHP code filter for the Block body input.


Using menu tab for each panel variant I'm trying to use Panels to arrange content on my site. I've made some strides in creating a panel that displays a view of images based on different criteria.

I added a page (panel) which allows me to tap into Drupal's menu system and make a tab called Photos. Now I want to add a number of variants to this panel, and I want links to those variants to show up in the sub-tab (MENU_DEFAULT_LOCAL_TASK). Since there does not seem to be any way to add a menu item for each variant, I'm wondering what is the best way to do this.

I see two possibilities, both of which don't seem ideal:

I could write a module, that adds the  default local tasks to the menu item.
I could add a separate panel page for each variant, and use the menus there.

It seems like there should be an easy solution to this. Can anyone help me?

I sort of figured out a way to do this.

Add a variant within the Panels module
Add a visibility rule so that different variants show at different URLs (clean URLs and paths required), for example, example.com/paneltitle/variant1, example.com/paneltitle/variant2.
Create a custom module to hook into the menu. There is a great example of a menu module in the module code samples on drupal.org. A example here for above variants:

`

function custom_module_menu() {
  $items['paneltitle/variant1'] = array(
    'title' => 'variant1',
    'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,
  );

  $items['paneltitle/variant2'] = array(
    'title' => 'variant1',
    'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

This seems to have worked for me.


Get image width for a styled image in module In hook_node_load I need to get the width and height of a styled image, for a given fid.

The image style has only height effect and the width is scaled and calculated by Drupal, so using image_styles() is of no use.

My code so far is like this:

  $field_image = field_get_items('node', $node, 'field_image', LANGUAGE_NONE);
  $img_uri = file_load($field_image[0]['fid']);
  $img_url = image_style_url('mystyle', $img_uri->uri);
  $img_info = image_get_info ($img_url);

$img_info gives me FALSE instead of the info. How to get the width?

according to documentation, you just need image_style_path instead of image_style_url

and finally

 $field_image = field_get_items('node', $node, 'field_image', LANGUAGE_NONE);
 $img_uri = file_load($field_image[0]['fid']);
 $img_url = image_style_path('mystyle', $img_uri->uri);
$img_info = image_get_info ($img_url);


Suggest a new template file for a page node view I have a site which has two main views, a men's blog and a women's blog, both with their own content types, mens-blog-post and womens-blog-post. The problem I am facing is that they share the same page--node.tpl file (node page view, default file:page.tpl not node.tpl), but need to have different content (e.g. other relevant views in the sidebar region). I need to suggest two new template files called page--node--mens-blog-post.tpl.php and page--node—womens-blog-post.tpl.php based on content type.

Here is my attempt:

function force_preprocess_page(&$vars){
 if ($vars['content']->type == 'mens-blog-post') {
  array_unshift($vars['theme_hook_suggestions'], 'page__node__mens_blog_post');
 }
 if ($vars['content']->type == 'womens-blog-post'){
  array_unshift($vars['theme_hook_suggestions'], 'page__node__womens_blog_post');
 }
}

Can anyone help me clean this up and make it work? I am looking for any solution that works so I am open to other ideas.

To use a different template file for the node being shown, you need to add a new suggestion in $variables['theme_hook_suggestions'] (Drupal 7), or $variables['template_files'] (Drupal 6). In both the cases, the variable is an array.

In a module, the hook to implement is hook_preprocess_page().

function force_preprocess_page(&$variables) {
  if (!empty($variables['node'])) {
    if ($variables['node']->type == 'mens-blog-post') {
      array_unshift($variables['theme_hook_suggestions'], 'page__node__mens_blog_post');
    }
    elseif ($variables['node']->type == 'womens-blog-post') {
      array_unshift($variables['theme_hook_suggestions'], 'page__node__mens_blog_post');
    }
  }
}

If you have a module called force.module, then your code is correct. The same code can be used for a theme whose short name is force; in this case, in its template.php file you add a force_preprocess_page() function.
In Drupal 6, your theme needs to also have the default template file (page.tpl.php), or the custom template is not going to be picked up. I didn't check if this is still valid in Drupal 7. (The only time I created a theme that was using a custom template file was in Drupal 6.)

I would rather check the variable $variables['node'] is not empty, as hook_preprocess_page() is called for every page served from Drupal, including the ones not associated with any node.


Entity References Auto create between Nodes I have node 1 has a reference to node 2 & node 3
how can I make node 2 & node 3 have a reference automatically (because they have the same reference with node1)?

You can implement hook_entity_insert()

  Act on entities when inserted.

  Parameters

  $entity: The entity object.

  $type: The type of entity being inserted (i.e. node, user, comment).

and inside the hook check if you have more than one node in the reference field, in this case you will edit all the nodes and add the reference to the others.


Overriding field label I'm trying to override the label of the picture field.  I've started with the code here:

How to change the field label on my registration form? Drupal 7

function mymodule_form_alter(&$form, &$form_state, $form_id)
{
if ($form_id == 'user_profile_form') {
  dsm($form_id);
    $form['account']['picture']['#title'] = t('Profile Picture');
}
}

I just want to override the "PICTURE" title to something else.

Actual code should be:

I have used hook_form_FORM_ID_alter() instead of hook_form_alter().

function test_form_user_profile_form_alter(&$form, &$form_state) {
  // Used dpm() to check for picture array.
  $form['picture']['#title'] = t('Profile Picture');
}

Result:

Note: The capitalization of all the character must be coming from theming layer.

Use dpm() for development:
The structure has changed and the account array no longer holds picture array.


In Scald, is there a way to link a scald atom shown using an image style to the original image? I still haven't figured out how to link to the original atom from a display context.  For instance, if the context for an image is to downscale to a specific Image Style, I want to be able to link to the full size image (this is what users with prior exposure to WordPress expect).

So far I've tried the following:

1. Finding a way to autopopulate the link field when I edit atom properties (see screen shot below).

However, I've been informed that this option is not for the automatic link purpose, so I've abandoned this approach.

2. Setting "Link to content" to "yes" in the Manage Field display tab (see screenshot below). That does not seem to make a difference (the image does not become linked to anything).

I've tried both Scald 7.x-1.3 and 7.x-1.4 - and yes: I have cleared the cache.

Do anyone know where to find the setting for this?

This option is not for the automatical link purpose.

What you want is always to link to the original image. This is configurable in the Manage Field display tab.

In your 2nd setup, enable "Link to content" will link to the content (the host entity, not the atom itself). If you want the image is linked to the atom, then there are two options:

Write a custom player and use it (the current player has no "link" option)
Configure qt the Manage display of the atom (admin/structure/scald/image/display), hide the atom itself and show the image field, with the link option.


fastest between hook_js vs hook_menu to get JSON via REST I'm trying to figure out if in my case it makes sense to use the High-performance JavaScript callback handler module.
Between js/MODULE/example.json (hook_js()) and example.json (hook_menu()), the difference of time is not huge, but I think hook_js() is faster.

In a case I'm not using any Drupal function, variable or session, and I'm only calling another server with REST. Can I bypass all the bootstrap functions, or do I have to use the first layer (DRUPAL_BOOTSTRAP_CONFIGURATION)?

What would be the faster solution?

function MODULE_js(){
    return array(
      // Example URL is /js/MODULE/example.json
      'example.json' => array(
        'callback' => 'my_json',
        'includes' => array('unicode', 'locale', 'language'),
        'dependencies' => array(),
        'bootstrap' => DRUPAL_BOOTSTRAP_CONFIGURATION,
        'access callback' => 'access_callback',
        'access arguments' => array(),
        'page arguments' => array(),
        'skip_hook_init' => TRUE,
        'delivery callback' => 'drupal_json_output',
      ),
    );
}
function access_callback (){
    return true;
}

function MODULE_menu()
    $items['example.json'] = array(
        'type' => MENU_CALLBACK,
        'page callback' => 'my_json',
        'page arguments' => array(),
        'access callback' => true,
        'delivery callback' => 'drupal_json_output',
    );
return $items;
}

function my_json(){
    //call with curl/rest and return a json
    return 'json';
}

Actually, as the project documentation says, you should use http://example.com/js.php?q=js/mymodule/callback instead of http://example.com/index.php?q=js/mymodule/callback, and basing on the test reported from the maintainer, the previous is faster than the latter (59.371 ms per request versus 446.846 ms per request). Since you are waiting a reply from another server, probably you would not notice that difference too.

For you second question, if you are going to use the High-performance JavaScript callback handler module in the way shown in the documentation, js.php bootstraps Drupal at DRUPAL_BOOTSTRAP_DATABASE level. In any case, if you are not using any Drupal function nor the session, and you are using just plain PHP functions or classes, then you don't need to bootstrap Drupal at all. Keep in mind that this means you cannot use any function implemented by Drupal modules too.


Change the value of a taxonomy field on cron run I have the article node with two extra fields:

Taxonomy reference field field_verification_status with two possible values:

Valid (tid: 272)
Expired (tid: 271)

Date field (field_article_expiry_date)

When a user will create a new article, will set:

Taxonomy reference field field_verification_status = Valid (tid: 272)
Date field (field_article_expiry_date) = Any time in the future.

Now using Ultimate Cron Module, I want on every cron run, to:

Check if the field_article_expiry_date value is less than current time (now)
if above return true then change the field_verification_status value to Expired (tid: 271)

To accomplish the above, I have created a new module custom_cron_expired_articles and in the .module file I added the below codes:

<?php

use Drupal\node\Entity\Node;
use Drupal\taxonomy\Entity\Term;

/**
 * Implements hook_cron().
 */

// On "Cron Run" and "Every Half Hour":
    // Loop through all "Valid" articles with expiry date set to the past,
    // Change the status of each article to "Expired".

function custom_cron_expired_articles_cron() {

  // Get the "cron time" (Return Value is in UNIX Timestamp format)
    //$cron_time = \Drupal::time()->getCurrentTime();
    //date_default_timezone_set('GMT');

// Load all available expired nodes of type 'offer'.
  $storage = \Drupal::entityTypeManager()
    ->getStorage('node');
  $query = \Drupal::entityQuery('node')
      ->accessCheck(FALSE)
      ->condition('type', 'article')
      ->condition('field_verification_status', 272)    // Verification Status = Valid
      ->condition('field_article_expiry_date', strtotime($?????), '<=')  // Something is missing here
      //->range(0,50);
  $nids = $query->execute();

// Loop through all expired nodes.
foreach ($nids as $nid) {

// Load the Node by its ID.
    $node = \Drupal\node\Entity\Node::load($nid);

    // Update the node.
    $node->field_verification_status->target_id = 271; // Verification Status = Expired

    // Save the updated node.
    $node->save();

// resetCache() in such a loop over all entities of one type avoids running out of memory.
\Drupal::entityManager()->getStorage('node')->resetCache(array($nid));
}
}

How to compare if the field_article_expiry_date is less than the current_time ? or by other words, how to load only the nodes with field_article_expiry_date less than the current_time?

Can somebody tell me what is the missing part ?

You store the value returned from \Drupal::entityTypeManager()
    ->getStorage('node') in $storage, but you don't use it. On the next line you use \Drupal::entityQuery(). (I don't recommend it, as it will be deprecated in Drupal 9; you should use the entity type manager.)

The code I would use is the following one.

  use Drupal\Core\Datetime\DrupalDateTime;

  // Build Drupal DateTime & set correct format for your query
  $curent_time = new DrupalDateTime('now');
  $curent_time = $curent_time->format('Y-m-d\TH:i:s');

  // Get Entity Manager to build your query
  $storage = \Drupal::entityTypeManager()
      ->getStorage('node');

  // Get all Nodes satisfing your conditions
  $nids = $storage->getQuery()
      ->condition('type', 'article')
      ->condition('field_verification_status', 272)
      ->condition('field_article_expiry_date', $curent_time, '<=')
      ->execute();

  // Load all Node entities according to their IDs
  $nodes = \Drupal\node\Entity\Node::loadMultiple($nids);

  // Do whatever you want with Nodes
  foreach ($nodes as $node) {
    // Do something
    $node->save();
  }

See also

DrupalDateTime
DateTime in queries


How to set configuration value for drush site install? I have set a central translations directory(sites/all/translations) for my multisite installation profile so that each site does not have to download translations that were already downloaded.

I have set this via global settings file that I am including in the site's settings file, but it did not helped. Then I have added locale.settings.yml config into the profile, still no change. This works always AFTER the site was installed.

In the site installer there is a condition that checks if the config value for the directory exists in the global config variable, it will use that value or if not it will use the site's own translations directory by default.

So I think that during the installation process using config won't work and the only way is to use the global config variable.

So my question is how I can provide this variable to drush's site install command?

I am talking specifically about this: core/includes/install.core.inc:411

  // Register the file translation service.
  if (isset($GLOBALS['config']['locale.settings']['translation']['path'])) {
    $directory = $GLOBALS['config']['locale.settings']['translation']['path'];
  }
  else {
    $directory = $site_path . '/files/translations';
  }
  $container->set('string_translator.file_translation', new FileTranslation($directory));
  $container->get('string_translation')
    ->addTranslator($container->get('string_translator.file_translation'));

It is not possible to override this since the install_check_translations() has this hard-coded.


Send email notification for the new created survey using webform I'm looking for a way to send email notification to all my users once my scheduled survey is already open. Upon checking the Webform module, all I can see about email notification is when a user submitted a response to the surey.

Webforms does not work that way.  Webforms is for you or an administrator to receive an email when a user on your site fills out a form.

For example, if a customer wants you to send them a brochure in the mail, Webforms will let you know when they fill out your form.

If you want to notify multiple site users (not administrators) about a form being available, consider trying something like MailChimp, or one of the other popular mailing list programs.  The well-known ones (MailChimp, Constant Contact, etc.) all have modules that will allow you to integrate them with your Drupal web site.


Additional Uncaught Exception? I updated some modules, and the site was working fine afterward; then, I made some changes to my .info file, uploaded, and suddenly I'm getting this error.

  Additional uncaught exception thrown while handling exception.

  Original

  PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column "base.access_exposed" in "field list&": SELECT base.id AS id, base.name AS name, base.label AS label, base.plugin AS plugin, base.active AS active, base.weight AS weight, base.status AS status, base.dirty AS dirty, base.module AS module, base.access_exposed AS access_exposed, base.data AS data FROM {rules_config} base WHERE (base.plugin = :db_condition_placeholder_0) AND (base.active = :db_condition_placeholder_1) ; Array ( [:db_condition_placeholder_0] => reaction rule [:db_condition_placeholder_1] => 1 ) in EntityAPIController->query() (line 152 of /home/content/92/8292092/html/sites/all/modules/entity/includes/entity.controller.inc).

  Additional

  PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column "base.access_exposed" in "field list&": SELECT base.id AS id, base.name AS name, base.label AS label, base.plugin AS plugin, base.active AS active, base.weight AS weight, base.status AS status, base.dirty AS dirty, base.module AS module, base.access_exposed AS access_exposed, base.data AS data FROM {rules_config} base WHERE (base.plugin = :db_condition_placeholder_0) AND (base.active = :db_condition_placeholder_1) ; Array ( [:db_condition_placeholder_0] => reaction rule [:db_condition_placeholder_1] => 1 ) in EntityAPIController->query() (line 152 of /home/content/92/8292092/html/sites/all/modules/entity/includes/entity.controller.inc).

I do have a database backup that was made before updating the modules.

The error cites entity, but nothing has changed there since Drupal was installed.

If you updated the modules manually, rather than using the Drupal UI system then you must run example.com/update.php on the URL.  It is likely that one of the modules you updated made changes to the database table system.  If you do not run update.php, then the modules may not have made the necessary table structure changes that match the code.


Is there a way to pass selected date from date_popup to another view in URL? I'm using date module in Drupal 7. There are two views that I created; a link inside of one leads to another view. In the first view, I used exposed popup date filter to get the result. What I'm trying to achieve here is how to pass the selected date from the date popup, put it in the URL to use as contextual filter in the another view.

Thanks,
Jake

Definitely. When you expose a filter, it listens for a specific $_GET ID in the URL. This ID can be set by expanding the "More" settings of the particular filter item and entering/modifying the string in the "Filter identifier" field.

In your case, you'd copy the first View's filter identifier and paste it into the second View's filter identifier, thus allowing both of them to use the same item in the URL.


hook_node_view_alter not working I'm hoping to finally find some solutions here. I'm new to custom module development in Drupal and I'm trying to learn the basics. What I'm trying to do is use hook_node_view_alter, however even at the simplest step (showing a status message) it does not work.

My module (test_module) is installed and enabled on the site. Currently the custom module has only two files: test_module.info.yml and test_module.module

Code from test_module.info.yml file

name: test_module
type: module
description: Test module
core: '8.x'

Code from test_module.module file

<?php
/*
* Implementation of hook_node_view_alter
*/

use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\NodeInterface;

function test_content_node_view_alter(array &$build, NodeInterface $node, EntityViewDisplayInterface $display, $view_mode) {
    drupal_set_message(t('Hello!'));
}

?>

It doesn't show the message when I'm opening a node (/node/1) at my Drupal site. As I understand it, it should show the message for any existing node when it is viewed. I've cleared the cache, nothing's changed.

Update

changed test_content_node_view_alter() to test_module_node_view_alter()
adjusted the code to coding standards
removed the php closing tag

My code in test_module.module looks like this right now:

<?php

/**
 * @file
 * Implementation of hook_node_view_alter();
 */

use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\NodeInterface;

function test_module_node_view_alter(array &$build, NodeInterface $node, EntityViewDisplayInterface $display, $view_mode) {
  drupal_set_message(t('Hello!'));
}

I've cleared all cache and now the website gets this error:

  The website encountered an unexpected error. Please try again later.

After researching more examples out there in the Web, I've finally managed to make this work, however I'm still not sure why it was not working before...

Working code:

<?php

/**
 * @file
 * Implementation of hook_entity_view_alter();
 */

function test_module_entity_view_alter($entity, $type, $view_mode) {
    drupal_set_message(t('Hello world!'));
}

Moving on to further modifications. Thanks everyone!


How to display the View according to the logged user? I'm Creating a view of a specific content type called "requests (Demande)" , Each request is assigned to a specific user (I have two users : "Salaktarus" and "Zaferro") , what I want to know is how to configure the filter so each user ("Salaktarus" or "Zaferro") sees only the requests which he/she is assigned to.

Add a relationships based on user who is assigned in the request (if he/she is assigned using a reference field , select that field) , then create a filter based on user (the user who is currently logged in and is viewing the table) , use relation to relate user to nodes which he/she is assigned to.


Display images as a form element in a webform The goal is quite simple – I'm looking for a way to display an image in a webform.
By that I mean the image would part of the webform as a complement to a question (example: "what color is the car in this picture").
If possible it'd be great if the user could to upload the images when administrating the webform elements, and also if they were their own element that would be awesome (but even adding them to the descriptions of the question-elements themselves could work as well).
So basically, how can I setup a "display custom image in the webform"-element?
I've tried searching for a solution but all my results are about how to add an image upload field, which is quite the opposite of what I'm looking for.
Grateful for any help I could get on this.

If you install the IMCE module and set up the right permissions, users can upload and insert images into a webform.
Another option is to change the Webform module's default HTML Editor to use a Text format which supports inline images. You would do this by going to Webform > Configuration > Elements ( (/admin/structure/webform/config/elements)


How can I programmatically override the title tag from within custom module? I have a custom module that creates a search form and displays search results. We have a need where we want the title that displays in the browser tab to change depending on the search criteria. This particular search searches jobs that are available in specific specialties. I know you can use drupal_set_title() to change the title that gets displayed to the user in the H1 tag on the page, but what I am talking about is changing the title in the browser. The actual title tag for SEO purposes. So by default, the Browser tab title says "Job Search | My Site Here" ("My Site Here" is a place holder for the actual name of my site). When they perform a search we want the title to change to "{Specialty Name} Jobs | My Site Here". So for example if they search on the specialty "Cardiology", the browser title will be "Cardiology Jobs | My Site Here". I know there are custom modules to handle changing the page title dynamically, but those are for existing content types. This job search has been created completely from within a custom module, so ALL of the pages are dynamic. Is there a way to edit the browser page title independently of the drupal_set_title() function from within the custom module?

See this question and answer. In short, I think your might be looking for something like hook_preprocess_page().

function mymodule_preprocess_page(&$variables) {
  $variables['head_title'] = t("The new HTML title.");
}


What's the difference between Page manager and Panels? I'm writing this question, because I see confusion all over the Drupal community about "what is Page manager", and "what is Panels".

Ctools

In Ctools, there is a sub-module called "Page manager". This module, at it's core, is a graphical user interface to hook_menu. It allows you to either create new paths in the system, or take over some of the ones provided by Core.

Page manager

Once Page manager manages a path for you, it can do several different things with it. Out of the box, it can provide redirects for you. One common use case for this, is to deny access to nodes that lack proper theming because they are not meant to be viewed on their own, such as "Fact boxes" or "Image nodes". Another is to redirect from a term view to a Solr search of the same term.

One of the main benefits of Page manager, is that it introduces a way of dealing with "Context", not to be confused with the module Context. The kicker here, is that Panes, which are "slightly smarter blocks", can declare their dependencies to the system, and them have the actual arguments (called Contexts) passed in dependency injection-style.

For those unfamiliar with DI, but familiar with Drupal, this, for example, allows you to never need to use menu_get_object again to get "That one and only node referenced from the menu path". What if there's more than one node in the path? Or if you really want to base the block on a node from an entity reference? This becomes a non-issue with Page manager, making all blocks (panes) much more flexible and re-usable.

Panels

The most common use case however, is to hand over the layout, and rendering of the path, to Panels. Panels provides tools to define layouts, either in code or directly in the browser, and the lets you place content directly in the browser.

Conclusion

Both of these modules are very powerful, and relatively poorly documented, which has lead a lot of people to be frustrated about them. Understanding how to use them is however well worth it if you are building a larger site, especially since their approach to handling "pages", as well as layout, looks like they are going into Drupal 8 core, courtesy of EclipseGC's SCOTCH initiative. Relevant sandbox project

Further reading

Examples of other interesting things one can do with these tools:

If Context is used as a sectioning tool, Panels can work in tandem with it and be used as a layout tool.
Panels can interact with Display suite to provide it with a nice drag-and-drop UI.
Page manager and Contextual Administration can help building in "Context" sensitive menues and other helpful things for site admins/editors.


How to make Voting api not cache For my application with several different voters, I want the caching table (votingapi_cache) to never be populated. Is there a hook or a configuration I can implement so that no caching happens at all?

The function votingapi_add_results() is responsible for writing records to the votingapi_cache table. Immediately afterwards, it invokes hook_votingapi_results() which any module can use to wipe out the table.

For example:

/**
 * Implements hook_votingapi_results().
 */
function MYMODULE_votingapi_results() {
  db_truncate('votingapi_cache')->execute();
}


Print field with an array I have a field name called 'field_serial_571' that contains an array. I've tried several ways to display it and it only display blank space. I ran a debugging script (printr) and this is what I found:

[field_serial_571] => Array ([und] => Array ([0] => Array ([value] => 1)))

Does anyone know how to display results from a field with an array?

Assuming this is an entity (it looks like it probably is), you might want to look into using entity metadata wrappers. It'll make your theming life much easier.

Otherwise, to immediately display your field, this would work (assuming a node):

echo $node->[field_serial_571][LANGUAGE_NONE][0]['value'];

LANGUAGE_NONE is a constant for an undefined language, in your example the 'und' part of the array. It's best practice to use that constant rather than using 'und'.

Read even more about entity metadata wrappers here: http://www.pixelite.co.nz/article/how-use-entity-metadata-wrappers-drupal-7/


Add class for a date field I have a  content type "Task" with a Date field to define a deadline for tasks. What I'm trying to do is to add an extra css class to the field wrapper to indicate that today is the deadline. I can do it with JQuery, but its stupid...

So i'd like create a function in my custom module which checks the field date, compares it with today date and if it results that today is a deadline (or the deadline already past), adds an extra class to the wrapper.

Will be very appreciate for any help or advice.

this might be what are looking for Adding CSS Classes to Fields in Drupal

  Implementing any type of modular CSS requires fine grain control over
  classes in your HTML. In my last post, we looked at how we can easily
  add classes to blocks in Drupal using preprocess functions. Now let's
  apply the same technique to fields. Fields are a fundamental building
  block of any Drupal 7 site. Fields contain content and content is
  king. Before we dig in and start classing up our fields, let's look at
  how they are rendered to the screen.


How to implement variable caching of nodes based on published date in a Drupal 6 website? I have a Drupal 6 website and I want to write a module that will cache nodes based on the published date. Older nodes would be cached longer than newer nodes.  I plan to use cache_set(), cache_get() and nodeapi hooks to add the node to the cache and check if it is in the cache before loading. However I am not sure if my logic is correct. Can provide any tips to put me on the right track?

Boost could do this. Core can not due to the cache_page bin/table getting cleared on cron & node save. Boost has a cache expiration block that allows for different cache lifetimes.


How can I add a direct link to the edit account settings page in a menu? Ok, I must be missing something obvious, but I'm having trouble adding a link to user/%/edit to the main menu.  In the Menu UI, I clicked "add link," set the title to "Account settings," and then was at a loss about what to put for the path.  I know how to generate a link to the account edit page using views, which is what I've always done before, but this time I actually need to add the link to the "Main Menu."

Try this module menu_token , it allows to use tokens in menu

  Menu Token module provides tokens, that could be used in title or in path of menu items (links). For example, if you create a menu item with path: "user/[current-user:uid]", the url will be changed "on fly" to: "user/1" (assuming you are user 1).


Customize drupal commerce checkout page How do I customize Drupal commerce checkout page?  I selected shipping information, billing information and payments in the checkout form builder. But the layout the fields are customized and was wondering how to change the layout of the fields like First name, last name etc...

Customize Checkout Look and Feel

There was a recent commit that made the checkout process table-less in the Commerce Issue Que. It was reverted in favor of making such a large change to the codebase on a 2.x release. That code still exists and it's all possible using theme_ functions in your template.php

Go here
/modules/checkout/includes/commerce_checkout.pages.inc and look for functions that start with theme_
Add those functions that you
want to your template.php in your theme or a custom module
Change the function word "theme" with your theme name or module name.
Make an obvious change or two
Clear all caches and
then go through the checkout process.


Autocomplete on multiple fields Entity Reference This is my case:

I have a content type advertisement with some fields and an entity reference of content type product. The widget type of the entity reference is autocomplete.

These are my settings of the autocomplete field:

When I create an advertisement I can type in the name of the product. But the product has also other fields like cnk. How can I make sure the autocomplete will search on the name AND the cnk?

You can use the functionality Views: Filter by an entity reference view that comes with the Entity Reference module to search on more fields.

To use this functionality you need to change Entity selection mode to Views: Filter by an entity reference view instead of Simple (with optional filter by bundle) on the settings for your entity reference field.

First off you need to setup a View that lists your product nodes. Then add a display of the type Entity Reference.

You can exclude the field cnk from display but add it as a search field to the settings for the Format "Entity Reference List". If you don't exclude the field cnk from display it will show content from the field in the autocomplete widget.

No go back to the entity reference field and choose the view you just created under the settings for Views: Filter by an entity reference view.


Combine multivalue field rows with copy of same multvalue field Having a list of pdfs using pdfpreview for image-preview I want to add an additional formatted text-field to this ouput.
That's why I've created a copy of this field with a different formatter (e.g. rendered entity).
As this is a multivalue field I want to combine the values means having the new text-field underneath every preview-picture instead of having all preview pictures first and all rendered entities afterwards.

I've found the solution via media entities and "media pdf thumbnail"


Adding a taxonomy drop down to drupal search I am trying to add a drop-down containing taxonomy terms to my site's basic search. I have created a taxonomy term category and used search auto-complete module for providing auto-complete search functionality. Can anyone suggest me how to add taxonomy drop-down besides the search button on the search block and relate the drop-down selection with search text.

I think you will need to use custom search module. For auto-complete feature i think it is better to go with custom development rather than depending on contributed modules which will come with lot of unwanted features.

To preface :

You will need to use hook_form_alter() for add you custom field.
Then with the help of hook_search you can inject your custom search criteria using search query extract and search query insert.


Setting the default value for a text field as a variable in Form API I thought this would be straight forward but my lack of drupal knowledge is holing me back. I want to grab the email from the logged in user, and set it as the default value of the form. I can grab the email from the global user logged in, but cannot pass this to the form?

The email field is blank, but I have the email stored in $email1 I want to place this value in the text box, as the default field.

global $user;
    $user_full = user_load($user->uid);
    $email1= $user_full ->mail;
    echo $email1;

 $form['admin_email'] = array (
 '#type' => 'textfield',
 '#title' => t('Admin Email need email validation!!!'),
 '#description' => t('Please enter an Email'),
 '#default_value' => $user_full->mail,
 );

You don't need to use user_load($user->uid);. You already have a complete object inside global $user; variable. And don't forget PHP is not a natural languages. You can't just put whitespaces where you want them. In method call or property access, there should be no spaces around ->, it should be right next to object, and property should be right after arrow.

This line is sufficient for me:

'#default_value' => $user->mail,


How do I display page numbers in a book? I have my nodes organized using the book module. I would like to be able to display the page number at the bottom of the page. The pages would be numbered according to the order in the book outline. Is this possible? I even tried looking for a PHP code snippet I could put in book-navigation.tpl.php or similar.

You can add simple PHP code in your node.tpl.php

    <?php
      $allbook = book_toc($node->book['bid'],3);
     $allbook_chapter = array_search($node->book['mlid'], array_keys($allbook));
print $allbook_chapter;
            ?>

This code prints page number of current node. This in't better way of course.
Moving this logic to template.php is better solution.


How do I display a Taxonomy Term Description to a view in D7? I would also like to know how to display a custom field that you add to taxonomy terms.... D7

You will have to add a relationship to include the term data for the content(?) you are listing – then the term description will be available as regular View fields.

You can check out Learn Views with NodeOne, part 11: Relationships for a quick video on managing relationships.

Good luck!


Any way to do DISTINCT ON? I'm trying to create a query like this:

SELECT DISTINCT ON (field1, field2) field1, field2, field3 FROM table1

But can't figure out how to get DISTINCT ON narrowed down to a few fields in Drupal like that. Calling $query->distinct() just seems to structure the query like this:

SELECT DISTINCT field1, field2, field3 FROM table1

I did figure out a hacky way to add what I want by adding an expression before I add any fields like this:

$query->addExpression('DISTINCT ON (field1, field2) field1', 'field1');

Which creates:

SELECT DISTINCT ON (field1, field2) field1 as field1, field2, field3 FROM table1

I'm looking for a better way to this ?

You could try with the distinct() method for dynamic queries and see how it goes with your query.

There is an example to follow on the taxonomy module of the Drupal core, on the following line:

$node_types = db_select($revision_name)
->distinct()
->fields($revision_name, array('bundle'))
->execute()
->fetchCol();


How can I edit the 'Title' field label of a Node content type within a module? I'd like to do this in Drupal 8:

I need to change the label of the Title field on a custom content type  without using admin panels.

I know this is possible via the admin menu, but I feel like I should be able to have the module fully set up when it is installed.  Is there a flag in the content type's configuration file that I can add to override the default value?

Here's my node.type.employee.yml file

langcode: en
status: true
dependencies: {  }
name: 'Employee'
type: employee
description: ''
help: ''
new_revision: false
preview_mode: 1
display_submitted: true
third_party_settings: {  }

This is stored as a field override configuration. It's a separate config entity with the name core.base_field_override.node.your_node_type.title.


How do I turn off maintenance mode? Does anyone know how to turn off maintenance mode for brainfx?  I tried http://www.website.com/?q=user/login but that gives me a blank page (no html source or anything).  I tried the following query.

UPDATE `variable` SET `value`='0' WHERE 'name' = 'maintenance_mode';

It didn't affect any records.

I tried to find a $conf['maintenance_mode'] variable in the project, but it doesn't exist. Adding that $conf['maintenance_mode'] = false; in setting.php didn't do anything either.

How do I turn off maintenance mode?

Using Drush, you can run drush vset maintenance_mode 0 to disable the maintenance mode on a Drupal 7 site.


Migrate module only imports first line of CSV file I have a Migrate module class that works with CSV files and when I go through with the import it only goes through the first line of the CSV and then completes with a success message.  That one line is imported correctly and the data is in place, but I'm wondering why it continues to stop at the first line.

When I run the import again it does not import anything and completes with success message again, mostly likely because the first line is already imported.

Any ideas?

class UserMigration extends MyMigration {
  public function __construct($arguments) {
    parent::__construct($arguments);

    $this->description = t('Import Users');
    $columns = array(
      0 => array('username', 'Username'),
      2 => array('email', 'Email'),
    );

    $this->source = new MigrateSourceCSV(drupal_get_path('module', 'my_module') . '/Users.csv', $columns);
    $this->destination = new MigrateDestinationUser();
    $this->addFieldMapping('name', 'username');
    $this->addFieldMapping('mail', 'email');
    $this->addFieldMapping('roles')
         ->defaultValue(DRUPAL_AUTHENTICATED_RID);
    $source_key = array(
      'username' => array(
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
      )
    );
    $this->map = new MigrateSQLMap($this->machineName, $source_key, MigrateDestinationUser::getKeySchema());

  }
}

It's possible that the CSV is saved with the wrong line endings. Try saving the CSV file with Unix-style line endings. By default, I believe Migrate expects a Unix format text file.


Running Drupal 6 with PHP 5.3 and Maintaining Security I have a number of Drupal 6 sites that I can't upgrade at this time due to sheer lack of time to do so (it would be a major overhaul). Therefore, I am required to continue running PHP 5.3 on my server, but it is already EOL, and there are security fixes that have not been applied to it.

Are there other people here that are using Drupal 6 and PHP 5.3, while keeping their PHP secure? If so, how are they doing it? Is there a source for PHP 5.3 with backported security fixes, like an LTS version? I've seen Zend's version of that, but can't afford it. I saw Red Hat has RPMs with some security fixes backported into PHP 5.3, but not the most recent ones, at least as far as I can tell.

Here are the patches I'm using for D6. Some of these issues will have been committed, thus they don't need a patch anymore.

Views
http://drupal.org/node/853864#comment-6465560 - views_get_default_view() - race conditions and memory usage
http://drupal.org/node/402944#comment-4650020 - Persistent caching for unpack_options() calls from building displays
http://drupal.org/node/1372388#comment-5370432 - Inline/Remove recursion in views_object->unpack_options to improve performance
http://drupal.org/node/465332#comment-4756670 - Strict warning: non-static method should not be called statically
http://drupal.org/node/893128#comment-4894754 - Strict warning: Declaration of * should be compatible with that of views_handler::*
http://drupal.org/node/1265138#comment-4928988 - Notice: Undefined variable: teaser in views_plugin_row_node_rss->render()
http://drupal.org/node/1432242#comment-5807802 - Notice: Undefined index: size in views_db_object->export_row()

Views Bonus Pack
http://drupal.org/node/1223910#comment-4756506 - Strict warning: is_a(): Deprecated

Views Bulk Operations
http://drupal.org/node/1782662#comment-6469236 - Notice: Undefined index: HTTP_USER_AGENT in views_bulk_operations_form()

Views Datasource
http://drupal.org/node/1265190#comment-4929150 - Notice: Undefined property: stdClass::$name in views_plugin_style_xml->option_definition()

Views Slideshow JCarousel
http://drupal.org/node/1885586#comment-6926004 - php notices

Here are some of the more popular modules as well

Calendar
http://drupal.org/node/999514#comment-4761150 - Strict warning errors for views plugins

CCK
http://drupal.org/node/1118792#comment-4358322 - array_keys() expects parameter 1 to be array, null given in content_multigroup.node_form.inc
http://drupal.org/node/1244534#comment-4845816 - Notice: Undefined index
http://drupal.org/node/1247732#comment-4857954 - Undefined index: _remove
http://drupal.org/node/1156096#comment-4868230 - Notice: Undefined index: title/description in content_storage()
http://drupal.org/node/1251146#comment-4871780 - Notice: Undefined index: #children in template_preprocess_content_field()
http://drupal.org/node/1251160#comment-4871816 - Notice: Undefined index: #field_info in fieldgroup_form_alter()
http://drupal.org/node/1265080#comment-4928778 - Notice: Undefined property: stdClass::$broken in content_handler_field->render()
http://drupal.org/node/1316510 - fix undefined index '#id' notice in form_alter hooks
http://drupal.org/node/533610#comment-5157454 - Notice: Undefined index: safe in theme_text_formatter_default()
http://drupal.org/node/1762506#comment-6411880 - Notice: Undefined property: stdClass::$field_* in content_rules_field_has_value()

CTools
http://drupal.org/node/1226098#comment-4765262 - Strict warning: Only variables should be passed by reference
http://drupal.org/node/1334894#comment-5215962 - Warning: Invalid argument supplied for foreach() in views_content_views_content_type_render()
http://drupal.org/node/1510118#comment-5807950 - Strict warning: Creating default object from empty value in views_content_views_content_type_admin_info()

Context
http://drupal.org/node/866208#comment-4845268 - Notice: Undefined property: stdClass::$taxonomy in context_node_condition() on line 352

Date
http://drupal.org/node/802722 - Extra comma in output when using "display from and to dates" on Display fields configuration
http://drupal.org/node/1223956#comment-4756746 - Strict warning: Creating default object from empty value in date_handler_fields
http://drupal.org/node/1948238#comment-7200236 - Strict warning: Declaration of date_handler_field_multiple::pre_render()

Features
http://drupal.org/node/1516900#comment-5833834 - Notice: Undefined index: group in views_handler_dependencies()
http://drupal.org/node/1515878#comment-5833794 - Strict warning: Only variables should be passed by reference in content_features_rebuild()

FileField
http://drupal.org/node/1180508#comment-4872304 - Warning: array_merge() Argument #2 is not an array in filefield_widget()
http://drupal.org/node/1164892#comment-4500360 - Warning: Trying to get property of non-object in filefield_field_sanitize()
http://drupal.org/node/1317424#comment-5146998 - Notice: Undefined index: fid in filefield_widget_process
http://drupal.org/node/1415840#comment-5514392 - Fatal error: Cannot unset string offsets
http://drupal.org/node/1677208#comment-6213652 - Notice: Undefined index: data in theme_filefield_widget_preview
http://drupal.org/node/1775708#comment-6440138 - Notice: unserialize(): Error at offset 0 of 1 bytes in filefield_get_node_files()

ImageAPI
http://drupal.org/node/1189884#comment-4608576 - Allow for custom code to be inserted into the convert command before it is ran
http://drupal.org/node/1201914#comment-4663120 - Add in the ability to "nice" the convert process
http://drupal.org/node/1250348#comment-4868656 - Fix divide by zero errors.
http://drupal.org/node/1766064#comment-6434498 - User error: ImageMagick reported error code 1. Message: convert: no encode delegate for this image format

Imagecache
http://drupal.org/node/1243258#comment-4841244 - use lock.inc instead of a file lock
http://drupal.org/node/1761108#comment-6407780 - Notice: Undefined index: filepath in theme_imagecache_formatter_default()

jQuery Update
http://drupal.org/node/1067290#comment-6516884 - Fix jQuery 1.7 for Drupal 6

Rules
http://drupal.org/node/1250384#comment-4868884 - Strict warning: Only variables should be passed by reference in rules_core_action_execute()

Core patches
http://drupal.org/node/496184#comment-5787602 - db_set_active errors out if db_connect fails. Add in the ability to handle this gracefully (don't always call _db_error_page)
http://drupal.org/node/764726#comment-5787642 - (Shared taxonomy patch) hook_taxonomy_term_presave() is missing
http://drupal.org/node/905156#comment-5791724 - PHP notice in form_builder function
http://drupal.org/node/1006938#comment-4661790 - Remove PHP warnings from legacy PHP4 XML parser for new update status release history XML
http://drupal.org/node/352180#comment-2562140 - Better, multi-site friendly "www." addition/removal in .htaccess
http://drupal.org/node/939810#comment-5791876 - Notice: Undefined index: key in format_xml_elements()
http://drupal.org/node/985814#comment-5791916 - Undefined index: configurable in actions_synchronize()
http://drupal.org/node/557542#comment-4989990 - Cache module_implements()
http://drupal.org/node/1317236#comment-5146174 - Race condition in file_delete: Warning: unlink() No such file or directory in file_delete()
http://drupal.org/node/1004820#comment-5171678 - Notice: Undefined index: type in dblog_build_filter_query()
http://drupal.org/node/1345204#comment-5259212 - Optimize element_children()
http://drupal.org/node/753064#comment-5274348 - _menu_link_translate() might avoid calling _menu_load_objects()
http://drupal.org/node/261148#comment-5798704 - menu_masks variable is empty (race condition)
http://drupal.org/node/1688282#comment-6240944 - Unknown error: Function split() is deprecated in _filter_autop()
http://drupal.org/node/521838#comment-6375266 - Clean up drupal_get_schema_versions()
http://drupal.org/node/1710656#comment-6474030 - If item is hidden in _menu_tree_check_access() skip it right away.
http://drupal.org/node/1882556#comment-6913038 - Notice: Undefined index: REMOTE_ADDR in includes/bootstrap.inc on line 2835
https://www.drupal.org/node/2292125#comment-8912499 - PHP 5.5 - preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in decode_entities() (line 349 of includes/unicode.inc)

Most of the issues I'm following that have the word notice in it
https://www.drupal.org/project/issues/search?text=notice&projects=&project_issue_followers=mikeytown2&status[0]=Open&categories[0]=1&issue_tags_op=%3D&assigned=&submitted=&issue_tags=&&order=field_issue_version&sort=asc

And the ones that contain the word warning
https://www.drupal.org/project/issues/search?text=warning&projects=&project_issue_followers=mikeytown2&status[0]=Open&categories[0]=1&issue_tags_op=%3D&assigned=&submitted=&issue_tags=&&order=field_issue_version&sort=asc

Query used to find the worst offenders for php issues: http://groups.drupal.org/node/170339


How can I render an image stocked in a custom module with an image style? I'am learning Drupal 8, and I would like create a custom module who create a block to add share button. The link of this button should be an image who stocked in my custom module. I would like use an image style on my picture.

Last but not least, i want use a render array.

In my build() method of my customblock.php i have whrite :

//create url link
$url = Url::fromUri('https://www.facebook.com/sharer/sharer.php?u='.$base_url.Url::fromRoute('<current>')->toString());

//create uri image
$pathmodule=drupal_get_path('module', 'share_configurable');
$urifacebook=$pathmodule.'/src/img/facebook.png';

//render array of link
if ($this->configuration['network']['facebook']=='facebook'){
  $build['link_facebook'] = [
    '#title' => [
      '#theme' => 'image_style',
      '#style_name' => 'thumbnail',
      '#uri' => $urifacebook,
    ],
    '#type' => 'link',
    '#url' => $url
  ];
}

The link is create, but the image is not render... Can you help me please ?

Thank to Hudri :
Image styles only work with managed files (uploaded, with entry in DB), not with static assets. Since this is a static asset anyway, just provide the correct size in your module.


How to get administration views to work? As my content began to expand into a large repository I started to miss the feature of being able to filter content by a simple "title contains" criterion. I found out Administration Views that got installed by Admin Menu. However, the content view is contaminated by a known bug. It allegedly comes from incompatibility with VBO. This prevents the view from functioning or being edited.

Is anyone successfully running admin views, caring to list the module versions for Views, VBO, Admin Menu?

I'm sure your problem is already gone by now but for those who might be searching for ways to make Admin Views and VBO work, the versions I'm using are 7.x-1.3 and 7.x-3.2 respectively.

You would need to clear Drupal cache for the default admin pages to be overridden by the newly added Admin Views.


Generating Views Block to list Taxonomy Terms of nodes curently visible in a Views Page I have a Views Page which lists nodes of the content type, Article. This page also contains pagination since I configured it to display no more than 6 articles per page.

So for example, if I have 10 articles, 6 of them would be displayed on page 1 and the remaining 4 would be on page 2. In addition, Article has a term reference field called Tags.

I was wondering if it's possible to have a Views block I can attach to my original View I mentioned earlier (a list of Article content type) that lists Tags belonging only Articles currently visible on the original View on one of the paginated pages.

Going again with my example, I want this Views block to display Tags from the 6 Articles when I'm on page 1. Likewise, I want this block to display Tags from the remaining 4 Articles when I'm on page 2.

Here's a little graphic of what I'm trying to do.
http://i.imgur.com/7rPsLaz.png

Also, I'm not sure if this info is relevant but I plan to use the Context module to attach this Views Block to the Views page.

I was thinking along the lines of Contextual Filters but I'm not quite sure what arguments I would use.

Any help is appreciated.

Offhand i'm not sure how Context will help you do this ... off the top of my head this solution came to mind.

In your 1st view make the Tag field a hidden field the view so the View knows about it.
Use hook_views_pre_render to loop through the results (and maybe respect page offset and # of items per page -- you can get that from the $view object) and grab your view field Tag values and store them into an array.
Still in hook_views_pre_render you can set $view->attachment_after = $some_string; where $some_string is like the list of your Tags.

In code it will look something like this:

function MYMODULE_views_pre_render(&$view) {
  if ($view->current_display == 'VIEW_ID') {
    $tags_on_page = array();
    // $_GET['page'] has page number.
    // $views->items_per_page has items per page count.

    $page_offset = intval($_GET['page']);
    // this is somewhat wasteful, but easier than a loop at the moment.
    $paged_results = array_chunk($view->result, $view->items_per_page, TRUE);

    // Build up the Tag list for X page of the results.
    foreach ($paged_results[$page_offset] as $i => $result) {
      $tags_on_page[] = $result->value; // save the taxonomy term name to the tags list.
    }

    // Take our tags and build a block of HTML to embed after the view.
    // Alternatively, maybe take these tag values and pass them as parameters
    // to a new view we attach after programmatically -- thats more work.

    // if you know the url prefix you've given these taxonomy terms use it here, or use something like entity_uri().
    $num_tags = count($tags_on_page);
    if ($num_tags) {
      for ($i=0;$i<$num_tags; $i++) {
        $term = $tags_on_page[$i];
        $tags_on_page[$i] = l($term, '/URL/ALIAS/BASE/PATH/TO/TERM' . $term);
        // or, ... $term may have a path value already ... I cant remember :).
        // $term = taxonomy_get_term_by_name($tags_on_page[$i]);
        // $term_path = entity_uri('taxonomy_term', $term[0]);
        // $tags_on_page[$i] = l($term[0]->name, $term_path);
      }
      $links = implode('
', $tags_on_page);
      $view->attachment_after = '

Related Tags
' . $links . '
';
    }

  }
}


Need full Taxonomy URL to be valid else redirect 404 I have two taxonomy term pages with the following details:

Term id : 1 , url alias : fruits
Term id : 2 , url alias : fruits/apple

When I am typing url http://www.example.com/fruits/apple then content related to term id 2 is getting loaded which is correct

But the problem is when I am typing http://www.example.com/fruits/apple1 which is not a valid url then the content of Term id 1 is getting loaded since it is matching till "fruits". In such scenario I want the site to be getting redirected to a 404 page instead of matching termid of "fruits".

I need the full taxonomy url to be valid or redirect to 404.

I am using views taxonomy term page (Default one which by default remains inactive) where a wild card character is there taxonomy/terms/%.

Please help. I cant find a suitable solution for the same.

If you are using contextual filter, then there is validation criteria in settings of taxonomy term name you have selected.

Then add filter value type as taxonomy term name and add action as page not found.

You will get the result.


Update a content type field's allowed values programmatically I have a list field in the content type and in the config table , the field storage details saved as follows :

collection:
name: field.storage.node.field_ip_range_sec_zone
data: a:17:{s:4:"uuid";s:36:"9d20e561-e39c-4c11-b100-ff3a29a75267";s:8:"langcode";
                                            s:2:"en";s:6:"status";b:1;s:12:"dependencies";a:1:{s:6:"module";a:3{i:0;s:17:
                                        "field_permissions";i:1;s:4:"node";i:2;s:7:"options";}}s:20:"third_party_settings";
                                    a:1:{s:17:"field_permissions";a:1:{s:15:"permission_type";s:6:"public";}}s:2:"id";
                                s:28:"node.field_ip_range_sec_zone";s:10:"field_name";s:23:"field_ip_range_sec_zone";
                            s:11:"entity_type";s:4:"node";s:4:"type";s:11:"list_string";s:8:"settings";a:2:
                        {s:14:"allowed_values";a:3:{i:0;a:2:{s:5:"value";s:2:"E1";s:5:"label";s:2:"E1";}
                i:1;a:2{s:5:"value";s:2:"C2";s:5:"label";s:2:"C2";}i:2;a:2{s:5:"value";s:2:"D1";s:5:"label";s:2:"D1";}}
            s:23:"allowed_values_function";s:0:"";}s:6:"module";s:7:"options";s:6:"locked";b:0;s:11:
        "cardinality";i:1;s:12:"translatable";b:1;s:7:"indexes";a:0:{}s:22:"persist_with_no_fields";
    b:0;s:14:"custom_storage";b:0;}

As you can see there is Allowed values (E1,C2,D1) , and now i want to add an additional value to the allowed values , How can i do that ?

WHAT I HAVE TRIED

I could get the allowed values using the following :

$entity_type = 'node';
$bundle = 'ip_range';
$field_name = 'field_ip_range_sec_zone';
$ip_sec_zone_storage_values = \Drupal\field\Entity\FieldStorageConfig::loadByName($entity_type, $field_name);

But dont know how to update it , Any idea ??

Those are settings, you get them using $ip_sec_zone_storage_values->getSetting('allowed_values'),, in there you'll find those settings, you can add another one, set the settings back with setSetting('allowed_values', $allowed_values) and then ->save() to save the field storage config:

$allowed_values = $ip_sec_zone_storage_values->getSetting('allowed_values');
// The new value.
$allowed_values[$ipseczone] = $ipseczone;
$ip_sec_zone_storage_values->setSetting('allowed_values', $allowed_values);
$ip_sec_zone_storage_values->save();


Custom Migration not appearing in UI I am trying to do a simple CSV import into a node using the Drupal Migrate module. I have created the .module and .info files and double-checked them against several examples online. I have also created a .inc file including

class CrfmMigration extends Migration

I have enabled my module from the Modules Administration panel and there are no errors. However, when I go to the Migration UI, my migration class isn't listed at all. The Beer and Wine samples show up just fine, but my custom migrate class is nowhere to be found. I'm not even sure which file the problem could lie in. I am more than happy to provide any additional information as necessary to figure this out. I prefer not to use Drush if possible, but I will if there is no other option.

This might happen for a couple of reasons. Here are some pointers:

Make sure your module implementing the migration is enabled (I believe you must have checked that already).
Make sure your migration classes are registered with Drupal using the files directive in the .info file.
Make sure you clear the cache, especially the class registry.

I hope it helps! I'm currently stuck in a D8 migration.


How to perform an operation every time a node is viewed? When writing a module, how can I perform an operation every time a node is viewed by a user?

You can use hook_nodeapi() in Drupal 6 and check that the $op argument is 'view'. In Drupal 7, this has been changed to hook_node_$op() where $op is replaced by the value you would have checked for in the Drupal 6 version. So you would use hook_node_view(). For more details about the changes from Drupal 6 to Drupal 7 see http://drupal.org/update/modules/6/7#remove_op.


Make Commerce Kickstart home page show up at a different URL By default, the store is the front page in Commerce Kickstart.  I want to have a different page as the front page, but be able to switch to Commerce Kickstart by clicking on a menu link.  However, when I change the front page to be my welcome page in Site Information, the store is no longer accessible.  How do I link the front store page to a link in a menu?  Essentially, I want the commerce kickstart store to be accessible from http://homepage/store.

The front page on Commerce Kickstart is node. The content is defined via blocks. So if you want to change the front page to another page, you could create a page and set it as the front page in the admin. None of the blocks should show up. If you want to make the contents of the current node page visible on a new or custom page, then you'll need to change the block configuration of all of the blocks that are currently visible on node and configure them to show up on another page.


Credit card and check payments in one order type I've created a store in Commerce 2.  The store has 1 order type currently, which uses the default workflow (Draft->Completed/Cancelled).  There is also 1 order item type only and all products belong to it.  We currently have 1 payment gateway for people to pay by credit card (live).

I am now being asked to add payment by check as a possibility.

I added a new "Check" payment gateway using the "Manual" plugin and things looked good, but when choosing it, the order gets the "Completed" status.  (Payment is "Pending" as expected.)  This is rather counter-intuitive for the staff.  Another status (even staying at "Draft") would be preferable.

I though to switch the order type to the "Default, with Validation" workflow (Draft->Validation->Completed/Cancelled).  This seems like to right solution for people paying by check... But the vast majority of people pay by credit card and their order should be immediately be completed without any validation.

I also read up on creating a 2nd order type with the "Default, with Validation" workflow, but that seems to entail having a completely separate order item type (and therefore separate products!) so it seems like the wrong way to go.

Is the solution to create a custom workflow that encompasses both
possibilities?  (With a way to transition from "Draft" to "Completed"
for credit card payments and from "Draft" to "Validation" for check
payments.)
Or is it better to use the "Default, with Validation" workflow and
have a subscriber wait for when an order is set to the "Validation"
state, verify the payment gateway and advance the credit card orders
to "Completed" automatically? (seems a bit hack-y)
Is there another solution to this (I assume) common problem that I
missed?

Seems like I was wrong about the 2nd order type.  Here's what I ended up doing:

I created a 2nd Order Type with the "Default, with Validation" workflow and a 2nd Order Item Type pointing to the new Order Type.

Then I used the "hook_commerce_order_presave" hook to change the order type from the default first Order Type to the other at the "review" step of the checkout.

Still, to me, this seems like a common enough occurrence (checks & credit cards accepted in one store) that there should be a no-code solution.  If someone know it, please share!


On what event does the cron begin its execution? I have a site which requires periodic tasks to be done (sending content update notification / subscription, etc); which are configured on cron run. The cron run is setup to run after every "3 hours" at admin > config > system > cron.

I (user 1) did not visit the site for 10-12 days, while some of the other authenticated users did some activity like commenting / adding content. I have enabled notification emails whenever any user adds / edits any content or comment.

Last night when I logged into the site, I received notifications for the period of 10-12 days (period for which I did not log in to the site). While, as per the expected behavior I should have been receiving the notifications on the cron run after the user activity.

I checked to see the logs, and during this days I can see only the following message under the type "cron"

  Attempting to re-run cron while it is already running.

And strangely, I could see

  Cron run completed.

just before 5 secs of the message:

  Session opened for admin-user.

So, it is clear that I did not receive the notifications because the cron did not run during this period of time.

So, my question is why did the cron not run for these days? What is the exact event which triggers cron to start running? I understand that in Drupal 7 cron.php is called along with a token value to run the cron. But who / what does this call? Or do the Admin users need to log into trigger this action?

UPDATE: The site is on a dedicated server owned by the company. I have access to it as root user. And obviously don't have a cpanel to it ;-) And I have not set any other application to like crontab? Do I need to do so? If so how?

So, my question is why did the cron not run for these days? What is
  the exact event which triggers cron to start running?

Poormans cron is D7 default cronjob handler, which invokes cron hooks. But it depends on traffic, when a user visits a page it will check last time at which cron was run, and schedule it to run if needed according to interval set.

Summary : This is not reliable if cron has to be run daily. To do so open up crontab from terminal (crontab -l will list the jobs, crontab -e will let you edit jobs) Ex:

0 0 * * * wget -O - -q -t 1 http://<yoursite>/cron.php?cron_key=<yourkey>

Will schedule cron job @midnight daily.


A module similar to Innovation News Module for Drupal7? Hello I am looking for a module similar to Innovation News so that news content can be developed collaboratively, placed into editions, and exported as XML documents.

It seems Innovation News is on a dead line.

Anyone could help me?

I think you can easily replace this module by a bunch of other module and that maybe the reason why the module is not anymore maintained. I will try to give you some clues to archive your goal, but maybe you need code a bit.

Flag - Flag allows you to associate content to an edition.
Views - Flag work with views, that allows you create views for each edition
Views Bulk Operations - With Views and VBO you can easily create control panel for each edition.

I hope this can help you.


Module to display blank theme template I am creating a module with a map displaying markers. Do I need to create a page/ node or can I load the drupal theme without any page / node content and add my code.

<?php /**
 * Implementation of hook_menu.
 */
function projects_map_menu() {
  $items = array();

  $items['projects-on-map'] = array(
    'title' => 'Projects on Map',
    'page callback' => 'projects_map_page',
    'access callback' => 'user_access',
    'access argument' => array('access nodes'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Page callback
 */
function projects_map_page() {
//render them current theme
//custom code
}

It is possible to create this functionality using the Geolocation Views module. Here is a quote about it (from the module's project page):

... is sub-module for Geolocation Field to display markers on Google Map using Views 3.
Module support:

show content in Info Windows
custom marker images
markers as links
multiple maps on a single page
support MarkerClusterer


how to specify the file directory in drush config:status drush config:import has the --source flag to specify where the import should come from.
drush config:export has the --destination flag to specify where the import should go.
I am trying to automate a system for determining if update hooks have modified configuration, to avoid the problem documented in #3110362 If an update hook modifies configuration, then old configuration is imported, the changes made by the update hook are forever lost.
To do so I will export the config to a temporary directory, like:
drush config:export --destination=/tmp/check-issue-3110362

Then I will run the updates
drush updb -y

Then I want to run a diff between the database config and the config in /tmp/check-issue-3110362, but the following does not work:
drush config:status --source=/tmp/check-issue-3110362
# The "--source" option does not exist.
drush config:status --destination=/tmp/check-issue-3110362
# The "--destination" option does not exist.

How can I tell drush config:status to use a specific directory to check against the database?
My version of Drush is 10.3.6

There's no option to do this with drush config:status. See the drush 10 documentation for config:status.
Presumably, you want to check if the config has changed so you can export it to your sync directories. Why not export it to them directly? If there are no changes, there will be no changes. But if there are changes, you'll see them in your repository, e.g. with git status.
I've always used Moshe's recommendation from comment #7 in your linked issue:

You must get your configuration right before you run a config import. Specifically, the config in the import must represent the values AFTER hook_updated_n runs. The developer workflow I advocate is to run the hook_update_n() locally, run drush config:export, and and then commit the results. Only then is the saved config ready to be imported.

I.e., start with a site in a clean state in your local environment:

Update your project(s) with composer.
Run drush updb to perform the db updates
Run drush cex to export any config changes made during those updates
Add any changes to your repo, commit, and push.
Pull the changes on your new environment
Run drush deploy


How to add AJAX call back from another AJAX result in a form I want to use 2 AJAX call back within a form. The scenario is like I am having a text field and a Search button which is defined in the form alter function. After entering a text and clicking on the Search button, will display some matching strings with some other information from database as an HTML in ul li a format.

I had made each string as a form element link and displaying under the search field. Now, I need to add AJAX callback to this link and after clicking on any string, the whole HTML content has to be removed and some other new text fields should be displayed in the form and the selected string should be placed on the text field.

Please see below codes.

FORM ALTER

  $form['searchbutton'] = array(
      '#type' => 'button',
      '#value'=> t('Search'),
      '#id'   => 'search_button',
      '#ajax' =>  array(
          'callback' => 'ajax_search_callback',
          'wrapper' => 'search-list-wrapper',
          'method' => 'replace',
          'effect' => 'fade',
          'progress' => array('type' => 'none'),
        )
     );

Below code is the first AJAX call on button click

/**
     * AJAX call back
     */
function ajax_search_callback($form, $form_state) {

//getting matching list from database with respect to search text
// $search_results

 $form['link-lists'] = array(
        '#type' => 'item',
        '#prefix' => "
",
        '#suffix' => "
",
    );
 foreach ($search_results as $key => $result) {
        $result_html = "
" . $result['title'] . "

" . $result['description'] . "
";

        $form['link-lists']['options'.$key] = array(
            '#type' => 'link',
            '#prefix' => "
",
            '#suffix' => "
",
            '#title' => $result_html,
            '#href' => '#',
            '#options' => array(
              'html' => true,
            ),
            '#ajax' => array(
              'wrapper' => 'search-list',
              //'method' => 'html',
              'callback' => 'select_ajax_callback',
            )
      );

 }
  $commands = array();
  $commands[] = ajax_command_replace('#descriptions-list', drupal_render($form['link-lists']));
  $page = array('#type' => 'ajax', '#commands' => $commands);
  return $page;

}

I think, the second AJAX call back select_ajax_callback given for the form item link is not correct. It would be thankful if anyone can help me on below questions?

How to set callback for a form item link? Please correct me.
How I will get $form and $form_state values in the function select_ajax_callback. And in this function I need to return another form element which is already defined in the form alter.

Thank You.

You are adding form elements in the ajax callback. These will never work, as the form has already been cached before the ajax callback is reached. You need to add your form elements in the original form definition, or a _form_alter hook. Use values in the form state to determine whether or not the form has already been submitted.


Show blog author info (related content) I have two content types. Blog and Author. On Blog content type I have entity reference field (blog_author) where admin can find author of the blog (Author content type).

Now I have a view that is supposed to show Author image and name (fields on Author content type) on the sidebar of blog post. The settings I have on my view:

Filters (published)
Relationships (referencing field blog_author), require this relationship.

But when I go see blog page it always show same author on each blog post (newest Author). Is my relationship somehow wrong? Should it be "referenced field blog_author" as there is two different entity reference for this field. EDIT: Though I did try this but with same result. So this is why I'm bit baffled now that how to do it. I thought relatioship would be enough but do I need to use contextual filters with this too?

Views settings:

Relationship:

Assuming the author of the blog is the same as the field and content type 'author' when a blog is created, I would suggest using core profile information for the author and use the Author Pane Module:

  Author Pane is a block of information about a given user, like those
  typically found on a forum post, but can be used in other places as
  well. From core, it collects the user picture, name, join date, online
  status, contact link, and profile information. In addition, any module
  or theme can feed it more information via the preprocess system. All
  of this information is then gathered and displayed using a template
  file.


Override theme for date field output? I have a field that accepts a date range using the Date module.  This is the theme function for outputting the date (found in sites/all/modules/contrib/date/date.theme):

/**
 * Returns HTML for a date element formatted as a range.
 */
function theme_date_display_range($variables) {
  $date1 = $variables['date1'];
  $date2 = $variables['date2'];
  $timezone = $variables['timezone'];
  $attributes_start = $variables['attributes_start'];
  $attributes_end = $variables['attributes_end'];

  // Wrap the result with the attributes.
  return t('!start-date to !end-date', array(
    '!start-date' => '' . $date1 . '',
    '!end-date' => '' . $date2 . $timezone . '',
  ));
}

I somehow need to override that and replace the 'to' in the return with a hyphen... I know, it's nitpicky but it underlines a more important point - I honestly have no way to alter this.  I've tried overriding it in my template.php but that doesn't take.  I literally just copy and pasted this code but replaced theme in the function with the actual name for my theme.

So yeah... how do I alter this theme function "the Drupal way"?

With the help of hook_theme_registry_alter you can override(actually by passing) any theme function.

Usually module's will define their theme functions in hook_theme(), however using hook_theme_registry_alter you can alter those information.

For your case below code will achieve the desired functionality,

/**
 * Implements hook_theme_registry_alter().
 */
function <my_module>_theme_registry_alter(&$theme_registry) {
  if (isset($theme_registry['date_display_range'])) {
    $theme_registry['date_display_range']['function'] = 'theme_custom_date_display_range';
  }
}

/**
 * Returns HTML for a date element formatted as a range.
 */
function theme_custom_date_display_range($variables) {
  $date1 = $variables['date1'];
  $date2 = $variables['date2'];
  $timezone = $variables['timezone'];
  $attributes_start = $variables['attributes_start'];
  $attributes_end = $variables['attributes_end'];

  // Wrap the result with the attributes.
  return t('!start-date - !end-date', array(
    '!start-date' => '' . $date1 . '',
    '!end-date' => '' . $date2 . $timezone . '',
  ));
}

So whenever you call theme('date_display_range', $variables), theme_custom_date_display_range() function will be invoked instead of theme_date_display_range().

Don't forget to clear the caches after adding hook_theme_registry_alter


How I can create a user programatically using user registration form? How I can create a user programatically in drupal 8. I am using the following code to generate user registration form.

$account = $this->entityTypeManager->getStorage('user')->create([]);
$form = $this->entityFormBuilder->getForm($account, 'register');

and form_sate values using the following code.

$form_state = (new FormState())->setValues(['name' => 'user1', 'pass' => 'pass']);

Now how can submit this form using the above form_state values?

I think you needn't use the registration form as you have mentioned. You can use the following code to create a new user:

if (!user_load_by_mail('email_id')) {
  $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
  $user = \Drupal\user\Entity\User::create();

  //Mandatory settings
  $user->setPassword('your_password');
  $user->enforceIsNew();
  $user->setEmail('email_id');
  $user->setUsername('user_name'); //This username must be unique and accepts only a-Z,0-9, - _ @ .

  //Optional settings
  $user->set("init", 'email');
  $user->set("langcode", $language);
  $user->set("preferred_langcode", $language);
  $user->set("preferred_admin_langcode", $language);
  //$user->set("setting_name", 'setting_value');
  $user->activate();

  //Save user
  $result = $user->save();
}

You can ensure that an user with same email id doesn't exist using user_load_by_mail(), and then proceed with the user creation.


How to make the radio field checked by default? I have a field group which consists of a radio box and other fields. This field group can have multiple values. My radio box field have two options and the first is checked by default. But when I add the second value (of the field group) – my radio field has no checked option, both options are empty (in the newly added field group). Is it possible to make the first checkbox option always checked?

Here's the short video showcasing the problem: https://www.dropbox.com/s/366xt4q57ryvteu/drupal-radio-issue.mp4?dl=0

I canno't comment to suggest you a solution, but it's probably due to the module field_group (or fieldgroup).

You should try the same content type configuration by using field_collection, because i have never faced any issue with this module.

1/ You create a new field type : field collection. You setup the field with an unlimited number of occurrences.

2/ You go to structure > field collection and add your fields.

I hope it help

Cheers.


Accessing a block types content programatically I have created a block type in the drupal 8 UI (structure/block/block-content/types ) that has two fields that are just strings. I then created 4 pieces of content using that block_type. How do I access the content created by the block type in hook_preprocessor_html programmatically?

This is a cutdown version of the function to access the block entities.

function _access_content_block_fields_build_arr($bidArr, $fieldRequestArr)
{

    $return = array();
    $blockElements = array();
    $blocks = \Drupal\block_content\Entity\BlockContent::loadMultiple($bidArr);
    foreach ($blocks as $block) {
        foreach ($fieldRequestArr as $fieldRequest) {
            $blockResult = $block->get($fieldRequest)->getValue();
            $blockElements[$fieldRequest] = $blockResult[0];
        }
        $return[] = $blockElements;
    }

    return $return;
}

purencool.com/accessing-a-block-types-content-programatically is the entire function for image fields url as well


Install module from URL to site directory instead of /all At http://drupal.local/admin/modules/install, when I install modules by entering a URL, they get saved to sites/all/modules.  I have a multisite setup, and I need them to go to sites/SITE/modules.

Any way to control that?

The update manager will only install modules to sites/all/modules unfortunately (see this page), so it looks like you'll have to FTP/SCP/whatever them to your server.

There are some advanced installation methods here, but installing modules into specific directories is not something the update manager can do.

Alternatively, you should definately try Drush if you're not using it already.  There's a pretty good tutorial on how to set up Drush for a multisite here.

Drush homepage

Drush project page

Drush DO page

Drush cheatsheet

Drush guide


Formatting options in Webform Select field I have a select field on a webform with 20+ options for the user. The default is a long list of options to select from. Is there any way to have the options broken into columns for the user to choose from so the webform doesn't end up an excessively long form?

Take a look at Chosen module can help you.


How to link to a translated node? I am using Entity Translation module.

My Basic Page content type is using field translation, and I create a node (mysite.com/node/1 for English, mysite.com/de/node/1 for German).

Now in the body field of another node, I hyperlink some text to 'node/1'. But if I am viewing the site in German and I click that link, it reverts back to English.

Is the answer to provide a translation for the body field, hyperlinking to 'de/node/1' instead? I guess this would work, but seems like a lot of extra work for content editors?

Or am I missing something easy? I tried using Path Translation module (part of i18n package), but it doesn't recognise 'de/node/1' as a valid path.

As usual, there is a module for that! :) Check out Multi-Language Link and Redirect (MultiLink). It was a bit buggy when I was testing it 5 months ago so I didn't include it in my Drupal 7 Multilingual Sites book (well, it's referred to in the appendix, page 112), but it should be working by now. Have fun!