How do I create a list with the previous and next referenced entities of the one being viewed? I have 2 content types: Books and Chapters.

Books have an entity reference field that can accept unlimited values.
Chapters have an entity reference field (single value) that corresponds to a book.

These entity reference fields are "linked" with the Corresponding Entity References module.

My goal is to create a block that will be displayed at the top of the Chapter nodes that will act like a pager of some sort and will display the previous and next chapters from the one that is being viewed.

For example, when someone views Chapter 1 of a book, the block will show:

Chapter 1 (no link)
Chapter 2 (link to Chapter 2)
Chapter 3 (link to Chapter 3)
Chapter 4 (link to Chapter 4)
Chapter 5 (link to Chapter 5)

When someone is viewing Chapter 10, the block will show:

Chapter 8 (link to Chapter 8)
Chapter 9 (link to Chapter 9)
Chapter 10 (no link)
Chapter 11 (link to Chapter 11)
Chapter 12 (link to Chapter 12)

and when someone is viewing the last chapter (say chapter 25):

Chapter 21 (link to Chapter 21)
Chapter 22 (link to Chapter 22)
Chapter 23 (link to Chapter 23)
Chapter 24 (link to Chapter 24)
Chapter 25 (no link)

My immediate thought was to create a view, but after I have created the view with the proper contextual filter and relationship, there was no option to sort the results based on the weight of the Chapter in the Book's entity reference listing.

I then tried to use Views PHP and sort the results via PHP with code like that:

$node = node_load($row1->nid);
$weights = $node->field_book_contained_chapter['und'];
array_walk($weights, function (&$v, $k) { $v = array_shift($v); });
return array_search($row1->nid_1, $weights) - array_search($row2->nid_1, $weights);

which works fine only if you select to display all items (doesn't work with pagers) but is also very inefficient: it runs through the whole array of referenced entities for every comparison between two rows (and some of my books have more than 1300 chapters). I haven't tested how it performs but my gut tells me that it's not a very elegant solution (I will also have to do additional filtering after I sort them).

Now I'm thinking about creating a custom block with php code that will traverse the $node->filed_book_contained_chapter['und'] array and find the neighboring articles of the current article. This seems like a more efficient solution than the views' one, but still feels kind of an awkward approach.

Is there an obvious way that I'm missing to achieve the functionality that I'm after?

A solution that comes to mind could include creating a block in a custom module and manually generate your pager-like unordered list. I wrote some quick code to show you how it can be done. I also added some comments in there to help you understand what I'm doing.

Notice, that this code is assembled in a hurry so you may find additional optimizations that you can perform in there.

/**
 * Implements hook_block_info().
 *
 * Declares your custom pager block.
 *
 */
function YOUR_MODULE_block_info() {
  $blocks = array();
  $blocks['parent_book'] = array(
    'info' => t('Parent Law'),
  );

  return $blocks;
}

/**
 * Implements hook_block_view().
 *
 * Renders the block. Calls the main rendering function.
 *
 */
function YOUR_MODULE_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'parent_book':
      $block['subject'] = '';
      $block['content'] = _YOUR_MODULE_parent_book_content_generator();
      break;
  }

  return $block;
}

/**
 * Helper function: renders the block's content.
 */
function _YOUR_MODULE_parent_book_content_generator() {
  // We'll need this to create the links to the articles.
  global $base_url;
  // Initialize the $output variable
  $output = '';
  // Checks if this is a node page.
  // No content type checking, you'll either have to add extra code
  // to narrow it down or use something like panels.
  if (arg(0) == 'node') {
    $book_chapter_nid = arg(1);
    if ($book_chapter_nid) {
      // Load the current chapter node object
      $book_chapter = node_load($book_chapter_nid);
      // Get the container book's nid and load its object.
      // If you have a multilingual site you'll have to pass the node's language in there
      $book_nid = $book_chapter->field_container_book[LANGUAGE_NONE][0]['target_id'];
      $book = node_load($book_nid);
      // Create a references array and walk through it to remove the intermediate arrays
      $references = $book->field_book_contained_chapter[LANGUAGE_NONE];
      array_walk($references, function(&$value, $key) {
        $value = array_shift($value);
      });
      // Setup the items that you want to display here
      $items_to_display = 5;
      // Find the current chapter's position in the array
      $current_chapter_position = array_search($book_chapter_nid, $references);
      // Crude method to get a maximum number of loops that will be needed
      $no_of_loops = (2*($items_to_display - 1)) + 1;
      // Initialize our final array
      $chapters_to_show = array();
      // Push the current chapter in the array
      array_push($chapters_to_show, $book_chapter_nid);
      // Index to stop adding items when we've reached our goal of items to display
      // Initialized to 1 since we've already added the current chapter
      $items_added = 1;
      // Loop a specific amount of times
      // Notice that we'll always break out of the loop before it ends
      // i.e. when the number of items added becomes equal to the number of items that we wanted to display
      for ($index = 1; $index <= $no_of_loops; $index++) {
        // The condition to add an item before our current chapter is the not-negative index
        if (($current_chapter_position - $index) >= 0) {
          // Previous chapters are added at the top of the array
          array_unshift($chapters_to_show, $references[$current_chapter_position - $index]);
          // Update index
          $items_added++;
        }
        // Check if we need to exit the loop right now.
        // This is needed for even amount of items to display
        if ($items_added >= $items_to_display) {
          break;
        }
        // The condition to add an item after our current chapter is if the array key exists in the $references array
        if (array_key_exists(($current_chapter_position + $index), $references)) {
          // Next chapters are added at the bottom of the array
          array_push($chapters_to_show, $references[$current_chapter_position + $index]);
          // Update index
          $items_added++;
        }
        // Check if need to exit the loop again.
        if ($items_added >= $items_to_display) {
          break;
        }
      }
      // Time to print our unordered list
      $output .= '
';
      // Loop through the array that we created and store the nid in $current_chapter variable
      foreach ($chapters_to_show as $current_chapter) {
        // Load the node since we need it to display the title
        // This: check_plain(db_result(db_query('SELECT title FROM {node} WHERE nid = %d',$nid)));
        // is also possible and more efficient than loading the entire node but revisions need to be taken
        // into account if it is used.
        $node = node_load($current_chapter);
        // Wrapper for the current list item
        $output .= '
';
        // If we are printing the current chapter, we don't want to print the link markup
        if ($current_chapter <> $book_chapter_nid) {
          $output .= '';
        }
        // The title needs to be printed in any case though
        $output .= $node->title;
        // Close the link markup if applicable
        if ($current_chapter <> $book_chapter_nid) {
          $output .= '';
        }
        // Close the list item markup
        $output .= '
';
      }
      // Close the unordered list markup
      $output .= '
';
    }
  }
  // Return our final input which will be stored in $block['content']
  return $output;
}


Drupal 7.x + Ubercart 3.x + Domain Access I have a full working Drupal 7 with Ubercart 3 running fine. It is well configured with thousands of products in it. I would like to create a sub-domain where all the contents and users are the same, but some things (theme, views, ubertcart) are configured differently.
Domain Access module seemed to be the best way to acomplish my goal (it can handle differnt views, settings, themes, etc), but there is no such an option for Ubercart.

So, my problem is that I can not set different configuration on my subdomain for my Ubercart.

My questions are:
 - Is there any way to force Ubercart to use maybe an other db prefix, where Im storing the different settings.
 - Is there any other solution (other module) to my multisite problem?

Any help, tip or suggestion is much appreciated!

There is no working UC_domain module for Ubercart 3 - Drupal 7, and many issues of configuration - including payment methods per domain user are not availble


Populate questions and answers (Display two types of content two different ways on one page intermittently) I am using the Answers module and would like the landing page to display all questions as well as all answers, as they are posted, and each would render different fields e.g. I want the questions and answers to look differently but still show up in the same feed. Currently, it uses a view to list all the questions only. Is this possible?

For an example of what I mean, this is a screenshot Quora.

I read this answer but do not want to use panels, but am also not sure if this solution will render questions and answers differently from each other in the
 list.

Please notice that the answer shown in this example isn't related to the question; it's just a random answer to a question. That's what I'm looking for.

You also get a "Answers to a Question" view with this module. Change display format to "Fields" and create a block pulling all the fields you need. You might as well find Relevant Answer (extends Answers) helpful found here.

  The module provides two predefined blocks to display questions and their corresponding answers: 'Popular Questions' and 'Recent Questions'.

Edit: Import this view- you should get a "Q & A feed" block which populates questions and its answers, apply a sort criteria to meet your need.

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

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Q & A Feed';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '5';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: Content: Answer to the question */
$handler->display->display_options['fields']['field_answer_question']['id'] = 'field_answer_question';
$handler->display->display_options['fields']['field_answer_question']['table'] = 'field_data_field_answer_question';
$handler->display->display_options['fields']['field_answer_question']['field'] = 'field_answer_question';
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'answer' => 'answer',
  'question' => 'question',
);

/* Display: Q & A feed */
$handler = $view->new_display('block', 'Q & A feed', 'block');


Bulk updating image alt and title tags I'm trying to bulk update image alt and title tags for about 1,500 images on a site.

I've tried a number of methods and I will outline them all. I've also tried with the media module enabled and disabled. I think my issue is something to do with not being able to save the changes through to the image itself.

The relevant part of my image array (the image field - called "field_meeme_image" can hold mulitple values) is as follows:

 [field_meeme_image] => Array (
        [und] => Array (
              [0] => Array ( [fid] => 131 [alt] => Test [title] => [width] => 500

Currently I am trying Devel Execute PHP to just change one node as follows:

$node = node_load(63);
$node->log = 'Test2';
$node->field_meeme_image[$node->language][0]['title'] = $node->title;
node_save($node);

Using ['und'][0]['title'] doesn't work either

I also tried using both methods from this post

And neither one worked for me. I have confirmed that VBO is working. For example if I simply set:

$entity->log = $entity->title;
node_save($entity);

The log gets changed fine but if I try:

$entity->field_meeme_image[$entity->language][0]['title'] = $entity->title;
$entity->field_meeme_image['und'][0]['title'] = $entity->title;
node_save($entity);

The change doesn't get saved.

I've even tried using a preprocess function in my template (I've tried everything I can think of)

function footheme_preprocess_node(&$vars) {
    $node = $vars['node'];
    $user = $vars['user'];
    if ($node->type == 'meeme') {
    if (in_array('administrator', array_values($user->roles))) {
        $node->field_meeme_image[$node->language][0]['alt'] = $node->title;
        node_save($node);
        }
    }

This makes the change in the $node array but it doesn't actually show up as the alt tag for the image and it doesn't save.

Any help would be massively appreciated. Cheers.

Hope my below answer helps you.

if you are using Image field, then Image field provides an option to insert "Alt" and "Title" tags. When enabled, you can insert the values in the fields.
When you are saving if yourself, custom save, then the image field array needs to look something like below.

[field_image] => Array
    (
        [und] => Array
            (
                [0] => Array
                    (
                        [alt] => alt text
                        [title] => title text
                        [fid] => 12
                        [display] => 1
                        [width] => 220
                        [height] => 169
                        [description] =>
                        [upload_button] => Upload
                        [remove_button] => Remove
                        [upload] =>
                    )

            )

    )

However, the above is from the node presave, but when tested for empty values, and changing values in node presave, this worked flawless.
Try that out, curious to know why It wont work, Should be simple (If I understand this correctly :) )

Now, you also need to see at what point you want to implement it.
Node presave, node view or any other point in time.


Search API Solr: How to index fulltext fields with and without stemming? In short: Is there any way to index the stemmed and non-stemmed version of Fulltext fields in Drupal Search API Solr without resorting to hardcoding field data into copyfield in the schema file?

(and if not, what's the safest, most Drupal / Search API friendly approach to doing this? e.g. using Drupal field machine names in the Solr schema file, maybe?)

Background: A common practice when working with Apache Solr is to use a stemmer like SnowballPorterFilterFactory (stemmers make searches match by the grammatical 'stem' of a word, so for example, searches on "walking" match content with "walked"), then, to copy fulltext fields (e.g. using copyfield), stemming one of the two duplicates and not stemming the other.

This popular approach has two advantages (at the cost of more processing):

Exact matches are indexed more highly than close matches - a search on "walking" matches content with "walking" twice (stemmed and unstemmed) and content with "walked" once (stemmed only)
You're guaranteed to not have any awkward cases where a search on a stemmable term fails to match content that contains that original exact term*.

As I understand it, when Solr is used outside of Drupal, this is usually done by hardcoding <copyfield> declarations into the Solr schema file for each field that is to be stemmed.

(for the sake of this question, imagine a Search API Solr search indexing nodes, processing as fulltext the fields Title, Body, Teaser, and one custom field named Notes)

The problem: With Drupal and the Search API module's Search API Solr, the fields are configured by Drupal dynamically - rather than being hardcoded in the Solr schema.txt file. It's not clear how to make the two approaches play nicely together.

Is there a better, more Drupal-friendly way to index stemmed and unstemmed content than hard-coding the field names into something based on copyfield in the schema.txt file?

If hard-coding is the answer, what names should be used, what care needs to be taken to avoid namespace problems?

Another popular approach with Solr outside of Drupal is to create a composite field of all your fulltext fields, combined, and treat it as a string rather than fulltext - so it bypasses filters and simply mops up and boosts any words that are searched for exactly as they appear in the text. Search API has two features under Workflow that look promising for this, Aggregated fields and  Complete entity view - but (as far as I can tell) both can only index as Fulltext and would therefore be stemmed just like the regular field.

I can't see anything on this specific to Search API Solr. The closest I can see is this issue for D8 core search, but that's rather different. I can't find any information about anything like this for Search API.

**(for example, I find that with stemming, searches on 'unravelling' don't match content containing 'unravelling', but searches on 'unravel' do. It's being stemmed down to 'unravel', but for some reason it's not recognising 'unravelling' as a valid extension of the stem 'unravel'. 'Unpublished' is another example (unpublish matches, unpublished doesn't). I've seen various reports of similar language-specific stemming issues. Keeping an unstemmed copy seems to be the standard approach, but I  can't see any clean way to do this in Drupal)*

Also posted as a support issue on the Search API Solr queue (yes, cross posting like this is okay, actually encouraged to make life easier for maintainers)

Good question, and also a topic that should probably be brought up as a feature request for both Apache Solr Integration and Search API Solr at some point. Searching both stemmed and unstemmed content can often lead to significantly better results.

For Search API Solr, there's no way to do this without modifying the schema.xml bundled with the module. But you're probably already aware of that since you're using stemming and the bundled schema does not have stemming enabled by default.

The key to doing this without lots copyField definitions is to use a combination of dynamicField and copyField. You'll also need two different fieldType definitions, one for unstemmed and one for stemmed text.

Try these steps:

Duplicate the entire definition for <fieldType name="text"> as
<fieldType name="stemmed_text"> and uncomment the
SnowballPorterFilterFactory filter.
Add a dynamicField definition using this new fieldType. The data
does not need to be stored, only indexed.
Example: <dynamicField name="stemmed_*" type="stemmed_text" termVectors="true" stored="false" />
Add a wildcard copyField definition that copies all text fields into
corresponding stemmed text fields.
Example: <copyField source="t_*" dest="stemmed_*" />
Reindex.
Add "qf" params to the Solr query for all stemmed fields you want to
search. You can do this via hook_search_api_solr_query_alter(). If
you want all text fields, you can look for field names prefixed with
"t_".

Bonus: Sometimes it helps to boost matches against the unstemmed field in order to make more exact results appear first. You can add boost factors to the field names in the qf param.

Bonus #2: The pf param ("phrase field") is another good way to boost exact matches. This lets you give priority to results where terms are in the same order as what the user entered.

Apache Solr Integration module:

For those using apachesolr.module, matching against both stemmed/unstemmed can be done without changing schema.xml. The bundled schema includes lots of dynamicFields and is quite flexible. By default, searchable fields are stemmed. You can simply copy content fields to unstemmed dynamicFields in hook_apachesolr_index_documents_alter() and then add "qf" params for those fields via hook_apachesolr_query_alter().


Conditional Fields Changed Answer Problem I have three fields on an entityform the third is hidden unless the second one is answered with yes.

The problem I have is that if a user makes three visible by answering "yes" and then answers three but then decided to change question 2 to  "no" field 3 is hidden but the answer is still recorded.

Adding another dependency with field 3 - emptied when question 2 is no should most likely fix your problem


Giving users control of who sees their information? On our rebuilt site we have an "about me" field attached to the user account.
We want to give people the ability to specify who can see this information (or their whole user profile):

Anyone (anonymous users)
Authenticated users only
paid Members of the organisation only (a role).

What's the best way of doing this?

Assuming that by "best" you mean that you want to avoid custom code if possible (e.g. because you don't have the skills and/or budget for that), then this is a way to make it work with zero custom code:

Implement your "About me" field as an entity reference, which references a node of some other content type (say "Details About Me"). So if somebody wants to complete such field, they should first have created an appropriate node of content type "Details About Me" (so that they can use that node in their entity reference field.
Add a special (required) field, which you define as a single value selection field, to let the user "specify who can see this information" (as in your question). Say you call such field "Visibility".
Whenever somebody wants to browse such "Details About Me" page, let the Rules module decide if such browse is yes or no allowed (based on the content type, and the value of that Visibility field. Refer to the answer to "How to make the permissions of a module more granular?" for a sample rule you could start from, and make it fit your case like so:

Adapt the Rules Conditions.
Tune the redirect URL and message in the Rules Actions.

The above should take care of the "specify who can see this information"-part of your question. The remaining part of your question (= "or their whole user profile") is really a different question, not answered here. Though you could use a similar approach for that also.


Prefix of drupal: in front of certain dependencies and what does it mean? I saw certain modules list their dependencies with a prefix of drupal:, while other don't.

What's the difference between:

name: Core
type: module
core: 8.x
dependencies:
  - block

And

name: Core
type: module
core: 8.x
dependencies:
  - drupal:block

Notice the extra prefix drupal: in front of block.

The 2nd is the correct way as per: https://www.drupal.org/docs/8/creating-custom-modules/let-drupal-8-know-about-your-module-with-an-infoyml-file but I think drupal is assumed for the project if its not specified (The first part before the : )

So for Drupal core modules they'd prefix with drupal: and for custom modules its usually the module name e.g. webform:webform as they are projects of themselves


Location to Call the function theme_uc_price($variables) This function is located at /public_html/location/sites/all/modules/ubercart/uc_store

function theme_uc_price($variables) {
  $output = '' . uc_currency_format($variables['price']) . '';
  if (!empty($variables['suffixes'])) {
    $output .= '' . implode(' ', $variables['suffixes']) . '';
  }
  return $output;
}

So my problem is, where can I find the ubercart file that calls this function? So I could get the computation where they add up the products so I could tweak it.

Any help would be appreciated. :)

Since it's a theme function, based on DrupalContrib theme_uc_price it's called about 12 times within the Ubercart Suite.

As an example from one of the functions that calls the theme function which is uc_object_attributes_form.

theme('uc_price', array('price' => $option->price))

That's how Drupal uses theme functions.


Contact form in node I have a product catalogue website with no commerce feature and i want to embed a contact form in every product(node). User will be able to fill that form and the owner of the website will receive an email which will also includes the title and the link of the specific node. Is there any module available that can do this?

Thank you

Node feedback module offers a check box on the node form asking the author to allow the visitors of the node to send feedback/request for the node using the personal/site wide contact form. It is also possible to view URL from which node, for that you have set token. See the below image, possible to set available fields token.

For Drupal 6:

Author Contact shows a contact form that contacts the author of the current node.
You can set the tokens for title to show in email as well as in fields. I am using this in my website see the Interested in this Property


How to put User Profile in a Block? I know this is simple but can't find the answer. I'm just wanting to put the contents of  user-profile.tpl.php in a block. No extra formatting or anything. Just pull the information and put it in a block. It can either be in my custom module or by creating a block. Thanks for your help!

After trying the initial suggestion, I received this error message:

Fatal error: Unsupported operand types user.module

My user-profile.tpl.php doesn't contain the usual information and I should have mentioned that originally. There's a lot to it but I think the problem is here:

$account = menu_get_object('user');

Since it calls that immediately at the top, it may create a problem. Beyond that, the rest of the user-profile.tpl.php file uses the account variable highlighted above to get a bunch more information.

I'm using the latest version of Drupal which is 7.7 at this time.

For Drupal 6 you create a custom block and let the content be:

theme('user_profile', $account);

For Drupal 7 you do change the code a bit:

render(user_view($account));

In both cases $account if the fully loaded user object who's profile you want to display in the block.


JPEG Quality configuration I'm wandering how and when the JPEG quality ratio (75% by default in admin/config/media/image-toolkit) is applied to the images.
1/ I suppose it is used a first time when the image is upload and scaled to feat the max width/height set up in the content type field. So, in case the original uploaded image already feats the max width/height, is it processed and compressed anyway or not?
2/ Then, I suppose this ratio is applied a second time when generating image styles at page load.
So this means that the resulting displayed image has been compressed two times with 75% quality loss (resulting ±56%). Is that it?
Thanks for your help.

I tested it on a local server. Now I can say that:
1/ Image is processed at upload ONLY if it is larger than maximum authorized width/height (if it fits in this max size, it is not processed).
In this process, the JPEG quality ratio set up in configuration (admin/config/media/image-toolkit) will be applied.
This first step generates the "drupal original image" with will be used to generate image styles.
2/ In this new process of generating the image styles, the JPEG quality ratio will be applied AGAIN when resizing the thumbnails.

This means that it seems better to keep the JPEG quality ration roughly around 60-80% to have lights pages, but in order to avoid it to be applied twice on the images styles thumbnails displayed in the pages, upload "original" images that are 100% quality JPEG and fit to the max allowed size (so that are not processed at upload).


How to add a category in the FAQ_ask module I am using the FAQ Ask the Expert Module on my drupal 6.  I am not very familiar with the drupal interface and have trouble setting up modules. I would like my ask a question for to have categories in which the asker can check off. The question would then be sent to the expert corresponding with that category.
 It seems like this is what this module would do except I cannot get the categories to show up. Can someone give me step by step instructions?

EDIT: I would like the categories to show up on this form:

In order to use categories with the FAQ module you need to have the taxonomy module enabled.

Once you have the taxonomy module enabled you will need to create at least one vocabulary and associate it with the "FAQ" content type.

Once you've completed the above step you can visit the FAQ categories configuration page (admin/settings/faq/categories) and set up how you would like the categories to be display and there expected behavior on the faq page.

Hope this helps.


How can I add sort criteria for search api views? I set up a view with search api data according to this, but the sort criteria available in each view are not complete. I'd like to sort on some fields (indexed) that are not showing in the list. I'm wondering if I need to use a hook to alter the query, or if there's a configuration option somewhere that I've not read about.

I just discovered that if I re-index the fields (in this case, first name and last name) as strings, rather than the default fulltext, they are made available to sort on in views. This is great news.


Cannot get theme_links__system_main_menu($variables) to fire now matter what i've added the code below to my theme's template.php file. i've cleared the cache too. but this just isn't firing no matter what. i'm not getting any errors either.

anyone have any experience with this function? i am using a sub-theme of the Adaptive theme. don't know if that has anything to do with it.

function spn_at_links__system_main_menu($variables) {
 echo '';
 $html = "
";
 $html .= "
";
 foreach ($variables['links'] as $link) {
   $html .= "
".l($link['title'], $link['path'], $link)."
";
 }
 $html .= "
";
 $html .= "
";

 return $html;
}

yes my theme name is spn_at with an underscore. i have other theme related function working just fine in the template.php file. big thanks for any help w/ this

The Adaptive theme never calls links__system_main_menu from its page.tpl.php file, hence providing an override has no effect and it falls back to theme_links. If you want to override it you will have to provide your own theme suggestion in preprocess hook function.

Look here for more info: THE DEFINITIVE GUIDE TO DRUPAL 7


What to do when a module is uninstalled but leaves some features enabled? I just disabled and uninstalled a module. Problem is that I still see some features that were created by this module at: "admin/structure/features"

How can I delete these features? I don't see any "features" table in the database.

UPDATE
I think I wasn't clear enough, sorry. It is not a feature module, it is standar module called "md_portfolio". This module creates the features you can see in the capture.

There are not any modules with the names you see in the capture in sites/all/modules

Update2 the features are shown as "enabled" in the capture but NOW they are disabled (I took this capture when I had them enabled)

If the feature is creating some items that you no longer wish to have on your site (content type, maybe) you can always uninstall that feature. Remember features are basically modules, so you uninstall them the same way (go to mysite/admin/modules/uninstall). That may start to remove some of the items the feature was responsible for (depending on the feature's uninstall script)

Also, as features are basically mini modules, they won't fully go away (or stop showing up on your features page) without removing them first. They should be located in your site/all/modules folder. Remove the feature from the file system.


Drupal 7 Faceted Search: Always show Facets I have a faceted search working that uses searchapi, facetapi, and entityapi. I was not the one who developed this, but I have some experience with Drupal.  As of now the navigation uses links for selection and looks like below (first level of bullet points aren't links).  When mixing is selected sound design and composition disappear as expected.

What the client wants is for all items to still stay visible and selectable as the user drills down (even if it returns nothing). Only one item per category will be selectable at a time, but the user should be able to do it without having to 'go back'.
Any advice is greatly appreciated.

What We Do_

Mixing (18)
Sound Design(11)
Composition (6)

Who We Are_

Joe Schmoe (17)
Jeff Bleck (14)
David Berry (4)

Affiliated Composers_

Jim Carey (3)
Tony Maroni (2)

Under admin/config/search/search_api click “edit” on your search index and select “Facets”. Then for all facets that need the described behavior for their items, follow these steps:

Click “configure display”.
In the “Global settings” section, change the “Minimum facet count” to 0 (zero). Arguably this input field should rather be called “Minimum facet item count” …
“Save configuration”.

Now all non-matching facet items should remain in your facet list (with a zero count). As you have already mentioned, clicking such a facet item will return no search results anymore.


Missing icons with CKEditor for Drupal 7 I've recently installed CKEditor 4 for Drupal 7 module and some of the toolbar's icons don't seem to show up.

They are:
Add Media
Media
Teaser Break
and
YouTube (to name a few).

I've cleared the Drupal and Browser cache, but that hasn't helped. I've also ensured that I've got the right skins (reuploaded just in case). I tried multiple skins and these same buttons don't seem to want to appear.

Does anyone have any ideas for how to resolve this issue? Test thread is here.
http://iloveqatar.net/forum/content/test-0#comment-36224

(Note, I installed CKEditor because I needed an easy solution for users to upload multiple images when created a post so I'm not really attached to CKEditor if someone has a better idea. I was using TinyMCE with the WYSIWYG module)

Try re-upping the CKeditor library (not the module) and double-check that the owner/file permissions are set correctly on the server.

I believe TinyMCE also works with CKeditor. If you only need to attach images to content and don't need a WYSIWIG editor for your input area, you can add an Image or File field to the content type. If you're using a File field, you might also want to look up the File Entity and Media modules.


How to resave all my nodes In D7, it was easy with the VBO module..
But how to do it with D8? (Preferably using a view to select the nodes to resave)

In many places I saw that a small part of the VBO module is now included in the D8 core but I can't figure out how to use it (assuming a simple save should be feasible)

What you are asking for is included in core Views, unless I am mistaken.
In a new Content view you will be able to add a "Content: Node operations bulk form" field and that offers you an option for "Save content".

You could even use the default "Content" view...

that already offers that option out of the box:


How set background image for doc files when exporting nodes to Word in Drupal 7? I used the Node to Word module in Drupal 7 to export nodes to Word. It doesn't have an official release for D7 yet, but there seems to be some D7 version of it in GIT. I downloaded this file) for it. This module supports writing template for a very convenient view mode.

How can I set the background image for the doc file when exporting a node to a doc?

I tried to use the background for the <div> sheathed same template but the export of the word, it has no effect.

Node template:

And result:

The functionality you are looking for does not (as right now) exist in the version of the module you have linked to.

Therefore you will not be able to set the background image of the Word document without making modifications to the module.

This would be non-trivial as your modified module would have to do the following:

parse the CSS of the page to determine what image should be displayed
load the image and embed it in a format that Microsoft Word can understand
set the necessary tags in the Word document to use the embed image


How to redirect to the webform node when it just created? I followed the webform cookbook and created a custom module to "automatically create a Webform node when adding a Webform". Moreover, I need to redirect to the Webform Node at the same time, so I add the "RedirectResponse" code, but it didn't work. Following is my code:

function webform_chshb_webform_insert(\Drupal\webform\WebformInterface $webform) {
    $webformnode = \Drupal\node\entity\Node::create([
        'type' => 'webform',
        'title' => $webform->label(),
        'webform' => ['target_id' => $webform->id()],
    ]);
    $webformnode->save();
    drupal_set_message(t('Node %label created.', ['%label' => $webformnode->label()]));

    $nodeid = $webformnode->id();
    $response = new RedirectResponse("/node/$nodeid/edit");
    $response->send();
}

Thank you.

try it with return

function webform_chshb_webform_insert(\Drupal\webform\WebformInterface $webform) {
    $webformnode = \Drupal\node\entity\Node::create([
        'type' => 'webform',
        'title' => $webform->label(),
        'webform' => ['target_id' => $webform->id()],
    ]);
    $webformnode->save();
    drupal_set_message(t('Node %label created.', ['%label' => $webformnode->label()]));

    $nodeid = $webformnode->id();
    $response = new RedirectResponse("/node/$nodeid/edit");
    $response->send();
    return;
}


How to do a "Corner Stamp" with Masonry Views? I am building a jQuery Masonry based website, and have content listed as responsive Masonry bricks thorugh Masonry Views.

I need to be able to insert a so called "Corner Stamp" (a static right corner element) in the views results, so that the results wraps around the corner stamp, as described here: http://masonry.desandro.com/demos/corner-stamp.html

In my case the corner stamp will be a unique View or Block with navigational features.

My question is:
How can I insert the corner stamp into a result set listed with Masonry Views?

Is this possible through Masonry Views (possibly with a template), or should I use jQuery Masonry without the module somehow?

Thank you in advance!

Here's a thread in which considerable progress has been made: http://drupal.org/node/1988588#comment-7411276


Using Feeds to import data In order to import data from a CSV file, I would like to use Feeds. I followed an example from the Drupal Cookbook, and it uses the Basic Page content type.

Because the data I would like to import has unique data, could you please confirm if I will need to create a new content type with its own fields so I can map map the source to target? I would just like to make sure what I am attempting to do is correct to avoid corrupting the database...

If there are different data that you would like to store from your csv, you should create your own content type, add required fields there.

Then in create your feeds importer, set the required settings(like selecting your content type), set mappings and let feeds do its magic(yep, its an awesome module!)

Fees is a great module where you have to import data into nodes, users or taxonomy.


How to not have an image in a facebook share I have a problem

Although many have the problem with not have the right image, I'm trying to have no image at all. I have ads on the page that get chosen because the content type has no image.

I have tried to do put in a "[none]", (then a random field from another content type), in the image field under open graph in meta tags, it's still not working.

I simply want to share the text itself without the image of the ads, and if you have a better solution, please mention.

Thanks!

First of all try investigating URL you are sharing on Facebook Debugger:
https://developers.facebook.com/tools/debug/

If you are not providing og:image meta tag, Facebook will try to get the best matching one, I guess those AD images in your case.

Unfortunately there is no way you could not provide an image, you could try with empty og:image meta tag, but I don't think this would work.

It would be best if you provide an image anyway. Here are some hints:
https://developers.facebook.com/docs/sharing/webmasters#images


How to display the title at the end of the breadcrumb? I would like the page title to be displayed as a part of the breadcrumb, at the end of the preceding path.

I've got the following code.

<?php print $breadcrumb; ?><?php print $title; ?>

I have checked the following option in appearance/settings: Append a separator to the end of the breadcrumb.

If the page is a top level page, the breadcrumb displays correctly; however, for any further level pages, the title doesn't display, but just the previous path.

How do I change this to get it to work?

This is what I would like to do: Adding the page title next to the breadcrumb.

I've now got the following code.

<?php print $breadcrumb . $title; ?>

The page title only displays for top level pages. If a page has parents, then the title doesn't get displayed. I've cleared the cache, but still no luck.

In template.php of your theme folder you can do this:

This is for changing the seperator or overriding the already available breadcrumb:

function mytheme_breadcrumb($variables) {
  $sep = ' &gt; ';
  if (count($variables['breadcrumb']) > 0) {
    return implode($sep, $variables['breadcrumb']) . $sep;
  }
  else {
    return t("Home");
  }
}

For adding title of page next to the breadcrumb you simply do this.

In page.tpl.php of your theme folder:

<?php print $breadcrumb . $title; ?>

[Alternative Answer]:

If you dont want to do with custom code then you can try this module(Menu Breadcrumb) which will have option for adding page title at the end of breadcrumb.

In the configuration of this module you need to check this option for getting page title use menu the page belongs to the breadcrumb

Module Name is Menu Breadcrumb


Clicking reset in Views UI causes PDOException Error I have a searchable view created that returns the following error when I click to  "reset" the search query. It only occurs when resetting a search from the search terms field.

  An AJAX HTTP error occurred. HTTP Result Code: 500.

The logs show the following:

  PDOException: You cannot serialize or unserialize PDO instances in
  DrupalDatabaseCache->set() (line 455 of /code/includes/cache.inc).

This error occurs in the preview, not on the live page.

Something is trying to serialise a PDO object, which you can't do in PHP (unless you're running < 5.3 and are happy with nasty workarounds).

Drupal core doesn't do this; The Views module itself doesn't do this; so you'll need to disable custom/contributed modules you have installed one by one until you find the culprit. If/when you do, either fix the module if custom, or report the bug to the module's issue queue on Drupal.org for review.

If you're making use of the PHP filter in that View, remove the PHP code temporarily to see if that's the problem. If it is, consider re-implementing that logic in a more stable manner, i.e. using the hooks from the Views module.


How do I make a checkbox form initially have all options checked? I have a drupal form in a module that doesn't pull in information until submitted.  Can I make the checkboxes initially checked?
  $form['search_block_type'] = array(
    '#description' => "Select content types",
    '#type' => 'checkboxes',
    '#options' => $options,
    '#title' => t('Content types'),
    '#default_value' => $default_types,
  );

I assumed it was #checked' => 'yes' but that doesn't seem to work.(from a view)

The actual form element values when selected are always the keys of what you have inside $options. You also can see that when inspecting the markup. So simply use '#default_value' => array_keys($options) to have all options preselected.
$form['search_block_type'] = [
  '#type' => 'checkboxes',
  '#title' => t('Content types'),
  '#description' => t('Select content types'),
  '#options' => $options,
  '#default_value' => array_keys($options),
];


Why I can't access to dblog? Why I can't access "Recent log messages" (via /admin/reports/dblog)?

It's not listed in the Admin Menu. And when I try to get there directly (via /admin/reports/dblog), I only see the "Reports", as shown via /admin/reports.

I've installed Drupal 7.15 with the OpenPublish Profile.

What could be the solution to this problem?

As suggested, Check whether "Database logging" module is enabled in your modules list.


How to have parent taxonomy terms include their children terms' nodes? I have a hierarchical taxonomy, and I'm currently using the Taxonomy Menu module to display navigation links. E.g.

+ Dairy
  * Milk
  * Cream
+ Fruit n Veges
  + Citrus
    * Lemon
    * Lime
  * Pumpkin
  * Tomato

Each of the links refers to a taxonomy page, which is nice, but the page for "Dairy" only includes nodes that have the term "Dairy". It doesn't include "Milk" and "Cream" nodes, for example, which is what I want.

What's the best way to implement this? And "what's the point" of sub-terms, if they don't seem to have any semantic meaning?

Install the module http://drupal.org/project/hierarchical_select and check its configuration and you will find an option to "Save term lineage" select it and all the level of terms will be saved with the node.


Drush modifying variable on settings.php Can I modify a variable of the setting php via drush?
I actually want to change

ini_set('session.cookie_lifetime', 2000000);

to

ini_set('session.cookie_lifetime', 0);

Drush cannot edit the settings.php file.  You could do the above with sed.  Let me know if you want the regex to do it.


Disable user_node_load Is there a way to disable user_node_load on non-admin pages without hacking core modules? My theme doesn't use user data so this function results in needless database queries.

Disclamer

I am using a hook in a way that is different from the usage that is documented on Drupal.org API. See the notes at the end of the question.

You could achieve what you want by implementing two hooks:

hook_module_implements_alter()

function mymodule_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'node_load') {
    unset($implementations['user']);

    // Put mymodule_node_load() to the beginning of the list.
    $group = $implementations['mymodule'];
    unset($implementations['mymodule']);
    $implementations = array('mymodule' => $group) + $implementations;
  }
}

hook_node_load()

function mymodule_node_load($nodes, $types) {
  if (path_is_admin($_GET['q'])) {
    $uids = array();
    foreach ($nodes as $nid => $node) {
      $uids[$nid] = $node->uid;
    }

    $user_fields = db_query("SELECT uid, name, picture, data FROM {users} WHERE uid IN (:uids)", array(':uids' => $uids))->fetchAllAssoc('uid');

    // Add these values back into the node objects.
    foreach ($uids as $nid => $uid) {
      $nodes[$nid]->name = $user_fields[$uid]->name;
      $nodes[$nid]->picture = $user_fields[$uid]->picture;
      $nodes[$nid]->data = $user_fields[$uid]->data;
    }
  }
}

The code I used for hook_module_implements_alter() is different from the example code shown in the documentation, which just alters the order in which different implementations of the same hook are invoked.

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

In general, it is not a good idea to avoid a hook implemented from another module is invoked. Modules that change their behavior because a hook implemented from another module is invoked normally use module_exists(), rather than module_implements(), which means those modules normally make the assumption that the module being enabled is sufficient for that specific hook to be invoked.
Generally speaking, there could be modules that depend from the data injected from the hook you are trying to block. It is not said that avoiding user_node_load() executes its SQL queries would avoid another module executes its own SQL queries with a decrement of performance even worse.

If you are sure that none of conditions I described are verified, you could implement the code I shown, at your own risk. Be prepared to verify there aren't any unwanted consequences, and check what the code used by the modules you use in the site is doing.


Publishing events on a calendar to an individual/a specific group/ or all Hey I'm new to drupal and trying to create a calendar that users can publish different items to.

there are different roles involved say:
worker,
supervisor,
manager.

workers are divided into groups.

Are there modules that would allow a supervisor or manager to post an event that
1) only a single worker could see,
2) that only a group of workers could see,
3) that everyone  could see.

Would user-relationships handle this?

Events are nothing but nodes so you finding for a solution to have node access for a user, user role, or to all will give you the answer

Might the following modules can do this for you

https://drupal.org/project/nodeaccess_userreference

https://drupal.org/project/content_access


highlight the menu items related to the particular content type How to highlight the menu items related to the particular content type? Actually I want whenever the user visits the page related to the particular content type,it should highlight the particular menu item. Context module is the one solution for this. Is any other custom coding solution without installing any module?

You can use theme_menu_link function.
Add this code to template.php of your theme

function themename_menu_link(array $variables) {
  $path_parts = array();
  $element  = $variables['element'];
  $sub_menu = '';
  $menuName = $variables['element']["#original_link"]["menu_name"];
  //Check menu name
  if($menuName == 'main-menu')
  {
    $path_parts = explode('/',$element['#href']);
    if($path_parts[0]=='node' && is_numeric($path_parts[1]))
    {
      $menu_load_node = node_load($path_parts[1]);
      //Check node type (In our case 'article')
      if($menu_load_node->type == 'article')
      {
        $element['#attributes']['class'][] = 'highlight';
      }
    }
  }
  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

All links to nodes with type 'article' will have class highlight


How do I use theme('pager')? I have problem to understand how I should use theme('pager') as explained on
EntityFieldQuery display pager.

I can't make it work (display pager and links to resulting pages).

Does pager(10) in EntityFieldQuery automatically invoke the pager? Should it be displayed with print(theme('pager'))?

Is this functionality included in Drupal core (7.15)?

I am doing my queries in template.php and injecting the query result in article.tpl.php through a variable.

As a workaround, I am thinking of doing two queries, one to find out what the number of nodes that meet a condition is, output links with numbering, attach the variable to those links, read the variable in another query and select the resulting nodes with range($i,$j).

Does pager(10) in EntityFieldQuery automatically invoke the pager?

Yes; it even avoids the usual problem of multiple pagers on a single page conflicting, by getting a new delta from the PagerDefault class.

  Should it be displayed with print(theme('pager'))?

Yes (but obviously only if there is more than one page worth of results to display).

  Is this functionality included in Drupal core (7.15)?

Yes.

This works perfectly for me:

$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'node')
  ->pager(10);

$results = $query->execute();
$nodes = node_load_multiple(array_keys($results['node']));

$build = array(
  'nodes' => node_view_multiple($nodes),
  'pager' => array(
    '#theme' => 'pager',
  )
);

That's returned from a menu callback function, so will be passed through drupal_render(). When it does so, a list of node teasers is displayed with the expected pager right below.

If the same example doesn't work for you then there must be something wrong with your installation, or something in a custom/contributed module conflicting with the core pager system.


Automatic tagging (based on other tags) I have the following taxonomies:

Countries
Cities

When I create a new node Im allowing to enter "Cities" as a field of that node. Given that I have a "mapping" in place, how can I automatically assign the "Country" to that node as well (the user doesn`t have to do it, it happens in the background)?

Example:
I "tag" a node with "New York" - and that node is atomatically tagged with "United States" behind the scenes. When listing "United States" in a view, the node tagged "New York" would appear amond all other nodes tagged with US cities.

Also, where would the mapping of "New York -> United States" be defined?

Thanks for your help!

Here is the module to do it:

Hierarchical Term Reference Autocomplete

I think it's preview image shows exactly what you want


How to define jQuery in libraries for avoiding conflict with theme with library? For use of most frameworks (Zurb Foundation, Bootstrap, etc) or libraries (Like Owl carousel, Slick, etc) within a theme, jQuery has to be added as a library.

Is it enough to add jQuery only once as dependencies in a global library and have it load on every page (imagine that I add this library in Library section of ThemeName.info.yml) Or would I have to add it as dependencies each time I define a new library again?

For example, is the below structure correct:

global:
  css:
      # The path to the css file.
      assets/css/stylesheets-1.css: {}
      assets/css/stylesheets-2.css: {}
  js:
    assets/js/myglobal.js: {}
  dependencies:
    - core/jquery

library-A: # Bootstrap Library.
  css:
      assets/css/stylesheets-3.css: {}
      assets/css/stylesheets-4.css: {}
  js:
    assets/js/myglobal.js: {}
  dependencies:
    - core/jquery

library-B: # Owl carousel Library.
  css:
      assets/css/stylesheets-5.css: {}
      assets/css/stylesheets-6.css {}
  dependencies:
    - core/jquery

Is there any problem If I add jQuery once as library in js: category and again as dependencies: in one library like library-C simultaneously? Something like below? Can it cause the conflict?

library-C:
  css:
      assets/css/stylesheets-c-1.css: {}
      assets/css/stylesheets-c-2.css: {}
  js:
    assets/js/myglobal.js: {}
    assets/js/jQuery.js: {}
  dependencies:
    - core/jquery

Every library needs to have all it's dependency listed !
As libraries can be loaded independently.

  drupal will make sure to include every file only once.

So this is correct. yes.


Using paragraphs tag instead of div in fields? I have a node type with a body, that I want to display in a custom node template.  When I use code like

print render($content['body']);

I get a mess of div tags like

Here is my body content

I appreciate Drupal's rich markup, but I just want

Here is my body content

According to http://api.drupal.org/api/drupal/modules!field!field.module/function/field_view_field/7 I should be using render(), but it render() doesn't seem to be giving me the control I want.  Is there a best-practice way to do this?

The extra junk is added by the field.tpl.php file from core.
But hey you can customize it.

Create a new file in your theme's templates folder. (For available variables, see here)

File name: field--body.tpl.php  (See http://drupal.org/node/1089656 for template file suggestions)
Contents:

Now, when you use render() in your node.tpl.php files, you will see the p tag wrapped content instead of the extra junk.

Update: I have forgotten that the $item comes from $items array. Updated the code above. If the body field has multiple instances, each one will be shown in individual p tags.


Search for drupal site using taxonomy We are due to move our website (a rather large charity site) and we would really like to make sure search is working as well as possible. We are currently working on tagging all our content using a controlled vocabulary taxonomy which we hope to be able to use in Drupal.

What I would like to know if there are any search modules for drupal, where search result would be displayed with visible taxonomy tags. So as for example if someone would search for "drugs" and "depression" a list of result would be displayed where you by the article also could see the taxonomy tags related to that article. So Search result one would have the tags "Drugs""Depression" and any other tags used so perhaps "stress", search result two "Drugs""Depression" and "Pain". I hope this makes sense? Does anybody know if this is possible and if so are there any website that uses something like this already?

I'm not very clear what you're asking, so I might be on the wrong track. However a basic search returns a set of nodes that match in a particular order; the normal culprits are Apache Solr and Elastic Search, but there are others. For a large site definitely don't use the builtin search, and do investigate using 'search api' if you're not already.

Once you have a set of nodes, it's up to you how to display them. Including the taxonomy terms associated with each node is part of the display logic, rather than the search itself, and should be relatively easy. Have a look at Display Suite for better control of search views if you need it, though it may well be more appropriate to write a custom node render hook.

If you are more interested in something like a tag cloud of terms that the currently matched nodes reference, that is more difficult but I would look at the tag cloud module, with some custom glue logic to link them.

Hope this helps...


How can I change the labels on a chart created with the Google Chart Tools module? I'm using both the Chart module and the Google Chart Tools module to create a chart from  the data that I'm collecting from registered users.

Here is a sample of my chart:

But how can I change the labels of the X-axis?

And I want the title to appear on the X-axis also, instead of the link. How can I do that?

That is very easy. Simply uncheck link field to original piece of content of the field you are using.


SSL errors - .well-known I am seeing lot of SSL errors after enabling SSL for my site.
Following is the common error related to the SSL configuration:

AH01797: client denied by server configuration: /var/www/xxxxxx/.well-known

Is this something related to any settings in our Drupal folder like creating ".well-known" folder or adjusting .htaccess settings or is it related to the Apache settings?

That folder is needed by LetsEncrypt and is nothing to do with Drupal. For some details elsewhere on the SO network see https://serverfault.com/questions/796745/letsencrypt-do-i-need-to-keep-well-known-accessible-for-certificate-renewal


How to remove Input format from comment form? I used following code to create a module to remove input format from comment forms, but it doesn't work. Is there anything I'm missing or another way to do this ?

<?php
function comment_custom_form_alter($form, $form_state, $form_id) {
  if ($form_id == 'comment_form') {
    foreach ($form['comment_filter']['format'] as $i => $filter) {
      if (is_int($i) && !$filter['#type']) {
        $form['comment_filter']['format'][$i]['#value'] = '';
        $form['comment_filter']['format'] = '';
        unset($form['preview']);
        unset($form['_author']);
      }
    }
  }
}
?>

Administer > Site Configuration > Input Formats

Click configure for each of the formats, and edit which roles can see which format.

You can also look at Better Formats.

  Set the default format per role. Set the default format per content
  type. Control allowed formats per content type. Hide format tips. Hide
  more format tips link. Hide format selection for nodes, comments, and
  blocks seperately, forcing the default to be used. Expand the
  selection fieldset by default. Disable the expand/collapse of the
  selection fieldset. Set selection fieldset title. Set more format tips
  link text. Set default formats for nodes and comments separately.
  Sensible defaults and fail overs for ease of use. Works with CCK
  textareas. Works with Panels comment form. i18n module support for
  user defined strings

.

Also if you want to hide it completely you can also unset the filter form element in your form alter but I don't think it is the right way to do it.

unset($form['comment_filter']['format']);

NOTE: If you do so you will loose out on text processing and checks which drupal makes to make sure the html is safe.

This should also work

$form['comment_filter']['format']['#access'] = FALSE;

This will make sure the format is not accessing to anyone.

Try this

function modulename_form_alter(&$form, &$form_state, $form_id) {
 if ($form_id == 'comment_form') {
  $form['comment_filter']['format']['#access'] = FALSE;
 }
}


How do you add a prefix to an existing drupal database for single site use? I have a drupal 7 site running on a webserver, it is currently using a database that was created with out a prefix.

I am attempting to restore that database to a new drupal instance from a shared hosting provider. I am using the Backup and Restore Module to move the database.  One thing I have no apparent control of is that their "quick install script" creates a new drupal database with a "drupal_" prefix.

Do I need to convert my existing database to have that prefix, because as it seems now my migrated changes are not even being read since it probably has both sites data sitting side by side, and the  database information I want to be reading  entries  from don't have the prefix? Is that reasoning correct? If so how do I convert my Drupal database to the same one but now with the necessary prefix applied throughout?

If you have phpMyAdmin the simplest way is to:

go to the "Structure" tab (where there is the list of tables).
select all the tables (with the "Check All" checkbox at the end of the list)
in the dropdown list close to the "Check All" select the action "Add table prefix" (or "Replace table prefix" if that is the case)
insert the prefix, press the button and let it do all the work.

After that remember to specify the prefix in the site\default\settings.php

array (
  'database' => 'sample_drupal_db',
  'username' => 'sample_drupal_usr',
  'password' => 'sample_drupal_pwd',
  'host' => 'localhost',
  'port' => '',
  'driver' => 'mysql',
  'prefix' => 'prefix_', // <<== prefix here
),


Persistent variable (`variable_set()`) name restrictions Are there any restrictions, conventions, etc. for the names of persistent variables created with variable_set()?

Aside from project name prefix, I haven't found anything in the documentation. However, I notice that most modules restrict themselves to the same rules that apply to PHP variables.

Until Drupal 7, the main storage for the variables is the variable table in the same database Drupal uses.

The name column is a varchar(128) so that requires the variable names to have equal or fewer characters than 128.

Prefixing the variable names is purely by convention. Drupal Form API can handle spaces in machine names too, but you will almost never see a form array item key with spaces in it.

There are workarounds, but it's easier if there are no spaces, for example when you use drush, export settings, etc.


Using custom functions in Views template files = not good practice? I have a field in my View that outputs a YouTube URL (eg. http://www.youtube.com/watch?v=rF1X12PE6PY)

I want to output just the ID part (ie. rF1X12PE6PY)

So I made a module with a function that takes the full URL and returns just the ID. Then in my views-views-fields.tpl.php template I call the function:

<?php print youtube_id_get($fields['url']->content); ?>

Now this works fine, but something tells me it's not good Drupal practice?

Will this screw up Views performance/caching? Should I create a custom Views filter instead (still learning about such things)?

This should be just fine, however, The REAL Drupal way to do this, would be for your module to provide a field formatter to views that calls this function. There are many modules which do nothing but provide functions. CTools, for example.

Having a field formatter removes your site's functionality from the "view". Which is a best practice with any kind of software. You'll be able to change the theme in the future without worrying about your youtube IDs. Creating a formatter isn't hard to do, here is a great tutorial on how to do it.

Once you have a formatter, you can simply select it from the drop down in the View's UI and you're done!


How do I use the global class \Drupal static methods to access services? Is there a difference between calling \Drupal::service('config.factory') and \Drupal::configFactory()?

Is it better to use the second one?

Can \Drupal be used to do something else than calling services?

The documentation says:

  Accessing services in global functions

  The global Drupal class provides static methods to access several of
  the most common services. For example, Drupal::moduleHandler() will
  return the module handler service or Drupal::translation() will return
  the string translation service. If there is no dedicated method for
  the service you want to use, you can use the Drupal::service() method
  to retrieve any defined service.

In which cases isn't there any dedicated method? How do I easily list all the retrievable services?

\Drupal::service('config.factory') and \Drupal::configFactory() are equivalent; the second is just shorter.

There are many, many services provided by core, and only a few of them have a dedicated method. You can get a list of core services on the core.services.yml page. Note that this is not all services that core offers, for example, there are more services in user.services.yml.

Also note that when working with classes, it's better to use dependency injection rather than calling static methods. Static methods should be called in procedural code (in D8, this basically means hooks, or API functions).

This is a slideshow I used when doing a presentation on dependency injection at Drupal Camp Tokyo this month.


hook_modules_enabled called before hook_menu (Note: the code and module names have been simplified for demonstration)

I have a number of custom modules in a Drupal 7 site. One of the modules (a 'base' module enabled during site installation) creates a custom menu (operations-menu) along with a hook (hook_operations_menu()) for customizing the menu. Other custom modules (I'll refer to them as implementing modules) with a need to add menu links into the operations-menu can simply implement hook_operations_menu() and return the appropriate menu item definitions.

Example:
Assuming my base module is called 'base' and my implementing module is called 'implements'.

base.module

/**
* Implements hook_modules_enabled()
*/
function base_modules_enabled($modules) {
  $links = [];
  foreach ($modules as $module) {
    $module_links = module_invoke($module, 'operations_menu');
    if(is_array($module_links))
      $links = array_merge($links, $module_links);
  }
  foreach ($links as $link) {
    menu_link_save($link);
  }
}

implementing.module

/**
* Implements hook_operations_menu()
*/
function implementing_operations_menu() {
  $links = [];

  // Define menu links here

  return $links;
}

/**
 * Implements hook_menu()
 */
function implementing_menu(){
  $items = [];

  // Define menu callbacks, etc.

  return $items;
}

This strategy works well to maintain a modularized custom menu with one exception. For some reason, when enabling the implementing module, base_modules_enabled() is called before implementing_menu(). This is a problem since some menu links defined in implementing_operations_menu() depend on routing established in implementing_menu().

I've checked the source code, and module_enable() invokes hook_modules_enabled() at the very end. I don't understand how hook_menu() is getting called after hook_modules_enabled() and not before.

Any assistance is greatly appreciated!

So, here's the solution. Hopefully it helps save someone else some time. As it turns out, hook_menu() is not invoked during module enabling. As such, I had to force a menu rebuild which invokes hook_menu() and ensures all the proper routes exist prior to building my menu links.

base.module>

/**
* Implements hook_modules_enabled()
*/
function base_modules_enabled($modules) {
  menu_rebuild(); // <--- Added this line to force hook_menu() to be called first
  $links = [];
  foreach ($modules as $module) {
    $module_links = module_invoke($module, 'operations_menu');
    if(is_array($module_links))
      $links = array_merge($links, $module_links);
  }
  foreach ($links as $link) {
    menu_link_save($link);
  }
}


Breadcrumb in drupal I want to breadcrumb in drupal8
that display as url as home / list page /  node page.
I just have in breadcrumb home > node page.
I use bootstrap breadcrumb.

Drupal 8 uses the page alias to build up the breadcrumb trail. Your "node page" would need to contain the "list page" alias to make it work e.g.
List page = /mylist
Node page = /mylist/mynode

If you want to use the menu structure then you could try this https://www.drupal.org/project/menu_breadcrumb


Theming Form Fields: Alter all fields In Drupal 7, you can put the following code in template.php to add the class 'vr-paragraphs' to the field called 'field_title'

function THEMENAME_form_alter(&$form, &$form_state, $form_id) {
       $form['field_title']['#attributes']['class'][] = 'vr-paragraphs';
}

How can I modify this code to target all fields on the form and not just 'field_title'.

Also, this code only adds the class to the form-wrapper part of the filed. How can I alter the label part?

Thanks for any help!

When you need to find the child items present in a form, you need to use element_children(), as Drupal functions like filter_process_format() do.

The reason is simple: In a Drupal form array, as well as in a render array, not all the keys are child items; those keys with a name that starts with # are properties. Consider, for example, the form returned from forum_form_forum(); if you loop through it with the following code, you would add values where you should not.

foreach($form as $key => $value) {
  $form[$key]['#attributes']['class'][] = 'vr-paragraphs';
}

In fact, $form['#submit'] is not a child item, nor is $form['#theme']. In particular, when your code will be executed for the last key, you would get a PHP error. $form['#theme'] is a string, and $form['#theme']['#attributes'] would select a character of that string, supposing that '#attributes' would be evaluated as the integer 0; even in that case, $form['#theme']['#attributes']['class'][] would not be a valid PHP construct.

The correct code would be the following one.

foreach(element_children($form) as $key) {
  $form[$key]['#attributes']['class'][] = 'vr-paragraphs';
}


Content referencing the referenced content I've been searching and cannot find a way to achieve this: display content referencing a content that is referenced by the content being displayed.

It may be somewhat confusing but I'll do my best to be clear:

I have two content types: 'Company' and 'Service'
As you can imagine a Company provides many Services, so there is an Entity Reference field in Services that points to the Company providing it.

That's it:  Service content points to Company content in a many to one relation, many services point to one company (the company that provides them)

When I display a Service, I also display the company that provides it through the Entity Reference field.

Now the tricky part is:
When displaying the page for a Service, I'd like to also show (e.g. in a sidebar) the other services provided by the Company that the displayed Service is pointing to.

I'm using Panels and Views on Drupal 7.

Please note: this is not a simple 'related content block', that's what I am using to display the company providing the content or when displaying the Company content

I don't see any problem here. or any difficulties to do this.. You only need a block with services of certain company, so you can create a views block , pass company id as argument (by contexual filter), and exclude current service from it.. But, I don't think that simply assigning it to region can help you, because you will need to fetch company id from service page and pass it to view block. I think the solution will be to implement hook_block_info and hook_block_view hooks to create another block and fetch company id from service page and display it..

example:

function MYMODULE_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case 'company_service':
        // there is multiple ways to get field value from entity. In this example I am it getting with entity_metadata_wrapper function from Entity API:

        $service_node = menu_get_object();
        $service_wrapper = entity_metadata_wrapper('node', $service_node);

        $company_id = $service_wrapper->field_company->value(); // I don't know the structure of your entity fields, that's why we assume that $service_wrapper->field_company->value() will get company_id..

        $block['subject'] = t('Company services');
        $block['content'] = views_embed_view(VIEW_NAME, DISPLAY, $company_id);
      break;
  }
  return $block;
}


Can we customize user login block in Hybridauth module Can we customize user login block in Hybridauth module in our custom theme?
Like writing block-hybridauth-hybridauth.tpl.php.

I need to customize the way of output. Instead of the Sign In icon which gives the overlay of enabled social accounts list, I need some text to replace it and add div and content along with it? Is it possible?

There are two template files used

hybridauth_widget.tpl.php

This one is used to create the list of the icons. It gets a variable called $providers which has all the enabled providers.

hybridauth_provider_icon.tpl.php

This one is used to print the individual icons. Two variables are used here. $provider_name is the name of the provider like facebook twitter etc. and $icon_pack_classes which has the current selected icon pack classes.

These template files can be found in with in the templates folder of the module.

You can make copy of the same in your theme and make the required changes.


How do I get the name of the content type? in Drupal 7, which function do I need to call to get the name of the content type? I have the $node object and I also have the id of the content type if I use $node->type. But I need to get the name of the content type set in the system, not the ID as something like 'name_of_the_content_type'. I need it as 'Name of the content type'.

Thank you.

Try calling this function

node_type_get_name($node)

  Returns the node type name of the passed node or node type string.


Altering the admin/content form After having added a “changed by” on nodes I now need to display the user who modified each node on the node_admin_content form (at admin/content) right next to the "Author" column.

I've managed to easily solve this by altering node.admin.inc and adding just 2 lines of code:

...
'changed_by' => t('Changed By'),
...

...
'changed_by' => theme('username', array('account' => user_load($node->changed_by))),
...

This, of course, is not a proper solution since it alters the core.

So I then tried altering the form via:

function hook_form_node_admin_content_alter(&$form, &$form_state, $form_id) {
  $form['admin']['nodes']['#header']['changed_by'] = t('Changed By');
  // ... ?
}

Using dpm I can see that the form has the nodes in options. The problem is that this is the result of rendering the nodes as table options. I don't have access to the original nodes, nor do I want to re-execute the node fetch query in order to get the "changed by" information. I guess doing this in the form hook would not be solving it in the correct layer. Or is it?

So, what is a good way to alter the node_admin_content form to add more data that exists on nodes?

The bad news is that having inspected the code, the form alter layer is the only place to really do this; your approach is pretty much spot on.

The good news is, Drupal implements all sorts of static caching throughout the page load, which minimises the need to go back into the database. So while altering the content table may appear cumbersome, you're not actually taking a noticeable performance hit.

The following code (or similar) should work; see the comments for more info about the caching issue:

function MYMODULE_form_node_admin_content_alter(&$form, &$form_state, $form_id) {
  // Load the nodes. This incurrs very little overhead as
  // "$nodes = node_load_multiple($nids);" has already been run on these
  // nids in node_admin_nodes(). The static cache will be used instead of
  // another db query being invoked
  $nodes = node_load_multiple(array_keys($form['admin']['nodes']['#options']));

  // Grab a list of all user ids that have been responsible for changing the node
  $uids = array();
  foreach ($nodes as $node) {
    $uids[] = $node->changed_by;
  }

  // Filter out duplicates (one user may have been the last to change more than one node)
  $uids = array_unique($uids);

  // Load a list of all involved users in one go. This is about as performant
  // as this is going to get, as you're going to need the user objects one
  // way or the other for the call to theme_username
  $users = user_load_multiple($uids);

  // Add another column to the table header
  $form['admin']['nodes']['#header']['changed_by'] = array('data' => t('Changed by'));

  // Loop through the rows in the table and add the changed by column
  foreach ($form['admin']['nodes']['#options'] as $nid => $row) {
    // Grab the user related to this node.
    $this_user = $users[$nodes[$nid]->changed_by];

    // Add data for the new column
    $form['admin']['nodes']['#options'][$nid]['changed_by'] = theme('username', array('account' => $this_user));
  }
}

The above code produces a nice shiny new column like this on the content admin page:


How do I disable the cache? I have created the settings.local.php file inside the default folder and uncommented the the following lines.

$settings['cache']['bins']['page'] = 'cache.backend.null';
$settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';

I also uncommented code in settings.php file, but Drupal is still caching the code. What's the solution for this? I am using Drupal 8.6.10.

I added these parameters in the development.services.yml file.

parameters:
  twig.config:
    debug: true
    auto-reload: true
    cashe: false

The settings.php file contains the following lines.

if (file_exists($app_root . '/' . $site_path . '/settings.local.php')) {
   include $app_root . '/' . $site_path . '/settings.local.php';
}

The Page Cache and Dynamic Page Cache store complete pages, but Drupal also uses the Render Cache to store page fragments (e.g. the teaser display of each node).

To disable the render cache, set it to use the null backend as well:

$settings['cache']['bins']['render'] = 'cache.backend.null';


Theme specific drupal commerce product form I want to create a .tpl file for each specific product type form. I get that I can create a custom product template and add this code on my theme's template.php:

'commerce_product_ui_product_form' => array(
               'arguments' => array(
                    'form' => NULL,
                    ),
               'template' => 'templates/products form/node--add--product', // set the path here if not in root theme directory
               'render element' => 'form',
            )

The problem is this changes all the product type's form. How can I find the Form ID for each specific product type form?

It's the same form ID for every type, but you can find context in the form state, e.g.

function MYMODULE_form_commerce_product_ui_product_form_alter(&$form, &$form_state, $form_id) {
  $product = $form_state['commerce_product'];
  $product_type = commerce_product_type_load($product->type);

  if ($product_type->name == 'foo') {
    // ...
  }
}


How to pass different arguments to view I am using profile2 field as user reference and also i filter results with an entity selection. The widget used is an autocomplete and i have a problem with it. If i type in the nid of a user the result returned is correct, but it does not work if i type in the name of the user or anything else related to it besides nid.

Example:

for this url everything is fine ( returns the name of profile with nid == 1):

entityreference/autocomplete/single/field_test/profile2/profiletype/NULL/1

but if i type "name" the result is null

  entityreference/autocomplete/single/field_test/profile2/profiletype/NULL/name

Is there any configuration that i miss ? Is it possible to change the behavior of autocomplete ?

The answer was to modify the views query!


Why doesn't skip_on_empty work when migrating from a text field? I'm trying to migrate Drupal 7 users to Drupal 8.  In Drupal 7, there's an additional text field representing the user's group.  In Drupal 8, it's a taxonomy vocabulary.  So I'm using the following pipeline:

  field_user_group:
    -
      plugin: skip_on_empty
      method: process
      source: field_directorate
    -
      plugin: extract
      index:
        - 0
        - value
    -
      plugin: entity_generate
      value_key: name
      bundle_key: vid
      bundle: groups
      entity_type: taxonomy_term
      ignore_case: true

field_directorate is the source field in D7, and field_user_group is the target in D8.

Records without that value set should be caught by the skip_on_empty plugin, and left blank, but that plugin seems to be failing (letting the process continue to the next plugin in the pipeline) as I'm getting errors from the extract plugin saying:

  Array index missing, extraction failed.

According to the documentation,

  The skip_on_empty process plugin checks to see if the current input value is empty (empty string, NULL, FALSE, 0, '0', or an empty array). If so, the further processing of the property or the entire row (depending on the chosen method) is skipped and will not be migrated.

How is the processing even getting to extract if skip_on_empty is supposed to skip values with an empty array?

It works fine for records with the value set.

I now believe this to be caused by Get process plugin sets multiple for empty array.


Programmatically get all names of an entity reference field Example: I want to get all tag names that are inside field_tags of node 5.

I can get the target_id with $node->field_tags->getValue();

But the problem is, I don't know what entity the target_id value belongs to. Could be a node id, term id, user id. Without that info, I am not able to use the target_id to get the name of the tag.

How can I get all the names of an entity reference field?

The easiest way to get what you want is something like this:

$names = [];
foreach ($node->field_tags as $item) {
  if ($item->entity) {
    $names[$item->entity->id()] = $item->entity->label();
  }
}

->entity is a so called computed property, it doesn't show up in getValues(). All reference fields have it.

And yes, forget about print_r() on entity or other complex objects. They contain objects that reference each other, and print_r() can't handle that. If you have an entity, always use print_r($entity->toArray()), then you get the field values only. You could install devel module or use a debugger, but that will give you the internal structure of an entity, which is not really want you want to see.


Drupal 8 missing filter view schema After run unit tests i am getting fail

Schema errors for views.view.example_form_element with the following errors: views.view.example_form_element:display.default.display_options.filters.my_module.expose.example_element missing schema

I understand the error but i can't solve it. I tried a lot of combinations of schema.yml file name and content but without success result.

I will point out, that module name is

  my_modules

but

  example_element

is under

  my_module

current file looks like

file config/schema/my_modules.views.schema.yml

views.filter.views_example_element:
  type: views_filter
  label: 'xxx'
  mapping:
    expose:
      type: mapping
      label: 'Exposed'
      mapping:
        example_element:
          type: integer
          label: 'xxx'

file Plugin/views/filter/ViewsExampleElement

@ViewsFilter("views_example_element")

What is wrong with it?

Try change in my_modules.views.schema.yml type on views.filter.many_to_one


Remove "submitted by" text on teaser only I read on How do I remove the "submitted by" text on node display? where you can remove this in the content type settings for the node itself, but is there a way to only change the teaser so it does not display "submitted by" text?

I'm looking for a non-preprocess function or module way to do this; I can't use my theme to deal with it.

I was hoping to avoid using Computed Field module for something so trivial.

That setting is checked and the information added in template_preprocess_node().

Which means that there is no other way than a preprocess function to change this. However, there is nothing stopping you from adding a preprocess function to a module, that works perfectly fine. You just need to make sure that your module runs after node.module by setting the weight in the system table to something higher than node (probably 0).

Code example by will:

In your .install file:

db_update('system')
  ->fields(array('weight' => 1))
  ->condition('type' => 'module')
  ->condition('name' => 'moduleName')
  ->execute();

And then in the .module file:

function moduleName_preprocess_node(&$variables) {
  // Do not display post information on teasers
  if ($variables['teaser']) {
    $variables['display_submitted'] = FALSE;
  }
}


How to create a preconfigured block/view. I am looking for a way to create a view/block that is styled with CSS by myself, that can have content uploaded by an administrator, that will automatically use the same styles.

So it is easy for the admin to add content repeatedly that will automatically through my preconfiguration layout with the CSS as I have styled it.

I thought maybe I could create a content type then run it through a view and place that view on the page that I need it. I this case it is an Image/Icon with a link and text description, so the admin can upload the content easily and it will layout as I have styled it without them needing to write any CSS.

Thanks

Ant:-)

Yes I could work with a specific content type and views.
an alternative way is to create a module with a specific form to change the content block, and to add the content to the block API.

1 _ add your admin path

function my_module_menu() {
 $items['content_block'] = array(
  'menu_name' => 'main-menu',
  'type' => NORMAL_MENU_ITEM,
  'title' => 'My content block',
  'page callback' => 'drupal_get_form',
  'page arguments' => array('my_module_form'),
  'access arguments' => array('admin_content_block'),
 );
 return $items;
}

2 _ Set your permission

function my_module_permission() {
 return array(
  'admin_content_block' => array(
      'title' => t('Can change content block'),
  ),

}

3 _ A form dedicated to your admin, allowing to change the content :

function my_module_form($form, &$form_state){

$form['block_content'] = array(
   '#type' => 'textarea',
   '#title' => t('Block Content'),
    '#default_value' => variable_get('my_module_block_content', ''),
);
$form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Submit'),
);

return $form;
}

function my_module_form_submit($form, &$form_state) {
   variable_set('my_module_block_content', $form_state['values']['block_content']);
}

4 _ your block view

function my_module_block_info() {
$blocks['block_content'] = array(
  'info' => t('Block Content'),
);
return $blocks;
}

function my_module_block_view($delta = '') {
if ($delta == 'block_content') {
    $block['subject'] = t('Your block title');
    $block['content'] = variable_get('my_module_block_content', '');

    }
return $block;
 }


How can I force users to provide a reason when cancelling their accounts? I would like to force users to provide a reason for cancelling (a text area would be ideal) their accounts.  I have had several users close their accounts on one of my sites recently and I would like to know why.

Here you go, alter the user_cancel_confirm_form.

function MYMODULE_form_user_cancel_confirm_form_alter(&$form, &$form_state, $form_id) {
  $form['reason'] = array(
    '#title' => t('Reason'),
    '#type' => 'textarea',
    '#description' => t('We are sad to see you go, why do you want to leave?'),
    '#required' => TRUE, // force to input
  );

  $form['#submit'][] = 'user_cancel_log_reason'; // add custom submit handler
}

function user_cancel_log_reason($form, &$form_state) {
  $reason = $form_state['values']['reason'];
  // do whatever with the reason, e.g watchdog
  watchdog('user', 'User cancel reason:' . $reason);
}


How to write custom access for a route which redirects the user to another route if a condition is true If I visit example.route.one and certain conditions are fulfilled I want to redirect it to example.route.two OR else access should be allowed.
How Can I achieve this? I tried writing the redirection in the custom controller routeOne but this method does not work properly for non-admin users, the issue being if I click/visit example.route it automatically redirects me to example.route.two
Menu Yml file - example.links.menu.yml
example.route:
  title: 'Route Example'
  route_name: example.route
  parent: system.admin
  description: 'Contains Route Example'
  weight: -99

example.route.one:
  title: 'Route One'
  route_name: example.route.one
  description: 'Route one example'
  parent: example.route
  weight: 1

example.route.two:
  title: 'Route Two'
  route_name: example.route.two
  description: 'Route two example'
  parent: example.route
  weight: 2

Routing File - exmaple.routing.yml
example.route:
  path: '/admin/route'
  defaults:
    _controller: '\Drupal\system\Controller\SystemController::systemAdminMenuBlockPage'
    _title: 'Route Example'
  requirements:
    _access: 'TRUE'

example.route.one:
  path: '/admin/route/one'
  defaults:
    _title: 'Route one'
    _controller: '\Drupal\example\Controller\ExampleController::contentOne'
  requirements:
    _custom_access: '\Drupal\example\Controller\ExampleController::routeOne'
  options:
    _admin_route: TRUE

example.route.two:
  path: '/admin/route/two'
  defaults:
    _title: 'Route two'
    _controller: '\Drupal\example\Controller\ExampleController::contentTwo'
  requirements:
    _custom_access: '\Drupal\example\Controller\ExampleController::routeTwo'
  options:
    _admin_route: TRUE

Controller for custom access - ExampleController.php
<?php

namespace Drupal\example\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Access\AccessResult;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\Core\Url;

/**
 * Defines a route controller .
 */
class ExampleController extends ControllerBase {

  /**
   * {@inheritdoc}
   */
  public function routeOne() {
    if (TRUE) {
      $response = new RedirectResponse(Url::fromRoute('example.route.two')->setAbsolute()->toString());
      $response->send();
      return AccessResult::forbidden();
    }
    else {
      return AccessResult::allowed();
    }
  }

  /**
   * {@inheritdoc}
   */
  public function routeTwo() {
    return AccessResult::allowed();
  }

  /**
   * {@inheritdoc}
   */
  public function contentOne() {
    return [
      '#type' => 'markup',
      '#markup' => $this->t("hello route one"),
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function contentTwo() {
    return [
      '#type' => 'markup',
      '#markup' => $this->t("hello route two"),
    ];
  }

}

The issue if you click/visit example.route it automatically redirects to example.route.two is caused by the access method not only called when you visit example.route.one, but also on other pages with links pointing to example.route.one, for example in a menu.
So use access methods only for calculating access results. If this then results in a 403 you can catch it in an event subscriber and set a redirect response instead of the default 403 message.
See Dynamically change the "access denied page" title and body.


Send user a reminder email after x-number of days if Profile2 field is empty and user has specific role I have a multi-step user signup process. When the user creates their account, they are assigned role "A" and are redirected to a Profile2 form with various fields. If they complete and save their Profile2 form, they are assigned role "B" and role "A" is removed from their account.

I need to send an automated reminder email to the new user 5 days after their account was created, if they are still assigned user role "A". The email's purpose would be to remind them to log in and complete their Profile2 form. How can I accomplish that kind of time delay using Rules? If not rules, are there any other modules that would accomplish this?

Thanks!

Here is my solution, based on tenken's advice:

I created a Rule COMPONENT with the condition "User has role: Role A" and the action "Send email".

I then created a Rule...

Events: After saving a new user account
Conditions: None
Actions: Schedule component evaluation

In that Action, I chose these options:
Component: the component from step 1
Scheduled evaluation date: account:created
Add offset: 5 days
User > Data Selector: account


show specific number of posts on front page for mobile d7 I would like to show only a few posts for mobile I have mobile_detect as well as mobile_detect_ctools mobile_detect_variables, installed and working.

I am using an adaptive theme, $is_mobile successfully in theme/page.tpl but I am unable to use it in settings.php where I believe I need to set.

$conf['default_nodes_main'] = $mobile-frontpage-post-number //(much lower than desktop);

How can I put global $conf vars in page.tpl or get $is_mobile from mobile_detect_variables working in settings.php.

tyvm.

I ended up just redirecting the mobile devices to mobile front page(view),
I was trying to avoid this, but it does not seem to be much trouble.

Add this code near the top of MYTHEME/page.tpl.php

<?php if ($is_mobile == TRUE && drupal_is_front_page()):
drupal_goto('/mobile');
endif;
?>

Then you can adjust the pager, number of posts etc. I suppose this
is a workaround not an answer.


Add programmatically created field to content type form I've programmatically created a content-type with 3 fields (in D8).

The fields are created but do not show up on node creation. If I go to the content-type form display, the fields are there, but I need to save this page to get the fields to show up on node creation.

The content-type and fields are created in yml-files and the Looks like this:

config/install/field.field.node.slideshow_slide.slide_weight.yml

langcode: en
status: true
dependencies:
config:
    - field.storage.node.slide_weight
    - node.type.slideshow_slide
module:
    - text
enforced:
    module:
        - custom
id: node.slideshow_slide.slide_weight
field_name: slide_weight
entity_type: node
bundle: slideshow_slide
label: 'Weight'
description: 'This slides weight'
required: false
translatable: false
default_value: 0
default_value_callback: ''
settings: { }
field_type: string

config/install/core.entity_form_display.node.slideshow_slide.default.yml

langcode: en
status: true
dependencies:
config:
    - field.field.node.slideshow_slide.slide_image
    - field.field.node.slideshow_slide.slide_link
    - field.field.node.slideshow_slide.slide_weight
    - node.type.slideshow_slide
module:
    - image
    - link
id: node.slideshow_slide.default
targetEntityType: node
bundle: slideshow_slide
mode: default
content:
slide_image:
    label: visible
    weight: 101
    settings: {  }
    third_party_settings: {  }
slide_link:
    label: visible
    weight: 100
    settings: { }
    third_party_settings: {  }
slide_weight:
    label: visible
    weight: 100
    settings: { }
    third_party_settings: {  }
links:
    weight: 100

Found out that it needed "type" for all the fields in the form_display.