Ajaxly set Text Field Value with Drupal Forms API

I suggest you instead of creating link and try to call ajax with old method( call form your custom js file ) try  drupal ajax method

My suggestion is :

function yourmodule_form_alter(&$form,$form_state,$form_id){
if($form_id=='your specified form name '){
$form['id_number'] = array(
    '#title' => t('ID Number'),
    '#type' => 'textfield',  //textfield
     '#prefix' => '
',
    '#suffix' => '
'
    '#attributes' => array('id' => 'myid_search_id_number'),
 );
$form['myajax'] = array(
        '#type' =>'button',
        '#value' => t('fill me'),
        '#ajax' => array(
            'callback' => '_myfuction_fill_number_ajax',
            'wrapper' => 'vm-container',
            'method' => 'replace',
            'effect' => 'fade',
            'prevent'=> 'sumbmit',
        ),
    );
 }
}
function _myfuction_fill_number_ajax(&$form,$form_state){
     $form['id_number'] ['#default_value'] = myid_some_function();
    // if not work try it with  $form['id_number'] ['#value'] = myid_some_function();
      return $form;
    }

also if you can want do ajax with jquery, add js file to your form, in that js file  set click handler for your link (  tag) and in click  call $.ajax with you menu rout.


Why file name and uri of the file in database are different?

The reason for difference is that multiple files with same name can be uploaded in Drupal, so when you upload a file, it adds a counter at the end of filename so that if a file with same name is uploaded again, then it doesn't replace another one.

Also the filename column contains the exact name of the uploaded file as it is used while downloading the file (the file will be downloaded with this name).


Does the tmp directory have to be shared between servers?

Yes, if you have multiple servers serving the same domain, then you need to ensure that the two Drupal server instances share the same filesystem. Best is to use NFS mount, so it is physically only one folder. You may get by with rsync in a cron depending on how the filesystem is used in your application.


How to do a newsletter / mailing list with Drupal 7

Use Simplenews and Mime Mail and/or HTML Mail to achieve this.


How to delete a path when uninstall a module?

You can use hook_uninstall and MenuLinkManager::removeDefinition

  Removes a single link definition from the menu tree storage. This is
  used for plugins not found through discovery to remove definitions.


How do I sell points using a new product type?

To answer your question in order to give you a solution. That people can "top" up here is maybe an alternative.

Drupal Userpoint Feature request

  Remember to use dev version.

Commerce Userpoints

What about something like this ?

1) Rule

Event: on payment completed
Action: loop through the order line-items. Each line-item has an action to call the next component with parameters of order and the line-item.

2) Component

Parameters: order, line-item
Condition: data comparison line-item:type is Product (to expose line-item:commerce-product)
Action: call next component with parameters of order and line-item:commerce-product

3) Component

Parameters: order, product
Condition: data comparison product:type is Product (to expose the product:field-points-to-add)

Action: add userpoints, number to add being
product:field-points-to-add


Get non-standard user attributes in layout

First, to access the additional user fields you will need to load the full user object using an available user id with the user_load() function.

global $user; //This contains the basic information for your current user.

$account = user_load($user->uid); //$account now includes all of your custom account fields.

Now that you have the fully loaded user object you will need to choose a template to modify.

Depending on where the values need to be, this could be one of many templates.  I highly recommend checking out the Theme Developer module to help find preprocessing functions and available templates to override.

There is some fantastic information on setting up variables for use in a template here.

Example snip:

<?php
function drop_preprocess_foo(&$variables) {
  // Do not do this unless you mean to:
  $variables['foo_list'] = array('list item 4');
  // Instead do this:
  $variables['foo_list'][] = 'list item 4';
}
?>


Lightbox is specifically design to preview images. For General purpose overlay preview for images, videos, iframe and any custom html/text I recommend to use Fancybox. Fancybox module is available for integration in druapl.

$.fancybox("Your HTML");


define a template file for a field item in my modules

In hook_theme you define and register your templates.

In your code your template will be "myplugin".
To use that template you need to specify "#theme" => "myplugin" in your render array (not my-field-item-template). Then twig tries to render your content with the file called "myplugin.html.twig". This twig file should be stored in the templates directory of your module.

You may read this https://www.drupal.org/docs/8/theming/twig/debugging-twig-templates to learn more about debugging theming.


How to construct a content type that would be useful for creating a "When is this store open" view

Unless you've got a system managing alot of stores and open hours, it's probably easiest to just have a static "Page" with the store open hours on it. A basic page can be easily content managed.


Custom login redirect failed in hook_user_login

drupal_goto() will use $_GET['destination'] when it is set. The following is the code used from the function.

  if (isset($_GET['destination']) && !url_is_external($_GET['destination'])) {
    $destination = drupal_parse_url($_GET['destination']);
    $path = $destination['path'];
    $options['query'] = $destination['query'];
    $options['fragment'] = $destination['fragment'];
  }

Setting $edit['redirect'] inside hook_user_login() doesn't have any effect.
What you can do is changing $_GET['destination'] in hook_user_login(). If you want to be sure the user is redirected to the path you set, you should be sure your hook is executed last, for example by increasing the weight of your module.


Access field object (not render array) in field templates

The field template receives its values from the parent entities' view display build array. This build array doesn't contain separate keys for the original fields on their components build arrays.

But a field preprocess function receives enough information to extract them: The 'element' item contains an '#object' key that holds the original entity, and a '#field_name' key that holds the name of the field. (Which is also available in the template as field_name thanks to template_preprocess_field().)

If you'd like to access the original field, you could do something like:

$element = $variables['element'];
$field_item_list = $element['#object']->get($element['#field_name']);

Which should return an instance of a class that implements FieldItemListInterface (FieldItemList, EntityReferenceFieldItemList, ...).


I think there are no need of any menu or other submit button.

You can use hook_node_insert for create a different node form partial data of a node  upon creation on node.

The statement is like:

function MODULENAME_node_insert($old_node) {

 if($old_node->type === 'article'){ // check node type

    $new_node_title =  $old_node->title; // get partial data from old node

    $node = new stdClass(); // We create a new node object
    $node->type = "page"; // Or any other content type you want

    $node->title = $new_node_title; // Assign partial data of old node to new node

    $node->language = LANGUAGE_NONE; // Or any language code if Locale module is enabled. More on this below *
    $node->path = array('alias' => 'your node path'); // Setting a node path
    node_object_prepare($node); // Set some default values.
    $node->uid = 1; // Or any id you wish
    // Let's add standard body field
    $node->body[$node->language][0]['value'] = 'This is a body text';
    $node->body[$node->language][0]['summary'] = 'Here goes a summary';
    $node->body[$node->language][0]['format'] = 'filtered_html'; // If field has a format, you need to define it. Here we define a default filtered_html format for a body field

    $node = node_submit($node); // Prepare node for a submit
    node_save($node); // After this call we'll get a nid
 }

}

If this not fullfil your requirement then use some other HOOKS provided by Node API


Create an admin menu in a MENU_LOCAL_TASK

After further investigation reading the code here, it appears that this can be done.

For example, admin/tasks has admin menu children in a MENU_LOCAL_TASK however, it appears that it looks at the current local task's parent item and then looks for MENU_NORMAL_ITEM children.

Unfortunately, this doesn't work in my case since I use wildcard urls (%node) and my local task is not the default one. (like the admin/tasks one is).

So I came up with a workaround function that achieves what I need.

The function my_module_account_settings($node) basically queries the DB for the current MENU_LOCAL_TASK's mlid, then queries the database for ALL menu links that have the current MENU_LOCAL_TASK's mlid as their parent.

I then call the theme function for admin_block_content and boom.

Let me know if anyone comes up with either a better, or more correct way of doing this.

function my_module_menu() {
  $items = array();
  $items['node/%node/settings'] = array(
    'title' => 'Account settings',
    'description' => 'Manage your account settings.',
    'page callback' => 'my_module_account_settings',
    'page arguments' => array(1),
    'access arguments' => array(1),
    'access callback' => 'my_module_access_account_settings',
    'type' => MENU_LOCAL_TASK,
    'weight' => 1000,
  );
  $items['node/%node/settings/upgrade'] = array(
    'title' => 'Upgrade your account',
    'description' => 'Use this form to upgrade your account.',
    'page callback' => 'my_module_upgrade_account',
    'page arguments' => array(1),
    'access arguments' => array(1),
    'access callback' => 'my_module_access_account_settings',
    'type' => MENU_NORMAL_ITEM,
  );
  $items['node/%node/settings/cancel'] = array(
    'title' => 'Cancel your account',
    'description' => 'Click here to cancel your account and remove all your data.',
    'page callback' => 'my_module_cancel_account',
    'page arguments' => array(1),
    'access arguments' => array(1),
    'access callback' => 'my_module_access_account_settings',
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

function my_module_account_settings($node) {
  $current =  menu_get_item();

  // get current MENU_LOCAL_TASK mlid
  $current_mlid = db_select('menu_links' , 'ml')
    ->condition('ml.link_path' , $current['path'])
    ->fields('ml' , array('mlid'))
    ->execute()->fetchField();

  // get all menu_links where the parent link id is the current
  // MENU_LOCAL_TASK
  $rows = db_select('menu_links' , 'ml')
    ->condition('ml.plid' , $current_mlid)
    ->fields('ml' , array('mlid', 'link_path'))
    ->execute()->fetchAllKeyed();

  foreach ($rows as $mlid => $path) {
    // load each of the admin menu items within this local task
    // in my case i replace the placeholder/wildcard with the node nid
    $item = menu_get_item(str_replace('%', $node->nid, $path));
    if ($item['access']) {
      $items[] = $item;
    }
  }

  // return the themed block
  return theme('admin_block_content', array('content' => $items));
}

function my_module_access_account_settings($node) {
  if ($node->type == 'organisation') {
    if (user_access('edit org account settings')) {
      return TRUE;
    }
  }
  return FALSE;
}


Why and when is feeds_entity_load needed

It isn't.

feeds_entity_load() was removed from the Feeds module 3 years ago. It no longer exists in the codebase (download and grep -nr feeds_entity_load feeds, the only reference you'll find is in the changelog).

You should upgrade your version of feeds ASAP, you must have an outdated version installed.


How to boost search relevance based on certain values using Search API

It would be insanely complex to do this properly, since you need to alter some very core Search API mechanics, much of which is handled by the database backend and not search api itself.

What you could do as a hack, it to

Create two fields: A and B.
Select a non existing word like ethsrtsghtpofksd
Add the word in field A when it's an editorial and in field B when it's not an editoral.
Set the searcg weight for field A to be higher than field B
Add the word to all searches before search API sends it to the DB.

Since the word is used in all searches and it always is matches (either in field A or B) it won't effect the results, but the weight they get will be different since field A will get a boost. I haven't tried this before, but it should work. But like I said it's a hack so it's not a pretty solution, but it's a clever way of avoiding to mess with the internal workings of Search API module.


How to add PHP to a node without php filter?

It really depends since you're planning to add functionality then the best place would be a module but if you're altering HTML or basically the output and maybe quite a little raw data manipulations then that could be in your theme.

Mostly a basic question that needs to be asked is, do you want the "thing" to be functional when you turn off or change your theme? If yes then that would give a strong idea that you would be creating a custom module.

For adding PHP code with panels, you can create custom panel panes. For nodes, your can use blocks or hook_preprocess_node() to add your code in the node level.


How do I paginate results with db_query?

db_select() is the way to go using a so called query extender. Here is a simple example:

$query = db_select('node', 'n')
  ->condition('type', 'article')
  ->extend('PagerDefault')
  ->limit(10);

Then theme_pager() can be used for outputting a pager.

Find more details on this drupal.org working example


Changing block templates based on context? moving title in body field in template

You mention the word 'context' in the first line of your question. Take a look at the Context module. I just came from this page

http://www.metachunk.com/blog/context-based-template-suggestions-drupal-7

Edit: elaborating .. here's the context module
http://drupal.org/project/context
Install it and create a context 'mycontext' for your 3 pages.

Based on this context, provide a template suggestion as mentioned in Topsitemakers' answer. In your themes template.php, it should be something like (not tested)

mytheme_preprocess_block($&vars) {
  $context = context_get();
  if(isset($context['context']['mycontext'])) {
    $vars['theme_hook_suggestions'][] = "block__mycontext";
  }
}

You can do this more generic as described in the post linked above. Now, your block will render using block--mycontext.tpl.php, if it exists, when shown in the 'mycontext' context.

$2c,
*-pike


I cannot see the dblog of my kickstart commerce

I found in the Commerce kickstart documentation that the dblog is disabled by default due to this functionality consumes a lot of resources.

Enable database logging module and then rebuilt the menus as suggested by Clive


How to modify the page at admin/structure/types?

see Can you change the list builder class used by an entity?

Using hook_entity_type_alter() you can override the list builder for nodes.

You can add a custom NodeListBuilder in your module that extends or replaces /core/modules/node/src/NodeListBuilder.php

This class is pretty simple, so it should be easy to add or remove rows to the table displayed.


How to create a theme that handle articles in different categories?

You will want to create different content types for each type article.

I would then use Views and Panels to create the page. Create a view for each subset of article types then place each view in your panels page.

You could also do it with a theme by creating what panels creates for you but you would still need a view with a block setting and then places the views block in the correct section of your site and set the block to only show on the home page.

The views+panels is a much cleaner implementation that is theme independent.


You need to go into People -> Permissions -> Roles.  Find the administrator role and click on 'Edit Permissions'.

Then, go down to the Node section, and check off the appropriate permissions for viewing, creating, editing, deleting, etc.. that particular content type.  The permissions actually look like this:

Article: Create new content [ ]
Article: Edit own content   [ ]
Article: Edit any content   [ ]
Article: Delete own content [ ]
Article: Delete any content [ ]

You'll of course want to check off probably all of those if the role is an administrator, as typically they'll have absolutely power over your application.  That is, if it's what you intend.  The power of Drupal is yours :)


How to remove markups of 'div' and 'span' from the billing info displayed through token

If you want to alter the content of tokens you could try using the Token Function module: http://www.drupal.org/project/token_function

With this module you can write a simple function to alter the content of a token (or use one of the few existing functions).

I hope this helps.


You can't write to /usr/bin on OSX (since Yosemite).

Add your symlink to /usr/local/bin instead, and make sure that's in your path.

ln -s /usr/local/src/drush/drush /usr/local/bin/drush


How do I create radio button for options on a Drupal Commerce product?

Sounds like you're after either the Commerce Product Option module:

This module adds customizable product options to the "add to cart" form. The approach is generic, so all field types / widget can be used. This module is created only for the commerce module. For other systems you need different systems / approaches.
The module provides a field called option set. You can assign to your commerce product. Each option set consists of a list of fields. If a product is connected to a option set the add to cart form will be extended by the fields of the option sets.

Or the Commerce Product Attribute module:

This module provides some enhancements to the Drupal Commerce attribute handling.
The improvement contains:
Attribute field for line itemEdit option for attributes

I'd advise installing both of those and seeing which fits your use case better. You'll have to handle the AJAX functionality yourself as I don't think it's built in to either.


Views to display recent content with user pictures

Add a relation ship of the type content:author and use that relationship to add the user profile image.

Hope that helps.

EDIT : A description as per the comment

1) From RELATIONSHIPS(This would be in the advanced section on the right side) click on add. it will bring up a list of fields that you can add.

2) Add the Content: Author relation ship.

3) Now When you try to add the a field additional fields would be displayed related to the user you can select  User: Picture. The relationship author should be select.


The best way to do this is to disable the module, remove the '.old' folder and then re-enable the module. Unless disabling the module is destructive, this is the course of action I would recommend.

Otherwise you need to call registry_rebuild, though as you've realised you can't do this from a module because your site won't bootstrap. There is drush command made just for this case which you can find at https://drupal.org/project/registry_rebuild

If none of this works, you will need to manually edit the database ; you will need to manually edit the 'system' table and clear the system cache. Not recomended.

Whichever option you go for, make a backup of your database first!


How to know if my XML Sitemap being submitted?

If you are using Drupal 7, it will show that your sitemaps have been submitted in your log messages at Admin > Reports > Recent Log Messages (/admin/reports/dblog)

Click on "Filter log messages" and select "xmlsitemap"

If you do this, it will show when the last sitemap was generated and when it was submitted the the search engines that you have configured it to submit to (in my case, Google and Bing).


"Initial Menu Level" config in Block Layout not working

Please check the following:

The link for the menu item should be <front>?parameter=value
The position and weight in the menu tree at admin/structure/menu/manage/MENU_NAME
This patch may be related


is the view page of events when we click on read more its takes me to the content display page (the second image) like there are sponsers block is there of individual node above that i need page links to show other fields which i use to save during creating the node like speakers and other thingd]1


Views, how to show x-items from each tag?

A possible solution involves creating two views, one of taxonomy terms, and another one of articles, and using Views Field Fiew to embed the article view as a field in the taxonomy terms view.

Create a taxonomy term view that shows fields. Add the title (optional) and Term ID fields. We'll come back to this one in a moment.
Create a view of content - of your sport articles that contain the tags. You can use an unformatted list of teasers, or if you want to include only some fields, an unformatted list of fields. My example uses teasers. IMPORTANT: Select a limited number of items to display. In my example I'm limiting it to 3. I won't use a pager in this example.
In the Advanced fieldset of the second view, add Contextual Filters. Select Content: has taxonomy term ID. Then in When the filter is not in the URL : Display content of "no results found".
Go back to your taxonomy term view. Add field Global: View. Select the View and Display of the view of content created in step 2. IMPORTANT: in the Contextual filters textfield, add the token for the Taxonomy term ID field (usually [%tid])

That's it. Visit your taxonomy term view and you'll see a list of 3 articles per term.

This is what the Views UI for the two views look like:

View of terms

View of content


You're probably looking for:

http://updates.drupal.org/release-history

From the update.module file:

/**
 * URL to check for updates, if a given project doesn't define its own.
 */
define('UPDATE_DEFAULT_URL', 'http://updates.drupal.org/release-history');

It's worth noting the "if a given project doesn't define its own." part of that - the vast majority of modules use the standard Drupal URL, but not necessarily all of them. If you have any modules that haven't been installed via Drupal.org, check through their .info file and look for the project status url key. If any modules define a value for that, you'll also want to whitelist it.


How to add classes to every X number of node in a array

For node listings for which the node.tpl.php (or a different node template) is being used you have variables like $zebra and $id at your disposal that you can use for this kind of tasks. You can see all the available variables with descriptions in the node modules node.tpl.php file or here.

For example if you want to add the necessary class to this line:

<div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>

you could use code snippets like these:

<?php $classes .= ' '.$zebra; ?> - add 'odd' to every first and 'even' to every second node in the list
<?php if (!($id % 2)) $classes .= ' last'; ?> - add 'last' class to every second node.
<?php if (!($id % 3)) $classes .= ' last'; ?> - add 'last' class to every third node.


exposed filter result : how to check the results is lesser than 20 or greater than 20...?

using the below code to check the result is greater than or lesser than 20

global $pager_total_items;
  print $pager_total_items[0] ;

if($pager_total_items[0]>20)
  {
    print 'Result is greater than 20';
  }
  else
  {
    print 'Result is lesser than 20';
  }

In this code put into your theme folder like mytheme/templates/page.tpl.php file.

but this is working only that particular theme because of i write that code into mytheme page.tpl.php file thats why...


How can I write users table data in custom file?

Your just need get your select put it in FOREACH and write down in file.(something like below code can help you_

$results= db_select('users','u')->fields('u',array('uid','name','email'))->execute()->fetchAll();
if($results){
     $fh=fopen(drupal_get_path('module',   'yourcustommodulename').'/usertest.txt','w+');
     foreach($results as $res){
     $string= 'uid:'.$res->uid.' ,name:'.$res->name.' ,email:'.$res->email.'\n\r';
    fwrite($fh,$string);
  }
  fclose($fh);

}


Safe to add a class attribute to the HTML element via the theme?

You should use .addclass():

<html{{ html_attributes.addClass('no-js') }}>

That would prevent the output in the example from your question and the result will be:

<html class="drupals-class no-js">


I've seen it often that the path is simply built by concatenating strings. But if you want to do it in a D8 way, then use the route from the view.

You can investigate the routes with Drupal Console on the command line or the Devel module in UI, where you'll find the routes in /devel/routes.

For example this view:

ROUTE NAME: view.testview.page_1    PATH: /testview/{arg_0}/{arg_1}

When you know the route name and the arguments for the contextual filters you can build the URL:

use Drupal\Core\Url;

  $url = Url::fromRoute('view.testview.page_1', [
    'arg_0' => $arg1,
    'arg_1' => $arg2,
  ]);

The URL is an object, which you put in a render array, for example in a link element. If needed you can get the path as string with the method ->toString(), but this should be avoided.

If you want to use the route in a field rewrite you can use the twig function url() in a field replacement pattern:

Link to Testview


How an user set his own password while creating account

Maybe this module is for you: User registration password


Module(s) doesn't enable properly with Drush

This is a bug in either Drush, Drupal or the Entity Reference Revisions module (which the Paragraphs module depends on). The solution is to enable the Entity Reference Revisions or the Paragraphs module from Drupal itself, not with Drush. You can safely download the modules with Drush.

See my Drush issue at https://github.com/drush-ops/drush/issues/2873 for more information.

No, I can't reproduce this issue with other modules. (I'm using the same setup as you.)


How to filter a node reference field in content type form

I've written step by step instructions on how to do that.

Your setup will be a bit different since you don't use flags. "Step 3" describes how to use the "views reference" feature to show the referenced nodes on your node/add,edit page using views.


How to use Rules to send an eMail with a body containing all items of a field collection?

Part 1: Custom Rule
Have a look at this rule (in Rules export format), which IMO is a possible answer to your question:
{ "rules_field_collection_msg_and_email_body" : {
    "LABEL" : "Field Collection msg and eMail body",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_view" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_article_details" } },
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "3" : "3" } }
        }
      }
    ],
    "DO" : [
      { "variable_add" : {
          "USING" : {
            "type" : "text",
            "value" : "\u003Ch2\u003EThis is a demo of a node containing a field collection ... \u003C\/h2\u003E\r\n\u003Chr \/\u003E\r\n\u003Cstrong\u003EAbout this demo\u003C\/strong\u003E:\u003Cbr \/\u003E\r\n\u003Cbr \/\u003E\r\nThe machine name of the field collection is \u003Cstrong\u003Efield_article_details\u003C\/strong\u003E, and the number of values for it is unlimited.\u003Cbr \/\u003E\r\nThis field collection has these fields:\u003Cbr \/\u003E\u003Cbr \/\u003E\r\n- a text field labeled \u003Cstrong\u003EAuthor\u003C\/strong\u003E with machine name \u003Cstrong\u003Efield_author\u003C\/strong\u003E.\u003Cbr \/\u003E\r\n- a decimal field labeled \u003Cstrong\u003EPrice\u003C\/strong\u003E with machine name \u003Cstrong\u003Efield_price\u003C\/strong\u003E.\u003Cbr \/\u003E\r\n- a boolean field labeled \u003Cstrong\u003EApproval required\u003C\/strong\u003E with machine name \u003Cstrong\u003Efield_approval_required\u003C\/strong\u003E.\u003Cbr \/\u003E\u003Cbr \/\u003E\r\n\u003Chr \/\u003E\r\n\u003Cstrong\u003EPart 1\u003C\/strong\u003E: The  list of items contained in the field collection with machine name \u003Cstrong\u003E\u0027field_article_details\u0027\u003C\/strong\u003E looks like so (note the comma to separate each item):\r\n\u003Chr \/\u003E\r\n[node:field_article_details]\r\n \u003Chr \/\u003E\r\n\u003Cstrong\u003EPart 2\u003C\/strong\u003E: The result of a \u003Cstrong\u003ERules loop\u003C\/strong\u003E that iterates for each of the field collection items (using its unique ID) ...\r\n\u003Chr \/\u003E"
          },
          "PROVIDE" : { "variable_added" : { "variable_for_email_body" : "Variable to use in eMail body" } }
        }
      },
      { "drupal_message" : { "message" : "\u003Ch2\u003EThis is a demo of a node containing a field collection ... \u003C\/h2\u003E\r\n\u003Chr \/\u003E\r\n\u003Cstrong\u003EAbout this demo\u003C\/strong\u003E:\u003Cbr \/\u003E\r\n\u003Cbr \/\u003E\r\nThe machine name of the field collection is \u003Cstrong\u003Efield_article_details\u003C\/strong\u003E, and the number of values for it is unlimited.\u003Cbr \/\u003E\r\nThis field collection has these fields:\u003Cbr \/\u003E\u003Cbr \/\u003E\r\n- a text field labeled \u003Cstrong\u003EAuthor\u003C\/strong\u003E with machine name \u003Cstrong\u003Efield_author\u003C\/strong\u003E.\u003Cbr \/\u003E\r\n- a decimal field labeled \u003Cstrong\u003EPrice\u003C\/strong\u003E with machine name \u003Cstrong\u003Efield_price\u003C\/strong\u003E.\u003Cbr \/\u003E\r\n- a boolean field labeled \u003Cstrong\u003EApproval required\u003C\/strong\u003E with machine name \u003Cstrong\u003Efield_approval_required\u003C\/strong\u003E.\u003Cbr \/\u003E\u003Cbr \/\u003E\r\n\u003Chr \/\u003E\r\n\u003Cstrong\u003EPart 1\u003C\/strong\u003E: The list of items contained in the field collection with machine name \u003Cstrong\u003E\u0027field_article_details\u0027\u003C\/strong\u003E looks like so (note the comma to separate each item):\r\n\u003Chr \/\u003E\r\n[node:field_article_details]\r\n \u003Chr \/\u003E\r\n\u003Cstrong\u003EPart 2\u003C\/strong\u003E: The result of a \u003Cstrong\u003ERules loop\u003C\/strong\u003E that iterates for each of the field collection items (using its unique ID) ...\r\n\u003Chr \/\u003E" } },
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-article-details" ] },
          "ITEM" : { "article_details_item" : "article details item" },
          "DO" : [
            { "data_set" : {
                "data" : [ "variable-for-email-body" ],
                "value" : "[variable-for-email-body:value]\u003Cbr \/\u003E\r\nThe host entity of this field collection item: [article-details-item:host]\u003Cbr \/\u003E\r\nThe unique ID of the field collection item: [article-details-item:item-id]\u003Cbr \/\u003E\r\nField \u0022field_author\u0022: [article-details-item:field-author]\u003Cbr \/\u003E\r\nField \u0022field_price\u0022: [article-details-item:field-price]\u003Cbr \/\u003E\r\nField \u0022field_approval_required\u0022: [article-details-item:field-approval-required]\u003Cbr \/\u003E\r\n\u003Chr \/\u003E"
              }
            },
            { "drupal_message" : { "message" : "The host entity of this field collection item: [article-details-item:host]\u003Cbr \/\u003E\r\nThe unique ID of the field collection item: [article-details-item:item-id]\u003Cbr \/\u003E\r\nField \u0022field_author\u0022: [article-details-item:field-author]\u003Cbr \/\u003E\r\nField \u0022field_price\u0022: [article-details-item:field-price]\u003Cbr \/\u003E\r\nField \u0022field_approval_required\u0022: [article-details-item:field-approval-required]\u003Cbr \/\u003E\r\n\u003Chr \/\u003E" } }
          ]
        }
      },
      { "mail" : {
          "to" : [ "site:current-user:mail" ],
          "subject" : "Demo of an eMail with a body containing all items of a field collection",
          "message" : [ "variable-for-email-body" ],
          "language" : [ "" ]
        }
      }
    ]
  }
}

Some more details about what this rule does:
- Rules Event: Content is viewed (change to whatever fits).
- Rules Conditions:

Entity has field, for entity=node and field (machine name)= field_article_details (adapt this machine name to whatever fits).
User has role(s), for user=[site:current-user] and role administrator  (adapt this condition to whatever fits, or just delete it entirely, doesn't make any difference).

- Rules Actions (this is where the party starts ... pay attention!):

Add a variable (to use in eMail body later on ...), with machine name variable_for_email_body (adapt to whatever fits), and set an initial value which corresponds in the demo with everything from Part 1 and the header line from Part 2.

Show a message on the site, this is just for QA-testing, to see what's happening when the previous Rules Action is executed. It shows the equivalent of the initial value assigned to the variable_for_email_body variable from the previous step.

Add a Loop for list [node:field-article-details] (are you following, the field collection field!), and for list item use article_details_item. Within this loop, add these Rules Actions:

Set a data value, for variable [variable-for-email-body] (which we added as the very first Rules Action!), and with value (watch out, here comes the clue) ... something that looks like so (in each iteration of this Rules loop, we concatenate (append) the actual data for each field collection item to the end of the our [variable-for-email-body:value], and surround it with whatever other fixed text and/or HTML tags that we want to see in our eMail body):

[variable-for-email-body:value]

Host entity of this field collection item: [article-details-item:host]

Unique ID of the field collection item: [article-details-item:item-id]

Field "field_author": [article-details-item:field-author]

Field "field_price": [article-details-item:field-price]

Field "field_approval_required": [article-details-item:field-approval-required]

Show a message on the site, this is just for QA-testing (also), to see what's happening when the previous Rules Action is executed. It shows what got concatenated (appended) to the previous value assigned to the variable_for_email_body variable.

Send mail, which is extremely basic (after the work completed in the loop above ...):

To: [site:current-user:mail] (adapt to whatever fits)
Subject: Demo of an eMail with a body containing all items of a field collection (adapt to whatever fits)
Message: [variable-for-email-body] (adapt to whatever fits, either you add anything to the message body BEFORE or AFTER this message body here, or you adapt what gets moved as content of this variable in the previous Rules Actions Add a variable or Set a data value)

If you have the Rule UI enabled, you should be able to import the above rule in your own site, provided you first apply some of the changes I suggested, after you adapt the machine names to fit your names. After importing you may want to also change any of its events or conditions in it, or apply changes to any of its actions.
Part 2: Demonstration
Status message
This is a demo of a node containing a field collection ...
About this demo:

The machine name of the field collection is field_article_details, and the number of values for it is unlimited.
This field collection has these fields:

- a text field labeled Author with machine name field_author.
- a decimal field labeled Price with machine name field_price.
- a boolean field labeled Approval required with machine name field_approval_required.

Part 1: The list of items contained in the field collection with machine name 'field_article_details' looks like so (note the comma to separate each item):
Approval required:     No
Price:     12.45
Author:    Pierre Vriens
,
Approval required:     Yes
Price:     9.15
Author:    Barak Obama
,
Approval required:     No
Price:     3.40
Author:    Hillary Trump
,
Approval required:     Yes
Price:     1.23
Author:    Donald Clinton

Part 2: The result of a Rules loop that iterates for each of the field collection items (using its unique ID) ...
Host entity of this field collection item: 73
Unique ID of the field collection item: 1
Field "field_author": Pierre Vriens
Field "field_price": 12.45
Field "field_approval_required": No
Host entity of this field collection item: 73
Unique ID of the field collection item: 2
Field "field_author": Barak Obama
Field "field_price": 9.15
Field "field_approval_required": Yes
Host entity of this field collection item: 73
Unique ID of the field collection item: 3
Field "field_author": Hillary Trump
Field "field_price": 3.40
Field "field_approval_required": No
Host entity of this field collection item: 73
Unique ID of the field collection item: 4
Field "field_author": Donald Clinton
Field "field_price": 1.23
Field "field_approval_required": Yes

eMail body
This is how the entire content of the body of the delivered eMail looks like (look for "Part 2" in it to see the most interesting, I think, part of it):

-------- THIS IS A DEMO OF A NODE CONTAINING A FIELD COLLECTION ...----------

------------------------------------------------------------------------------
*About this demo*:
The machine name of the field collection is *field_article_details*, and the
number of values for it is unlimited.
This field collection has these fields:
- a text field labeled *Author* with machine name *field_author*.
- a decimal field labeled *Price* with machine name *field_price*.
- a boolean field labeled *Approval required* with machine name
*field_approval_required*.
------------------------------------------------------------------------------
*Part 1*: The  list of items contained in the field collection with machine
name *'field_article_details'* looks like so (note the comma to separate each
item):
------------------------------------------------------------------------------
-------- APPROVAL REQUIRED: ------------------------------------------------

No
-------- PRICE: ------------------------------------------------------------

12.45
-------- AUTHOR: -----------------------------------------------------------

Pierre Vriens
 * Delete [1]
 * Edit [2]

,
-------- APPROVAL REQUIRED: ------------------------------------------------

Yes
-------- PRICE: ------------------------------------------------------------

9.15
-------- AUTHOR: -----------------------------------------------------------

Barak Obama
 * Delete [3]
 * Edit [4]

,
-------- APPROVAL REQUIRED: ------------------------------------------------

No
-------- PRICE: ------------------------------------------------------------

3.40
-------- AUTHOR: -----------------------------------------------------------

Hillary Trump
 * Delete [5]
 * Edit [6]

,
-------- APPROVAL REQUIRED: ------------------------------------------------

Yes
-------- PRICE: ------------------------------------------------------------

1.23
-------- AUTHOR: -----------------------------------------------------------

Donald Clinton
 * Delete [7]
 * Edit [8]

 * Add [9]

------------------------------------------------------------------------------
*Part 2*: The result of a *Rules loop* that iterates for each of the field
collection items (using its unique ID) ...
------------------------------------------------------------------------------
Host entity of this field collection item: 73
Unique ID of the field collection item: 1
Field "field_author": Pierre Vriens
Field "field_price": 12.45
Field "field_approval_required": No
------------------------------------------------------------------------------
Host entity of this field collection item: 73
Unique ID of the field collection item: 2
Field "field_author": Barak Obama
Field "field_price": 9.15
Field "field_approval_required": Yes
------------------------------------------------------------------------------
Host entity of this field collection item: 73
Unique ID of the field collection item: 3
Field "field_author": Hillary Trump
Field "field_price": 3.40
Field "field_approval_required": No
------------------------------------------------------------------------------
Host entity of this field collection item: 73
Unique ID of the field collection item: 4
Field "field_author": Donald Clinton
Field "field_price": 1.23
Field "field_approval_required": Yes
------------------------------------------------------------------------------

[1]http://www.example.com/field-collection/field-article-details/1/delete?destination=node/73
[2]http://www.example.com/field-collection/field-article-details/1/edit?destination=node/73
[3]http://www.example.com/field-collection/field-article-details/2/delete?destination=node/73
[4]http://www.example.com/field-collection/field-article-details/2/edit?destination=node/73
[5]http://www.example.com/field-collection/field-article-details/3/delete?destination=node/73
[6]http://www.example.com/field-collection/field-article-details/3/edit?destination=node/73
[7]http://www.example.com/field-collection/field-article-details/4/delete?destination=node/73
[8]http://www.example.com/field-collection/field-article-details/4/edit?destination=node/73
[9]http://www.example.com/field-collection/field-article-details/add/node/73?destination=node/73

I know, the formatting of this eMail body is pretty (really?) poor, but watch what's below the line with "Part 2": everything you possibly may want to know about every item in your field collection, in the eMail body ... which is exactly what this question was about, no? So just reformat the eMail content to your liking (i.e delete everything in it you don't want, and improve the formatting of what you're really interested in).


How to get a dropdown list with content of other content type

You need to use Entity Reference module..

Project page says

  Provides a field type that can reference arbitrary entities:

  A generic entity reference field

  Four widgets:

  Two implemented on top of the Options module (Select and
  Radios/Checkboxes),

  Two autocomplete widgets (one with one text field per entry, one
  tag-style with comma- separated entries in the same text field)

  Two formatters:

  A "Label" formatter, with optional link that displays the label of the
  referenced entity (the node title, the user name, etc.)

  A "Rendered entity" formatter, that renders the references entity
  using a configurable view mode

  Integration with Views (for both forward and backward references)

  Integration with Entity Metadata (and as a consequence with Search API
  and the like)

  Integration with Devel generate

  Integration with Feeds and Migrate (>= 2.3) for painless data import


How can I fix the node list page broken by changing the reference field from a term reference to an entity reference

I got it.  I had initially been trying to create  a new view to operate on the /pub/by/publisher/% path, but I realized by inspecting the view, that the view I already had on /taxonomy/term/% was handling the route because links to one of the pathauto generated routes end up being to the equivalent of /pub/by/publisher/term-name?destination=/taxonomy/term/tid

The problem is then to get the existing view to show the results I want.  In my case, since the existing view was showing no results for any publisher vocabulary term, and publisher terms should be the only terms that return results for my new view; I had the option of adding an attachment or other view in the no results section or to just create an attachment attached after the main view.  I added an attachment and added it after the main view.  Since I needed the results of two entity reference fields I needed an OR condition between my contextual filters.  For this I used Views Contextual Filters OR.

One additional problem I faced was that my filters and contextual filters were being joined with an OR condition rather than an AND condition, meaning that I was effectively querying for public nodes or the right type OR the nodes I actually want, which returned way more results than intended.  The solution for this, was to add a new empty filter group to my attachment, joined to the original filter group with an AND condition, this caused it to start joining my contextual filters with AND as well.

Finally, my main view had some exposed filters on it, but thought I had inherit exposed filters checked on the attachment, those exposed filters were not working.  It turns out that you need to add the same exposed filters to the attachment before the inheritance on them will work.

I doubt many people will have exactly the same problems I had, but hopefully it will provide a clue for people with something similar.  As seems to always be the case @no-sssweat was instrumental in providing the hints I needed to get to the answer.  Thank You!


Is it possible to turn off Ajax load for Commerce Coupon Module?

Maybe you run into this bug https://www.drupal.org/node/2412549.

Apply the two patches mentioned in comment #9

  If you really want to turn of AJAX, you need to hook all the
  corresponding forms and unset #ajax.

i would not suggest this thoe !


AddThis Icons Being Blocked on SSL/HTTPS Site

I ended up contacting AddThis and they told me the Drupal module is outdated, and to instead use this code:

So I put the first line (the  tag) in my html.tpl.php file and put the rest of the code in a block in my footer. I had to make sure to put all the  tags on the same line otherwise Drupal was forcing  tags between them making it impossible to style the toolbox correctly. Making sure the block content was set to 'Full HTML' and I was good to go.

The negative of this approach is that it requires another call to an external script. The positive is it negates the need for another module - you can safely remove 'addthis'.


Use hook_menu_alter() to override existing menu entries.


Drupal Commerce Custom Line Item Types without a Product Reference Field

A line item must have a product associated with it. Rules, Commerce Cart, and Commerce Shipping all depend on having the commerce_product field on a line item object.


Twig error "Uknown image_style filter", but the filter isn't missing

The error message isn't complaining about a missing Drupal image style - it's complaining about a missing Twig filter named image_style.

That filter doesn't exist in Twig/Drupal core, but it does exist in the Twig Tweak module. Make sure that module is available and installed, and the error should disappear.

If you've never had Twig Tweak installed then it's probably custom. In that case search your codebase for Twig_SimpleFilter('image_style' and you should find the culprit.


Here is what I would do:

1) Create a view BLOCK instead of page.

2) Go to manage display of your taxonomy page and disable all fields (you should have an empty page now).

3) In blocks, grab your view name block and put it under content area.

Select Display Only In.

In the text box, put: product/*  (so it will display the view in all /product pages).


How to make a collapsible fieldset in my theme?

Your theme might include jQuery 1.9. With this, I observed in Drupal 7.34 that fieldsets would not work (always shown collapsed, unclickable). Also CKEditor would not load (using the ckeditor module) and there might be other JavaScript related misbehavior.

To solve this, use jQuery 1.8 instead. I recommend the module jquery_update to handle jQuery versions in Drupal.


How can I get translation for a field of custom date

In Twig, you can use built-in translation contexts. I had to output my dates in dutch format. The default formatting was:
{% set date = node.created.value|date("j") ~ ' ' ~ node.created.value|date("F") ~ ' ' ~ node.created.value|date("Y") %}
// now {{ date }} outputs: 8 August 2020

When I use translation contexts, it worked as expected:
{% set date = node.created.value|date("j") ~ ' ' ~ node.created.value|date("F")|t({}, {'context' : 'Long month name'}) ~ ' ' ~ node.created.value|date("Y") %}
// now {{ date }} outputs: 8 augustus 2020

More about translation contexts in Twig: https://stefvanlooveren.me/blog/translate-dates-twig-drupal-8


Add CSS-class to current node in module logic

Would hook_preprocess_node help you for this?

Example:

function mymodule_preprocess_node(&$variables) {
  $variables['classes_array'][] = 'blah';
}

The variables array contains all information about the ndoe as well, so you can run logic to dictate which classes should be added to which node types/IDs etc.

If you run dpm (with the Devel module enabled) then you can print everything in that array that you can alter/add to.

I agree that $node->classes would be a really useful addition though.


Filter View based on Relationship to Current User

The only way to do this within views is the following:

Make View of using User type
add a Relationship to a Profile2 type (in my case 'Student')
Add Contextual Filter of type profile:student:location
select "provide default value"
type: "php code"
Use the following code:

global $user;
$profile = profile2_load_by_user($user->uid,'facilitator');
if (!$profile) { return ''; }
if (!isset($profile->field_location['und'])) { return ''; }
$locations='';
foreach ($profile->field_location['und'] as $location) {
  $locations.=','.$location['nid'];
}
return substr($locations,1);

Under "More", Set "Allow Multiple Values" to TRUE
Save your Contextual Filter

Using PHP in this manner, you can load the current User and get associated values to filter by. This may be useful in many other contexts and circumstances.


Field-Group Tabs not displaying on product page

Kind of late to the party, but I ran into this same problem earlier today and it appears to be caused by the fact that the Field Group module hardcodes the entity types that it latches onto.

The 1.x-dev version now includes a HOOK_field_group_content_element_keys_alter() that you can use to expose any entity type to the Field Group module.

To expose products and product variations you need to create a custom module and hook into the above alter function like this

MYMODULE_field_group_content_element_keys_alter(&$keys) {

  if (!isset($keys['commerce_product_variation'])) {
    $keys['commerce_product_variation'] = 'product_variation';
  }

  if (!isset($keys['commerce_product'])) {
    $keys['commerce_product'] = 'product';
  }

}

Hopefully this will be integrated into Drupal Commerce in the near future, but for now this is the only way.

Edit You can read up on the actual issue here https://www.drupal.org/node/2842280


I cannot upload an image - 404 ajax error

This part of the AJAX error message can be helpful for you:

  the requested url /@custom was not found on this server

This may have the following root causes (including but not limited to):

.htaccess settings
Your settings.php


ThemeKey: Use main theme for Node/edit and user/edit

you will need to create a hierarchical set up:

In this example set up, it checks for user:1 (admin), that the node type (content type) is article, and that the path meets the relevant criteria. You will need to adjust accordingly. Simply drag and drop the sub-elements into place.


There's a big difference between creating a custom module for just one site (your own, let's say) and creating one that will be able to be used on many different sites.

For example, let's say I want to limit access to a certain content type to only users of a certain role. Let's say that content type is 'awesome_thing' and the role is 'awesome_person'. There are two ways to go about this.

My own module that no one else will ever see or use

This would probably consist of something like a hook that gets called for each page, examines the $node object to see if it's 'awesome_thing' and then, if it is, examines the $user object to see if it's an 'awesome_person' and, if so, loads the page or whatever.

A module that is fit for contribution to d.o contrib

This would have to include a configuration interface that allows users to specify which content types they want to restrict, and which roles they want to allow on those content types. If there's more than one combination of role and nodetype then you have to deal with that. Then, since you've given a mouse a cookie, people are going to have feature requests, or maybe they'll write patches that add features and you think they're cool and you want to integrate them into a new version of your module.

Then say your module has a dependency on another module for some of these features, or your naming conventions conflict with another module's. On most sites this won't be noticeable so you probably wouldn't ever encounter it as a problem just on your own site. But by the law of large numbers, if you let a whole bunch of people use your module, they're more likely to discover corner cases where things work in unexpected ways than you are to think of every possible use case.

And then someone might look at your module and see that you violated a coding standard or namespace convention. Or they might see that you used 5 lines of code to do something that could be better done in 3 lines, or that you did something that's going to be expensive on performance if the module is used on a large-scale site with higher traffic than yours.

The tl;dr is that writing your own snippet for your one little use-case is exponentially less complex than writing, say, a patch for public consumption which itself is exponentially less likely than a full-blown module to both contain bugs and to have its existing bugs noticed and called out.


You can alter the options in this hook:

/**
 * Alter form options by id.
 *
 * @param array $options
 *   An associative array of options.
 * @param array $element
 *   The form element that the options is for.
 * @param string $options_id
 *   The form options id. Set to NULL if the options are custom.
 */
function hook_webform_options_alter(array &$options, array &$element, $options_id = NULL) {

See http://cgit.drupalcode.org/webform/tree/webform.api.php

The options are stored in the config entity webform_options, see http://cgit.drupalcode.org/webform/tree/src/Entity/WebformOptions.php


How is the views row plugin set? Can I use a views row plugin from a different module?

Row is just a plugin. You can write your own.
See the core/modules/views/src/Plugin/views/row directory.


Translation of select field allowed values

Make sure you enabled the Field Translation module, a submodule (i18n_field) of the i18n module. Some more details about it (from the Community documentation):

  ... allows for translation of text associated with a field's settings including the label, help text, default value, and list options. Translation of these field settings can be added through the 'Translate interface' pages (Administration > Configuration > Regional and language > Translate interface).

Especially the "list options" mentioned above seem to be what you're looking for.


How can I protect the account of the first user, and not allow administration users to alter it?

User Protect

From the project page:

  This module allows fine-grained access control of user administrators,
  by providing various editing protection for users. The protections can
  be specific to a user, or applied to all users in a role.

  Note: User Protect has a complicated configuration -- please take the
  time to read the very extensive module help before using it!

  The following protections are supported:

  username
  e-mail address
  password
  status changes
  roles
  deletion
  OpenID identities
  all edits (any accessed via user/X/edit)

  When a protection is enabled for a specified user (or the protection is enabled because
  the user belongs to a role that has the protection), it prevents the
  editing operation in question that anyone might try to perform on the
  user--unless an administrator who is permitted to bypass the
  protection is editing the specified user. The module will protect
  fields by disabling them at user/X/edit.

  User administrators may be configured to bypass specified protections,
  on either a global or per-administrator basis.

  These protections are valid both when trying to edit the user directly
  from their user/X/edit page, or using the mass user editing
  operations.

  The module also provides protection at the paths user/X/edit and
  user/X/delete, should anyone try to visit those paths directly.

  Note: this module is compatible with the RoleAssign module.


Need to send "High" and "Critical" priority only in email subject line itself

A possible solution might be to use hook_mail_alter to modify the subject. As far as I have seen, the Support Ticket System uses drupal_mail() to send notifications, so this hook would be invoked.

Hope it helps,


Integration of Microsoft Exchange server with Drupal

All recent version of Exchange (2000+) require and Active directory for the authentication and authorization.  Active Directory is integrated via LDAP.


Drupal 7:: create a page with views to show all the contents not authored by current user

For your first problem, Create a content view with a relation Content: Author, than you will get User: Current in side the add filter, Add this filter to your view

Use No for Second problem.


View does not pick up webform submission is from url

OK. I see the problem. The submission will be for only one node, so all you need to get the information is the sid. The nid you are looking at is not the nid in the webform submission record. (You will understand in a moment.)

First, delete both the contextual filter on Content:nid and the filter on Content:nid.

Then create a contextual filter using Webform Submission:sid. Under 'When the filter value is NOT available', select Provide Default Value > Raw value from URL, and set the Path Component to 4.

Now to get the correct nid value, you need to create a Relationship on Webform submissions: Node, and check 'Require this relationship'. Now go back to your fields, and edit the Content:nid field changing 'Relationship' to 'Webform Node', and save. Your field should now display as '(Webform Node) Content: Nid (Nid)'. This is the nid found in the Webform Submission record.

Save your view, and you will get the correct values in the block display. I don't know about the token replacements, but it looks like it should work. If not, the Views PHP module will be able to do it without the tokens, using the $row values directly from your view.

Good Luck.


how to get all the last level term id's of taxonomy in drupal 7?

<?php
function get_term_depth($tid) {
  $limit = 5; // level of your term
  $depth = 0;
  while ($parent = db_select('taxonomy_term_hierarchy', 't') ->condition('tid', $tid, '=') ->fields('t') ->execute() ->fetchAssoc()) {
    $depth ++;
    $tid = $parent['parent'];
    if ($depth > $limit) {
      break;
    }
  }
  return $depth;
}
?>


How do I create a rule that closes comments on node after 30 days?

You need at least 2 rules to make this happen. One is an actual "rule" and the other is a "rule component".

You are correct about the second one being a component which sets the data value on node:comment.

The other one, the rule, needs to be set to activate on the event "After saving new content."

An action for this rule needs to be "Schedule component evaluation". Setting this action then requires you to configure the evaluation, where you set the particular rule component to be evaluated, and then set "Scheduled Evaluation Date" as well.

To make it happen 30 days in the future, enable Data Selection mode, and select "site:current-date", then for the offset field which now appears below it, select 30 days. This will cause your selected rule component to be evaluated 30 days from the current date/time.

After configuring all this and testing it, you can check to see if it works by going back to the Rules interface and going to the "Schedule" tab. Your scheduled task will be listed there.


This can be done by twig template and jquery. Add only 'Status messages' block on 'Highlighted' region. and in the twig template add like below:

{% if page.highlighted %}
          {% block highlighted %}

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                      &times;
                    </button>

Message

                    {{ page.highlighted }}

                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

          {% endblock %}
        {% endif %}

After that in jquery file :

$(window).load(function(){
    if($.trim($("#modal-div .region-highlighted").text()) != ''){//region will be printed even if the highlighted area is blank
        $('#modal-div').modal('show');
    }
});

This will show your messages in modal window.


How can I use some Javascript to force a fieldset to stay open

You could definitely do that with some custom JS, but it might not be worth the trouble as there's a pre-built module which does what you need:
Fieldset collapser

Whenever a user clicks on a collapsible fieldset header to toggle the "collapsed" state, the new state is being saved - uniquely for every form fieldset possible. Depending on the user's being registered with your site or not, this happens either in his user account data or locally on his computer using cookies.
When the same form is called the next time, the fieldset states are restored to what they were last time. For registered users, this happens already on your server while preparing the form. Anonymous users will still see a little form animation by an invisible hand but then also be happy with their favorite fieldset states.


Form not showing in administration menu in Drupal6

You have an an underscore (_) in page_callback. Remove that, clear the caches, and you should be good to go.

function ptm_autocomplete_menu() {
  $items['admin/prestum/autocomplete'] = array(
    'title' => 'Autocomplete',
    'description' => 'Autocomplete',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('ptm_autocomplete_form', array(), array()),
    'access arguments' => array('access administration pages'),
  );

  return $items;
}

Also if this is Drupal 7 your form function should have $form as the first param:

function ptm_autocomplete_form($form, &$form_state, $unused, $form_values) { ...

But not for Drupal 6.


Display default image if the image isn't set

try: make sure in the field settings you have set BOTH default images.  There is one specific to that instance of the field, and one everywhere else it is used. The second is further down the screen:

IMAGE FIELD SETTINGS

These settings apply to the Image field everywhere it is used.


Why does Drupal insist on deleting my configuration?

Yes this is the expected behavior. Config import and export is really quite simplistic (uncharitably: dumb). All it is doing when you run a config operation is to look at the active state of the DB and the active state of the sync directory and make one look like the other. On config:import (cim) you are saying "make the DB match those files in the sync directory". Export does the opposite. It's completely ignorant of other factors. So to make your changes "stick"

enable the module
run drush cex
afterwards drush cim should show "no changes"

NOTE: you can override config in settings.php files by using `$config[my.config.file][a_key] = "my_value". This bypasses whatever the files say to do. This is very useful for per environment overrides or sensitive inputs like API keys.
A simpler approach over this manual writing you have is to add your config yml file to your_module/config/install/. When the module is installed this will be imported to the active config state. As commenters have mention when you then run drush config:export (cex) the files will be added to your config sync directory.
Note that your config in /install are essentially one time use. They should also not include the uuid in the top line of the file that is generated in cex built yml.
If you want to install config again from your /install directory you can accomplish this manually by running: drush cim -y --partial --source=modules/custom/my_module/config/install
--partial means do not remove any configuration.


Adding Quick Tabs Programmatically to a node is not working

I got this to work using node--typename.tpl.php

$tabs = array(
      array(
        'title' => t('Overview'),
        'type' => 'view',
        'vid' => 'product_tabs',
        'display' => 'block_1',
        'args' => $node->nid,
        'weight' => 0,
      ),
      array(
        'title' => t('Dimensions & Weight'),
        'type' => 'view',
        'vid' => 'product_tabs',
        'display' => 'block_4',
        'args' => $node->nid,
        'weight' => 1,
      ),
      array(
        'title' => t('Shipping'),
        'type' => 'view',
        'vid' => 'ps3_games',
        'display' => 'default',
        'args' => $node->nid,
        'weight' => 2,
      ),
      array(
        'title' => t('Ratings & Reviews (' . $node->comment_count . ')' ),
        'type' => 'view',
        'vid' => 'product_tabs',
        'display' => 'block_3',
        'args' => $node->nid,
        'weight' => 3,
      ),
    );
    $qtoptions = array(
      'style' => 'Zen',
      'ajax' => FALSE,
    );
    $qtname = 'commerce_product23';
    $quicktabs = quicktabs_build_quicktabs($qtname,$qtoptions,$tabs);
    print drupal_render($quicktabs['content']);

works with views, but if I try to use nodes it does not.

You should try another method.

Create a Quicktab using the Quicktabs UI. Then create a custom module to override the settings/output of the quicktab using the machine name to target a specific quicktab

For Example:

 function mymodule_quicktabs_alter($quicktabs) {
    $nid = $node->nid
        if ($quicktabs->machine_name == 'quick_tab_front_page') {
        $quicktabs->tabs = array(
          0 => array(
        'nid' => $nid,
        'view_mode' => 'full',
        'hide_title' => 1,
        'title' => 'Full',
        'weight' => '-99',
        'type' => 'node',
          ),
          1 => array(
        'nid' => $nid,
        'view_mode' => 'teaser',
        'hide_title' => 1,
        'title' => 'Teaser',
        'weight' => '-99',
        'type' => 'node',
          ),
        );
        $quicktabs->renderer = 'quicktabs';
        $quicktabs->style = 'Arrows';
        $quicktabs->options = array();
        }
        }


How to add CSS class to password-strength and password-confirm on /user/register page?

Trying to explain, first you need to implement hook_theme(), in this case, you have to implement the function in your template.php file, that is located in the folder that contains the theme you are using (sites/all/themes/your_theme_folder).

function yourThemeName_theme()
{
$items = array();
$items['user_register_form'] = array(
        'render element' => 'form',
        'path' => drupal_get_path('theme', 'yourTheme') . '/templates',
        'template' => 'user-register',
);
return $items;
}

After implementing the function, you have to create the template file, in the example, the template file is called user-register.tpl.php and it's located inside the "yourThemeFolder/template" folder.

In the user-register.tpl.php file you define your custom html, for the form, the code that will be rendered inside the <form></form>.
I can't test this now, but if I'm not wrong you can use the debug function to output the form array and check the fields names of your form.

debug($form);

Your template file would look like this:

<fieldset class="form-wrapper" id="edit-account">
        <legend><?php print t('User Account'); ?></legend>

                <?php
                // print render($form['account']);
                print render($form['account']['name']);
                print render($form['account']['mail']);

                ?>

                <?php
                print render($form['account']['pass']);
                print render($form['account']['pass2']);
                ?>

    </fieldset>

For a more detailed example, check the following link:
https://www.drupal.org/node/350634


Why is there quality loss on my image styles?

Under admin/config/media/image-toolkit there is an option to set the JPEG quality. By default this is 75%, so you should be able to up that to whatever you want.


You can use Views RSS: Content Elements module, I'm using it and works well...


How do I update the documentation on someone elses module?

Documentation pages on drupal.org are normal Drupal nodes. You need special permissions in order to edit these nodes. There is documentation on drupal.org about how to contribute to documentation.

If the module in question includes a README.txt file, then you can submit a patch to the module maintainers that includes the updates. If the module doesn't have a README.txt file, then submit a patch that adds one.


"Image Upload Button" section remove after click on upload

Put the following code in a custom module, this module will act on all users but admin (user 1), this will work after user saves/updates his account.  inside function there are two sentences begining with $form, first will hide user picture field, second will disable it. use only one. code:

// implementes hook_form_alter
function YOURMODULE_form_alter(&$form, &$form_state, $form_id) {
global $user;
$uuid = $user->uid;
/*  check that user is NOT admin (No1) */
if ($uuid !='1') {
if ($form_id == 'user_profile_form') {
//dsm($form);
if (!empty($user->user_picture) {
    // Prevent editing a field
    // hiding the field entirely on the edit form.
    $form['field_user_picture']['#access'] = FALSE;

    // disable update field on the edit form.
    $form['field_user_picture']['#disabled'] = TRUE;
    }
 }
}
}


Slideshow with views - Make slideshow title optional

Yes. Assuming your view is displaying fields (under Format > Show), you'd follow these steps:

Install the views_php module.
Edit your view, adding the fields you wish to display all the time.
Add the boolean field to the view, checking the "exclude from display box."
Add the title field to the view, checking the "exclude from display box."
Add a new field "Global: PHP" to the view. In the "output code" field, enter in the following code:

<?php
$title = NULL;
if ($data->field_field_show_title[0]['raw']['value'] === "1") {
  $title = $row->title;
}

echo $title;
?>

This code assumes your boolean field is called field_show_title. Note that, for whatever reason, $row->field_show_title reports the node ID instead of the value of the field, so I had to dig it out of the data object instead.

Beneath the "output code" field you'll find an "available variables" section which describes the data that views makes available to your PHP snippet.

You may order the fields however you like, of course.


How to calculate result from fields inserted?

Such page can be creating using various approaches, as further explained below.
Using Views and Views Calc
Use the Views module, together with the Views_Calc module. Here is a quote about Views_Calc (from its project page):

... adds simple calculations to a views table. Requires the Views module.
You can SUM, AVERAGE, COUNT, MIN, MAX, or AVG selected columns. A plug in theme makes the view look more spreadsheet-like (right justifies numeric fields, shades calculated columns and rows, and underlines calculated rows).
You can also create custom dynamic fields that can be used in any view using SQL snippets like CONCAT('field_first_name', ' ', 'field_last_name') or DATE_FORMAT(node.created, '%m/%%d/%Y'). The custom fields are set up in admin/settings/views_calc.

Refer to the question about How can I show average votes of fivestar nodes? for some screenprints about how to use this module.
Using Forena
If you'd want to "roll your own cookies" (i.e. some report that perfectly fits your custom requirements), then you might want to consider the Forena module. Here is an excerpt about that from its Community documentation:

Forena Reports is built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports.
It is designed to leverage existing knowledge of HTML, CSS, SQL and JavaScript to help you create rich interactive web reports.

For an example of such custom report, created with Forena, start from the statistics (summary info) of the Watchdog Statistics, as in this Watchdog Statistics sample. Note the red numbers to the right of the table, which are actually hyperlinks that can be used as drill-down reports. I.e. if you click on any of them (like the "2" for "Page not found"), you get a details report about (in this case) the 2 specific records related to the "Page not found"). More details about this specific case can be found in comment #2 of issue 2337327. Obvious, I didn't really do any effort to beef up the look-and-feel of that report, like background, etc.
Disclosure: I'm a co-maintainer of Views_Calc and Forena,
I hope this does not violate the site's policy on self-promotion.


modify Drush uli returned URL string of to include port?

You can create settings.local.php with your development base url:

$base_url = 'http://website-7-26-2-17-res124725.local:8888';  // NO trailing slash!

Drush just uses Drupal's url() function to build user one-time-login link.


You can achieve required customization by using Search configuration module.

additional things can be done with the modules are:

Alter the appearance of the core node search form.
Group content types for more meaningful searching
Restrict search results by the content type. This is a role based
restriction.
Restrict search results from showing individual items.
Alter the pager limit (aka number search item results per page).


You need to do more than simply declare the entity.  The Entity Examples in https://www.drupal.org/project/examples will walk you through each step in the process of declaring the entity, defining the form, and adding menu hooks to be able to manage the entities and the field structure for both the form and display.


Is there an easy way to display Atlassian Gadgets within a Drupal node?

Well, taking a look at the Jira/Atlassian web site, they are based in Java technology. Without going into too many details, because I'd have to learn how their proprietary environment works to advise you further, it is possible to embed Java applets in a Drupal page, in pretty much the same manner that one embeds a YouTube video on a Drupal page: just embed the markup in the same manner as you would any other web page, just make sure that the Drupal page's Input Filters are set to not strip out your embedding tags (such as using the 'Full HTML' Input Filter.)

However, this just gets one of their Java Applets on the page. It's not interacting with any information in your Drupal installation. In order to get your Java communicating with your Drupal installation's data, you need to install something like the Services Module into your Drupal installation hosting these Jira/Atlassian Java Applets, plus the Services REST server, and then create an API within the REST Services Framework that either mimics what the Java Applet expects for it's communications, or custom modify the Java Applets to communicate thru the API you created within Services.

So, no, there is no easy method if you want these Java Applets communicating with your Drupal installation's data. If you just want to display them, AND they support simple embedded like most Java Applets, just use the appropriate Input Filters when placing the Java Applet's embed script in the Drupal page.


Can't uninstall "Translation Language capabilities (tmgmt_language_combination)" dissabled ALL translation modules that might be dependant

Had to go into Phpmyadmin browse system>> search tmgmt_language_combination

Click on edit and set status to 0

Then I had to manually delete the modules, refresh, repaste the modules, then refresh, and finally it showed up as red.


Path to theme within a module / jQuery context?

Use Drupal.settings.pathToTheme.

$("li.green").click(function () {
 $('#logo-img').attr('src', Drupal.settings.pathToTheme + '/images/logo-purple.png');
});

Also, theme_preprocess_page(&$vars) should be in template.php as your_theme_preprocess_page(&$vars);

Good idea to not hard code the theme path, that path structure wouldn't work for all set-ups.


Drupal 7 allows you to create custom date formats on your configuration page under "regional and language" "date and time." Once in admin/config/regional/date-time click the  "Formats" tab. Then click "add format." You can now define custom dates using the variables available on the PHP date website. The drupal config page includes a link to the PHP date website as well.

I believe the output you are looking for would be: l, F dS, Y - ga (values from the PHP date website)

Once saved go back to the date and time config page and click "Add date type." Type in a name for your new display and select your new format.

In views you can now select the new custom date format you just created as your output.


How can I add a taxonomy terms as a CSS class to my views?

You can add a field with the taxonomy term and then exclude it from the view.

Then add as many fields you wish to present, such as Title.

Finally, add a global: custom text, and specify for example:

[title]

Replace with your field names obviously. You can consult the "replacement patterns" that the Views module kindly provides.


What are some reasons unpublished content is visible to anonymous users?

The issue was a bug in node_view_permissions, updating to 8.x-1.2 solved the problem.


How to programmatically display a select list label instead of the value?

I think you should use entity_metadata_wrapper because when the select label changes you don't have to change your code.

Following lines will do what you want:

$wrapper = entity_metadata_wrapper('user', $result->uid);
$gender = $wrapper->field_user_gender->label();

So your code would look like:

function display_results_submissions(){
  $results = db_query("SELECT * FROM {users}");
  $header = array(t('Name'), t('Mail'), t('Gender'));
  foreach($results as $result){
    $wrapper = entity_metadata_wrapper('user', $result->uid);
    $gender = $wrapper->field_user_gender->label();
    $rows[] = array(
      $result->name,
      $result->mail,
      $gender,
    );
  }

  return theme('table', array('header' => $header, 'rows' => $rows));
}

There is a good blog post at http://www.mediacurrent.com/blog/entity-metadata-wrapper


How do I ensure the Content-Type header is present?

Try this ( at the end of Your service callback function ):

drupal_add_http_header('Content-type','application/json; charset=UTF-8');

echo drupal_json_encode($response);


My personal opinion is that this is pretty subjective.

We typically just use the main menu for just top level section links (ie, all links are at the top-level and don't have children), and then will have a menu per site section.  We will also typically have a sub menu for extra header links and extra footer links.  Our theme will take care of displaying the proper menu on pages.

Keep in mind that we also do highly custom themes for large sites, so this scheme may not apply for your needs.


How to use t() function with node_load in custom drupal module?

Node translation should be done at the node level.  the t() function is for labeling elements of the interface and theme things.

You should look at multi-language node translation modules,  this link is helpful

You'd first want to use something like this:  https://api.drupal.org/api/drupal/modules!translation!translation.module/function/translation_node_get_translations/7

It'll let you get the NIDs of the translated versions of the node you want,  then you can use node_load() to get the translated version.


The Profile2 Registration Path module allows you to create different registration forms to register users using different roles and different profile types.


Calendar legend on taxonomy via relationship?

Try the fullcalendar module if you want to color-code calendar views.

It's also handy because you can display a legend in an autogenerated block that helps users figure out what each color represents, etc.  It's also a good solution because colors are easy to change/update via the admin configuration page.


"Missing required paramter" with all Social Auth providers

I've found the reason for the problem: outgoing proxy. The web server where I have my website installed doesn't have direct internet access, but it uses an outgoing proxy.

Regarding social_auth_twitter - it was my mistake - outgoing proxy was blocking access to api.twitter.com. After configuring the proxy to allow this traffic - Twitter authentication started working as expected.

But regarding the other two (social_auth_google and social_auth_linkedin) - no requests ever reached the proxy, meaning that these modules don't know how to use the proxy.

I've ensured that the proxy is configured correctly:

Environment variables http_proxy, https_proxy, no_proxy, HTTP_PROXY, HTTPS_PROXY, NO_PROXY are configured as needed;
In VirtualHost element (Apache configuration) I'm ensuring that these environment variables are available by setting the appropriate PassEnv lines (mod_env module);
settings.php file contains the appropriate $settings['http_client_config']['proxy']['http'] (and other) configuration.

At the end of the day - everything else (installing and updating modules, etc.) is working normally through the proxy, so proxy configuration isn't the problem.

It looks that, at least for now, you cannot have social_auth_google and social_auth_linkedin if your web server is behind a proxy. Another very disappointing fact is that there are no any logs in /admin/reports/dblog, so you cannot know that modules are struggling to access their corresponding API endpoints. Hopefully it'll be resolved in future versions. For now you simply have to allow direct access, and remove outgoing proxy completely.


How to use Drupal Captcha in Custom form?

From looking at the code in the Captcha module, it looks like Captcha defines a new form element.

So an example would look like:

$form['name'] = array(
  '#type' => 'textfield',
  '#title' => t('Name'),
);
$form['captcha'] = array(
  '#type' => 'captcha',
  '#captcha_type' => 'captcha/Math',
);

Where captcha/Math is the module that provides a type of captcha, followed by the type of captcha to use.


How do i force a text format and hide the format selector in a formatted text field?

Install the module Allowed Formats and configure the field to allow only one text format. Then the text format selector dropdown will no longer be displayed.


Add/Edit Taxonomy Terms directly from add content form

Take a look to the Hierarchical Select module.

  This module defines the "hierarchical_select" form element, which is a greatly enhanced way for letting the user select items in a hierarchy.


You should be able to include the Paragraph entity class, and use Paragraph::load($entity_id) to load it.

Example:

use Drupal\paragraphs\Entity\Paragraph;

$paragraph = Paragraph::load($target_id);
$foo = $paragraph->field_name->value;


All custom fields are missing in views 'add field' and 'add filter' forms (Drupal 7)

To add to james-geldart's answer, I solved this same problem permanently (or for a few hours so far at least) by deleting every row of the table cache_views in the site's database.


Why doesn't the overlay background show?

The problem has been resolved: The 'Overlay helper' was disabled.


Content Type with Tabular Data to be Input

did you try to use field_collection? (separate the E.Coli in 2 fields EColiB and EColiE ... and maybe some CSS to style it) - perhaps this is not a solution, I am posting it here since I am couple of points short and cannot leave comments for additional info under the original post


I had an issue similar to this. The update to Drupal core caused issues with content types using the References Dialog module. We noticed that altering any nodes with a type using these reference dialog fields had issues. What tipped me off was that the other content types didn't have an issue. Odds are that this error is being caused by another module. Here are a couple things you can try in a development environment:

Create a new content type with core fields (a title, body, and maybe an image field will work). Do you get the same problem?
Verify whether or not all of your content types are affected. I know you said you can't alter any content, but you can save yourself time by being absolutely sure. Choose a few nodes for each type and try editing them to see if you get any other issues. If you see that there are only some content types affected, you can find out what fields / widgets they're using and start to deduct which one is causing the problem.

Good luck!


menu_navigation_links() generate a error

Are you using the navigation menu as the secondary menu for the site?

The cause could be a bug in drupal core. See http://drupal.org/node/1018614

There is a patch in #83, which I think is for drupal 8 but the fix should be the same for drupal 7.


How can I get a field value of a node using PHP?

The easiest non Entity API way of doing it is to use field_get_items():

// Assuming you have the node object and assuming it is a single value
// field or you just want the first value of a multi value field.
$username_value = '';
if ($items = field_get_items('node', $node, 'field_user_name')) {
  $username_value = $items[0]['value'];
}


WSOD while trying to install Drupal Commerce Kickstarter

According to Commerce's docs http://www.drupalcommerce.org/commerce-kickstart-2/troubleshooting-kickstart-2-installation

RAM: minimum 128M, more is recommended because your server can fail with this memory if it is at all strained

Since the Commerce Kickstart 2 distribution can install an entire setup and configured working demo, the installation process requires a bit more sustained power. In our early beta tests, installations can sometimes silently fail when it uses close to your memory limit.

So, the answer is, "Scotty, we need more power!"


Can you have multiple groupings on a view?

Create multiple view pages in a single View definition and assign each with the same basic paths, but a different last segment eg. Node/%/Group1 & Node/%/Group2.
For each view select a menu item in the second column and set the type to menu tab.  Provide the name to display on each tab.
Set one of the pages' menu to default menu tab so it will show up first.  set its parent to already exists.

When you enter the path in the URL, you should get the default page displayed with the menu tabs above the view block.


Make the git repo part of the drupal site so I can commit my changes whilst testing

I found that if I cd into the profiles folder on the Drupal site that has been installed as above, and then commit changes, and push them to git, it also works as if I was committing them from the folder on the desktop which I initially ran the git init on. I read something that said that Drush automatically knows that you are in the directory of a Drupal install, so perhaps this is the resolution.


Why does my kernel test error with "Install profile will be a mandatory parameter in Drupal 9.0."?

Your problem is that your test and/or code is relying on a deprecated feature.

In Drupal 8.3, there was a push to have deprecated featured generate E_USER_DEPRECATED messages, eg in Drupal\Core\Config\ExtensionInstallStorage:

  public function __construct(StorageInterface $config_storage, $directory = self::CONFIG_INSTALL_DIRECTORY, $collection = StorageInterface::DEFAULT_COLLECTION, $include_profile = TRUE, $profile = NULL) {
    parent::__construct($directory, $collection);
    $this->configStorage = $config_storage;
    $this->includeProfile = $include_profile;
    if (is_null($profile)) {
      @trigger_error('Install profile will be a mandatory parameter in Drupal 9.0.', E_USER_DEPRECATED);
    }
    $this->installProfile = $profile ?: \Drupal::installProfile();
  }

This is to provide early warning to developers to update their code.

If the code is hit in a phpunit test (which includes unit tests, kernel tests, and functional tests using BrowserTestBase), anything from trigger_error will generate a fail.

So, you either need to fix your code, or you can cause the test to not fail by using the @expectedDeprecation annotation on the test method until you can fix it.


This notice is a known issue. You can solve it by implementing one of these patches:
https://www.drupal.org/node/1535942
or
https://www.drupal.org/node/2196065

If you do not know how to apply a patch, follow these instructions:
https://www.drupal.org/patch/apply


If you click on More link under the contextual filter settings, there is an option to allow multiple values.

Enabling this option, you can use URLs like /upcoming-events/happy-hours,drupal to show events having both happy-hours and drupal tags.


How to use inline_entity_form in Drupal 8?

In order to implement Inline Entity form in D8, all you need to do is set your entity reference field to use the IEF widget - simple or complex. That is all. No additional work.

Here is how we set it up in Drupal Commerce for products, programmatically.

$form_display = commerce_get_entity_display('commerce_product', $product_type->id(), 'form');
$form_display->setComponent('variations', [
  'type' => 'inline_entity_form_complex',
  'weight' => 10,
  'settings' => [
    'override_labels' => TRUE,
    'label_singular' => 'variation',
    'label_plural' => 'variations',
  ],
]);
$form_display->save();

This tells the variations field, which is a Product Variation entity reference, to use IEF as the way to manage field values.


Display an image for the first item in a Views news list

Views nodes split does exactly this:

  This module allows site administrators or builders to have a different
  view mode for the first nodes of a view result.

Source: Lullabot - Module Monday: Views Nodes Split


just type :
    drush field-create announcement img,image,image_image

the last two are field_type,widget_name


By considering that you have gone through pre-installation checklist of Commerce Kickstart, following are the steps to install commerce kickstart :

Download Commerce Kickstart.
Extract the Files into root directory.
Installation Screen, welcome.
Requirements Problem Screen.
Setting up the database configuration.
Installation running through.
Site Configuration.
Configure Store Content.
Importing Products.


Passing variables to a theme from a custom module

The correct code is the following one.

Theme call

theme('my_widget', array('node' => $node));

Theme declaration

function my_module_theme() {
  return array(
    'my_widget' => array(
      'template' => 'my_widget',
      // This array contains the default values.
      // You should not use a PHP variable.
      'variables' => array('node' => NULL),
    ),
  );
}


Page body content updated only after second load

Check http://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook_node_view/7

You should clear cache programmatically if you want to use current solution or just load node again (http://api.drupal.org/api/drupal/modules!node!node.module/function/node_load/7) after save.

Third argument of node_load must be true


How do I render the search form for a particular Apache SOLR search page on its own?

Well I'm not sure what the problem was, but after a bit of further digging into apachesolr_search I've come up with a work around which seems to do the trick:

$search_page = apachesolr_search_page_load('PAGE_ID');

module_load_include('inc', 'apachesolr_search', 'apachesolr_search.pages');
$build['search_form'] = drupal_get_form('apachesolr_search_custom_page_search_form', $search_page);

As kiamlaluno has noted in the comments it doesn't look like it's actually apachesolr_saerch causing this behaviour, but rather the core search module doing...something.

Hopefully this code will save someone the time in the future.


Overriding "/user" page with Feature (Drupal 7)

Features is the way to move configuration data between different environments, or at least the most typical. But in your case you need to move functionality, not simple configuration (as what you want to achieve can't be done just modifying configuration).

Features takes some Drupal objects as Views, permissions, roles, content types, panels and so on an put them into code that can be later imported to another Drupal instance. This is considered configuration because even when  this kind of objects add functionality to the site you have added it configuring some modules.

So, if you can manage to achieve your desired functionality (I suppose using Panels and others modules) you may export that configuration using Features. And I say may because not all configuration can be exported this way (most yes).

In your case probably you'll need a custom module that menu_alters the /user URL and uses a custom page callback that adds what you need. But what you need is too broad to explain in an answer here.


How can I access the node ID when writing PHP into a block?

You can use the menu_get_object() function which will get you the node object for the page, assuming of course your block is being displayed on a node page:

$node = menu_get_object();

if (isset($node->nid)) {
  $nid = $node->nid;
  echo my_custom_function($nid, $my_desired_class);
}


How do I get Drupal to 'discover' a new layout .tpl?

I assume this is a Panels layout and Drupal won't discover it. You have to manually add it to the theme's .info file like this:

plugins[panels][layouts] = your_new_layout_name


Quicktabs + Webforms. You can have multiple pages (nodes) or blocks and using the quicktabs module would allows you to have the different insert those pages or blocks into tabs. To created the field form you can used the Webform module and inserted into quick tabs module.


adding new validation method using HookEventDispatcherInterface::FORM_ALTER event

You can do it that way too:
in Oriented object way don't call the method like 'my_api_authentication' it should be [$this, 'myApiAuthentication'] and also the method should be Camel Cases, try with the following:

class MyFormEventsSubscriber implements EventSubscriberInterface {

  public static function getSubscribedEvents() {
    return [HookEventDispatcherInterface::FORM_ALTER => 'alterForm'];
  }

  public function alterForm(FormAlterEvent $event) {
    if ($event->getFormId() == 'user_login_form') {
      $form = &$event->getForm();
      $form['#validate'][] = [$this, 'myApiAuthentication'];
    }
  }
  function myApiAuthentication(&$form, FormStateInterface $form_state) {
    // Your code validation here.
  }

}


How to embed view in basic page content?

You might want to have a look at Paragraphs and some of the new Views Reference fields. You could then intersperse Views and content.

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

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


Fast way to make all menu-links "Show as expanded"?

Try using menu block and create block what level you want to trail you menu. You can also use menu expanded as per your requirement. Menu expanded is not well maintained.


This can be done through contextual filters in views.

Navigate to edit the structure of your view, click advanced and add a contextual filter. Here you will select the date field and "Apply"

On the next page, under "WHEN THE FILTER VALUE IS NOT IN THE URL" you want to "Provide default value" of type "PHP Code". The code you want to use is fairly simple, but depends on your date/time setup. you should have something like this in the php code field:

return date("Y/m/d");

Good Luck!


How to create an Atom RSS feed with site's content type?

You can use Views + Views Atom to create XML feeds.


Sum up views custom text field using aggregation

Yes short Answer have a look at creating a custom twig extension:

the idea would be to pass the details required  as an "exclude from display" field (or fields) to the custom global text field. Note excluded from display fields can be accessed in the "REPLACEMENT PATTERNS" section under view text.

then basically in the text field
you would do something like:

{myCustomTwigFunctionToCalculate( add_REPLACEMENT_fields_here)}
// or example ...
{myCustomTwigFunctionToCalculate( entity_id, nid, uid)}

  namespace Drupal\YOURMODULE\Twig;

  class CustomTwigToCalculateTwigExtension extends \Twig_Extension {

  /**
   * {@inheritdoc}
   */
  public function getName() {
    return 'myCustomTwigFunctionToCalculate';
  }

  /**
   * {@inheritdoc}
   */
 public function getFunctions() {
    return [
      new \Twig_SimpleFunction('myCustomTwigFunctionToCalculate', [$this,
      'myCustomTwigFunctionToCalculate'], [
      'is_safe' => ['html'],
    ]),
  ];
 }

 public function myCustomTwigFunctionToCalculated($param1 , $param2 ) : string {
 // Do the stuff you need to to calculate prams you pass.

  $output = '';
  $output = $param1 + $param2 + 42;
  return (string) $output;
 }

}

you will also need a service file ... see below examples.

Links to custom twig extension for Drupal 8:

https://www.openaccess.fr/la-veille-du-web/create-twig-extension-drupal-8

https://medium.com/@thihathit/extending-custom-twig-extension-to-drupal-8-twig-extension-class-d4b99c2177ae

https://www.youtube.com/watch?v=9PeAfExNSDk


How to create an "All" link in a taxonomy menu (block)?

My opinion:

You can create a new term called all and add it to all your related nodes.

Or,
You may use Views to create a page to show all nodes, and add that to your menu.


Custom blocks created as a plugin in a module not showing for Block::load()

Block::load() loads a configured block, that means a block that is placed in the block layout. It does not load plugins.

The name of the configured block is displayed in the block layout as Machine name.

You can place the block in the Disabled section, if you only want to configure the block, but don't want to show the block in a region.