I have found preceding value array with [x-default] shows the values.
I presume this has to do with the translation module

function remittance_providers_node_load(array &$entities) {
  //loop thorough the loaded entities
  foreach ($entities as $key => $entity) {
    // if provider node type is being loaded add our data on top of it.
    if ($entity->bundle() == 'providers') {
      $nid = $entity->id();
      $commission_data = currencyStorage::loadCommission(array("companyID"=>$nid));
      if(count($commission_data)>0){
        foreach ($commission_data as $ckey => $comm) {
          $entities[$key]->commission['x-default'][$ckey]['amount_from'] = $comm->amount_from;
          $entities[$key]->commission['x-default'][$ckey]['amount_to'] = $comm->amount_to;
          $entities[$key]->commission['x-default'][$ckey]['commission'] = $comm->commission;
        }
      }
    }
  }
}


add "items_per_page" number in title tag and meta tag

I got a solution. Just add the following code in template.php file.

function yourtheme_preprocess_html(&$vars){
    // add pager number to title.
    parse_str($_SERVER['QUERY_STRING']);
    if(isset($items_per_page)){
        $vars['head_title'] .= $items_per_page;
    }
}


How to render a media entity image (that uses a focal point image style) inside a paragraph twig file?

You'll run into troubles with this technique, because Media images are entities on their own, and have their own cache settings. So if you change the image style on paragraph level, the embedded media image will not know anything of this and instead returns the first, cached size.

Instead create multiple display view modes for your media entities, and let your editors choose the view mode on paragraph level. Below is the code I'm using in my own projects

function wtfrontend_base_preprocess_paragraph__image(array &$variables) {
  $paragraph = $variables['paragraph'];

  if ($paragraph->hasField('field_image_viewmode_image')) {
    $imageViewMode =  $paragraph->field_image_viewmode_image->value;
    if (isset($variables['content']['field_image']['0']['#view_mode'])) {
      $variables['content']['field_image']['0']['#view_mode'] = $imageViewMode;
      unset($variables['content']['field_image']['0']['#cache']['keys']);
    }
  }
}

Render the image normally with {{ content.field_image }}


Can't login using OpenId (core) and Google profile

The following works for me in Drupal 7:

https://www.google.com/accounts/o8/id

For more information, see Whats My Google OpenID URL?.


Redirect form out of modal window after submit

I would suggest using #ajax to submit the form and then allow the response to close the modal and go somewhere else. For example, here's a submit button that runs a function on click instead of submitting the form and reloading the page:

$form['submit'] = array(
  '#prefix' => '

',
  '#type' => 'button',
  '#value' => 'Submit',
  '#ajax' => array(
    'callback' => 'my_super_cool_ajax_callback',
    'wrapper' => 'super-cool-wrapper',
    'method' => 'replace',
  ),
);

And then in your callback function:

function my_super_cool_ajax_callback($form, $form_state) {
  // Do what you normally would with the form submission.
  return '';
}

Now you can process the form as needed and return a response that simply redirects the user.


hook_simplenews_scheduler_edition_node_alter does not work as expected

function hook_simplenews_scheduler_edition_node_alter(&$edition_node, $scheduler_node) {

    $my_arg = '-1day';
    $edition_node->body['und'][0]['value'] = views_embed_view('tracker03', 'page', $my_arg);
    return $edition_node;

}

This does the trick.


I did this way to create my own "edit user profile" for profiles of profile2 module.

function customtheme_theme() {
    $items = array();
    $items['user_profile_form'] = array(
        'render element' => 'form',
        'path' => drupal_get_path('theme', 'customtheme') . '/templates',
        'template' => 'user-profile-form',
        'preprocess functions' => array(
             'customtheme_preprocess_user_profile_form'
        ),
    );
    return $items;
}

I put customtheme_theme() function into my template.php file of customtheme theme. (a custom theme that i used for my website)
After that i created the template file user-profile-form.tpl.php and placed in the templates folder of my theme.
The customtheme_preprocess_user_profile_form function you can use that for changing some variables before render the profile form or if you dont need any changes you can remove the preprocess_functions.
After add the customtheme_theme(), create user-profile-form.tpl.php template. You have to clear cache and you can see the layout change for user-profile-form.


Date Time field machine name/view mode for theming using paragraphs

The best way to Debug this is to enable twig debug
open up or create sites/default/services.yml

change

 http.response.debug_cacheability_headers: true
 twig.config:
   auto_reload: true
   cache: true
   debug: true

once done run drush cr or clear your cache

then go to the page with the paragraphs on them and inspect the element in chrome
you will see ...
some thing like

<!-- FILE NAME SUGGESTIONS:
  * field--paragraph--field-range--event.html.twig
  * field--paragraph--field-range.html.twig
  * field--paragraph--event.html.twig
  * field--field-range.html.twig
  * field--daterange.html.twig
  x field.html.twig
  -->

then theme the new field templates to your liking


Install and enable domain module
Enable the submodule named Domain Configuration
Add a subdomain abc.example.com by clicking Create domain
Go to admin/structure/domain/ and click on edit domain for abc.example.com
click the Settings tab
Set the value of the Site frontpage field to abc


Associating a user with a particular form submit/click

For node you should load challenges data in your custom module, using next: hook_node_load and/or showing next: hook_node_view. See examples module for it: nodeapi_example.
For Views you should define connection with your custom table and node, there nice example for it.
For Views also you can use Data module.


How do I pass the value of a PHP variable?

In Drupal 8 drupal_add_css(), drupal_add_js() and drupal_add_library() have been removed, and we are supposed to use #attached.

$page['#attached']['library'][] = 'fluffiness/cuddly-slider';
$page['#attached']['drupalSettings']['fluffiness']['cuddlySlider']['foo'] = 'bar';

More details about how JavaScript can be added in Drupal 8 can be found in https://www.drupal.org/theme-guide/8/assets#configurable-javascript.


Total number of likes on views images and social networking?

To count how many times users have liked a particular node maybe checkout the Like Button module.


Views - Protect user-assigned content from direct url access

Have a look at the Group module which allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also.

The Group module creates groups as entities, making them fully fieldable, extensible and exportable. Which also makes it integrate very well (out of the box) with commonly used modules such as Rules, Views, etc.

For more details about the various roles and permissions, refer to my answer to "What are the various roles supported by the Group module?".

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".


500 Internal server error is normally at Server level. To fix this, you'll first need to check is the actual error which you can check either Drupal Logs (located at "Admin => Reports => Recent Log message") or Apache error log (located at "/var/log" in Linux OS).


Post method not working on non-CRUD methods

After debugging the action method of user/login (default in services module), I found where I went wrong. In my code, I added extra array called check inside username. When I remove that array everything is going well. Here the updated code

function my_module_service_services_resources() {
    return array(
      'test' => array(
         'actions' => array(
            'username' => array(
              'help' => 'Checks username for uniqueness',
              'callback' => 'test_module_username_check',
              'access callback' => 'my_module_service_access',
              'access arguments' => array('view'),
              'access arguments append' => TRUE,
              'args' => array(
                array(
                  'name' => 'username',
                  'type' => 'string',
                  'description' => 'The username to check',
                  'source' => 'data',
                  'optional' => FALSE,
                ),
              ),
            ),
          ),
       ),
    );
  }

  function test_module_username_check($username) {
    return $username;
  }

  function my_module_service_access() {
    return true;
  }


how to print a form in twig where a variable number of form elements have been printed already?

If you look at form.html.twig in the Drupal Core's system module, you'll see:
{#
/**
 * @file
 * Default theme implementation for a 'form' element.
 *
 * Available variables
 * - attributes: A list of HTML attributes for the wrapper element.
 * - children: The child elements of the form.
 *
 * @see template_preprocess_form()
 *
 * @ingroup themeable
 */
#}
<form{{ attributes }}>
  {{ children }}
</form>

Using this as a guide, you should be able to do:
<form{{ attributes }}>
  {% for item in form|children %}
    {{ item }}
  {% endfor %}
</form>

children is already a variable in the template so you can just use it like:
<form{{ attributes }}>
  {% for item in children %}
    {{ item }}
  {% endfor %}
</form>

But if you're not wrapping the individual children, why even use a custom template? Why not just use the default form.html.twig.


How can I export only one paragraph type, the fields, the form settings and the display settings?

That's exactly what the Features module is for. Syncing partial config across multi-site instances.

The features module enables the capture and management of features in
Drupal. A feature is a collection of Drupal entities which taken
together satisfy a certain use-case.
Features provides a UI and API for taking different site building
components from modules with exportables and bundling them together in
a single feature module. A feature module is like any other Drupal
module except that it contains additional information in its info file
so that configuration can be checked, updated, or reverted
programmatically.

That means you would create a feature on your main multi-site instance which contains the paragraph type. Have it placed inside the modules/features/ folder. Related config will be added automatically. You then enable the feature (which basically is just another module) in another multi-site instance. The config will be imported into the database. On both multi-site instances you then export config as usual. Because every multi-site instance still is managed from its own config. Which then also contains the synced paragraphs config.
As soon as you add another field to the paragraph type on either multi-site instance Features will recognise the changes. You then can recreate your paragraph feature and import the changes on another multi-site instance (into the database). Finally, on both sites again export config as usual (which then also contains the paragraph types you've synced via Features). Features enables you to keep track of changes to a feature via built-in diffing, which after you recreated the feature (partial config gets exported) can be synced into the database on other multi-site instances again.
Of course Features also comes with a set of Drush commands to make your live easier.


Drush on Macbook Pro cannot read Dupal Correctly NOW RESOLVED!

RESOLVED. 9/22/2014

I began to discover that the previous method of attempting to change the 'alias' or otherwise redirecting Drush to use MAMP's PHP was the wrong way to go. Especially 'name-distorting' the original MacBook-OS-PHP so that Drush would opt for the MAMP-PHP was causing all kinds of problems with other software, as might be expected. I don't know how this method came to be recommended, but it appears that it is actually a pit-fall.

The way better approach (watch me eat my words in a few weeks), is to rather just upgrade the MacBook-OS-PHP to the same or nearly same version as the MAMP-PHP. Then it does not matter which version of PHP Drush or anything else uses because they are both the same. This overcomes all the issues and is not that difficult to accomplish. At least on my platform which is a MacBook-Pro (2008-Mavericks).

The way that I upgraded my MacBook-OS-PHP was by the CLI-command "curl -s http://php-osx.liip.ch/install.sh | bash -s 5.5".

This is a download from a group of developers in Germany which upgrades your PHP. Check out "http://php-osx.liip.ch/".

Once my System-PHP and MAMP-PHP were almost the same, all my issues with Drush went away. I undid all my 'aliases', 'redirects' and 'name-distortions'. So far all is working well.

Note that on my machine MAMP is using PHP-5.5.14 and my CLI reports with a "php -v" command that MacBook-OS is using PHP-5.4.30 though I am not sure that the version is accurate. In the write up on the PHP-Upgrade it mentions that the version might not be accurate.

By the way this does not OVERWRITE your previous PHP installation but rather just adds a newer installation and directs your system to use it.

I will update if there later prove to be drawbacks in this approach.


d7: to be inserted ID, is there a cleaner way?

I don't think there's a 100% reliable way to get the ID that will be used next. Even the method you've got won't work completely. Take this example:

Insert a node into the database (it has the new nid of 1 for arguments sake)
Insert another node into the database (it has the new nid of 2)
Then delete that second node
Add a new node to the database again. This time it will have a nid of 3, not 2 (as would be expected from your code).

The problem is that the MySQL AUTO_INCREMENT value exists completely independently of the primary key ids that are currently in the database; so unless you reset the auto increment counter each time there's no way to reliably determine the next id.

Also in a system with multiple simultaneous accessess to the database using code like that introduces potential race conditions.

It would be far simpler to perform this task when the node has been saved, perhaps in hook_node_save().

Oh and one other little thing, the vid you're inserting should not be 1, it'll be determined for you by the system. Using 1 for every node will link every single node to one revision in the node_revision table...probably not what you're looking for.


Show content whose "team" field matches the user "team" field

The easiest way to set this up is through the Content: Has taxonomy term ID Contextual filter.

In Content Views listing your nodes add that Contextual filter and set it up:
When the filter value is NOT available
Provide default value
Taxonomy term ID from URL
Load default filter from node page, that's good for related taxonomy blocks
Filter to items that share any term
When the filter value IS available or a default is provided
Specify validation criteria
Taxonomy term
[your vocabulary]
Term ID
Adjust the other option as necessary.
Now if you enter some taxonomy term ID into the Views Preview field, it will be picked up by the Contextual filter and show only nodes that have been tagged with that term.

Create a block Display and place your block in a region shown on entities that have the taxonomy term ID chosen. The block will show all nodes that share the term.

In your case if you place that block on User Profile pages, it will show the nodes related through the same Taxonomy term.

If you want to show that Block anywhere on the site, and have it take the Context of the currently logged in user you have to approach it a bit differently.
There may be more ways on how to achieve this, here's one:

In the original Views where you show a list of nodes add a Relationship for the Taxonomy term field (Field: Team).
Then add another Relationship that is reverse, going from Taxonomy term to the field on Users (Taxonomy term: User using …). This is where the term matching is done, the second Relationship will use the first one. This introduces the User info into your content Views.
Then add the Contextual filter for User ID (User Uid), it will use the second Relationship. Set up the Contextual to use the logged in user context:
When the filter value is NOT available
Provide default value
User ID from logged in user
When the filter value IS available or a default is provided
Specify validation criteria
User ID
Single ID
Place the Block anywhere on the site and it will only show nodes related to the user that is currently logged in, even if you place it on user profiles and view other users profiles!


Put the access callback function in a separated file

The access callback has to be in the same file; the file passed in the "file" property gets loaded only if the access callback returns TRUE. The only other "solution" is to use an include at the top of your module.


how to discover where mini-panels are surfaced in Drupal 7

Assuming your site is using Drupal 7 version.

Mini-panels gives us a way to group together multiple blocks (and other content) into a single block. Which can then be placed on page using Panels or Drupal Blocks (Admin => Structure => Blocks). Check this Question Looking for a good Mini - Panels tutorial for more details.

There are 3 places you can check if Mini Panels are actually used in your site:

Drupal Blocks (Admin => Structure => Blocks) - Block name is usually shown as 'Mini panel: "Mini Panel Name"'
Panel Pages (Admin => Structure => Pages). Check all panel pages by editing them and navigating to Content section of Panel page.
Rendered in Code directly (Since this works similar to block, and can be rendered using the way blocks are rendered programatically). i.e. programatically rendered in theme or module. This might not be in your case, but just to make sure you can check this as well.

This Tutorial shows use of Mini Panels as Drupal Block.

Check out this tutorial on How to use Mini-Panels to create one block that includes all our global blocks - The video is paid, but description gives an overview of what it is.


Strange behavior of block display mode of views when the pager displays a specified number of items

Try using unique pager IDs for each block display here:


How to migrate Webform data from Drupal 6 to Drupal 7?

You can migrate Drupal 6 webform data to 7 using the Mirgrate Webform module.

  It will migrate all nodes of the webform node type (with the default D6 fields using migrate_d2d backend), all the configuration* of the webform's settings, the form components, email destinations, submissions and associated submission data, in addition to any validation configuration you have (from webform_validation module). It grabs the "last downloaded" data too, in case your users were downloading sequential batches since the last time they were on the site.


Panel Content not displaying correctly after migrating site to new server

When you're browser builds the admin page, it makes multiple requests over HTTP to the server to fetch resources, such as css files. If you look over that list, using whatever debugging tools your browser provides, you might be able to find out which file Panels is expecting to be there, but your browser fails to find.


How do I delete an orphaned paragraph node?

In Drupal 8, you can still use entity_delete_multiple(), but it is marked as deprecated and it is going to be removed from Drupal 9.

It makes easy to remove those entities using Drush, for example, with the following code.

drush php-eval 'entity_delete_multiple("paragraph", [$id]);'

Even using code that works on Drupal 9, you would delete those entities in a single command line.

drush php-eval '$storage_handler = \Drupal::entityTypeManager()->getStorage($entity_type); $entities = $storage_handler->loadMultiple([$id]); $storage_handler->delete($entities);'

Replace $id with the ID of the entity you are going to delete. You can also delete multiple entities at once replacing [$id] with an array of IDs.


Unexpected session reset when making authenticated user REST requests

Well. I found what was causing the error (unexpected behavior) reported above. There are chances that others might get stuck in a similar fashion, so I am answering my own question -

The above resetting of Session was taking place because my service end point was not configured to work with 'authenticated sessions'. When creating a new service endpoint there is an optional checkbox labeled Session authentication with description Choose which authentication schemes that should be used with your endpoint. If no authentication method is selected all requests will be done by an anonymous user. which one needs to check so that web service resources created under that end point and allow authenticated sessions.

If you fail to check this checkbox at the time of creating the endpoint, you could do so later too, by editing the particular endpoint and clicking on the EDIT tab.


Simple Oauth oauth/debug?_format=json Internal Server error

I fixed this issue by going to admin/people/permissions and selecting all of the Simple OAuth permissions for Authenticated User. I'm sure a more refined approach to selecting permissions will be possible, but initially selecting all of them has fixed this issue for me.


How to select a shipping box for a particular product based on quantity using Drupal Commerce?

Using the Commerce Box module, for which only a DEV version exists, you can create Commerce Box entities, but that's about it. E.g. it does not add any specific Rules Actions you can use to select the appropriate shipping box, such as based on product items and/or quantities.

However, there is an inspiring issue for the Commerce Fedex module, titled "Allow altering of default package dimensions". And comment nr 17 of that issue contains an interesting patch which allows for package dimensions alterations.


How to I add translations for Month and Day in a date field?

You can translate everything in Administration » Configuration » Regional and language » Translate interface (admin/config/regional/translate/translate)

Concerning dates, you usually need to translate the following strings :

!month-name |January|February|March|April|May|June|July|August|September|October|November|December : you must keep !month-name and | in the translated string
every string starting by !long-month-name
!day-name Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday

And you should be good.

Even better, if you know several people interested in maintaining a language translation, you should go to https://www.drupal.org/node/807756 and reopen the issue. The goal is to have one place to improve and maintain the translation in https://localize.drupal.org/


The ldap config page for users and fields has a user_dn entry you can set.


Preprocessing a front page block causes errors on other pages: why?

Try:

<?php
if (isset($variables['view']->result[0]->_field_data)) {
//
?>

Instead of your weird if/else construct. Not really sure what you are trying to accomplish with that code, so there might be a better way to check if you want to execute it or not.


How can I set a Feeds Importer to accept multiple values for a field?

Have a look at feeds tamper.

Using the pipe symbol is alright. The next step would be to enable Feeds Tamper and chose to "Explode" the "Files" with the pipe character as separator.


How to place multiple form elements from a loop

You could try this if I understand correctly:

$header = '
';
$header .= '
Something...
';

$form['header'] = array(
  '#markup' => $header;
)

$i = 1;

foreach($somethingAwesome as $val){

    $form['blah_' . $i] = array(
        '#type' => 'textfield';
        '#prefix' => '
'
        '#suffix' => '
'
    );

$i++;
}

$footer = '
Something else...
';
$footer .= '
';

$form['footer'] = array(
    '#markup' => $footer,
);

This should give you the output:

Something...

TEXTFIELD
TEXTFIELD
TEXTFIELD

Something else...

You'll need to do something to differentiate each $form['blah'] part too, otherwise you'll be running a foreach loop that overwrites that specific part of your form on every iteration.

You're running your foreach loop in the place where you want it, but all of the data you want surrounding the form is being put into one variable, and then added in one go as a prefix.  Suffix will add data to the end.

General Reference (in case you didn't know):

FormAPI Reference

Specific References:

#prefix

#suffix


Custom entity, entity_save() leads to PDO Exception?

The problem is centred around this bit of code:

$e = entity_create ('person', array(
  $entity->name = $message['params']['last_name'],
  $entity->field_person_copy['und'][0]['value'] = 'NO',
));

It's sort-of-technically-valid PHP (though you don't have a variable named $entity in scope), but certainly isn't doing what you expect. It's almost like you're trying to apply a feature from another language (like object initialisers from C# maybe).

I'm guessing somewhat, but I imagine what you're trying to do is:

$e = entity_create ('person', array(
  'BUNDLE_KEY' => 'BUNDLE_NAME',
  'name' => $message['params']['last_name'],
));

$e->field_person_copy[LANGUAGE_NONE][0]['value'] = 'NO';

entity_save('person', $e);

Or maybe

$e = entity_create ('person', array(
  'BUNDLE_KEY' => 'BUNDLE_NAME',
));

$e->name = $message['params']['last_name'];
$e->field_person_copy[LANGUAGE_NONE][0]['value'] = 'NO';

entity_save('person', $e);

Where BUNDLE_KEY and BUNDLE_NAME are whatever you have set up for your entity type.


Exist a Drush command to update all the contents?

You can take a look inside the module Drush Entity because in this module you have the command entity-update:

drush @drupal.d7 entity-update node 53 --fields=title

If you want to improve the command to work in all nodes you can read this post:

How to adapt the name of a custom Drush command?

EDIT:

If you want to learn about Drush alias (@drupal.d7) you can go to: Drush Aliases: What, Why and How


You can not access directly to #fieldgroups in form_alter you should add pre_render function like the following:

function mymodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == 'YOUR_FORM_ID') {
    $form['#pre_render'][] = 'mymodule_form_pre_render';
  }
}

/**
 * @param $form
 *
 * @return mixed
 */
function mymodule_form_pre_render($form) {
  foreach ($form['#fieldgroups']['group_employment']->children as $form_element_id) {
    $form[$form_element_id]['#access'] = FALSE;
  }
  return $form;
}

Edit :
if you want to just disable the fields change the pre_render function by:

function mymodule_form_pre_render($form) {
  foreach ($form['#fieldgroups']['group_employment']->children as $form_element_id) {
    if (isset($form[$form_element_id])) {
      //- For entity reference fields
      if (isset($form[$form_element_id]['widget'][0]['target_id'])) {
        $form[$form_element_id]['widget'][0]['target_id']['#attributes']['disabled'] = 'disabled';
      }
      //- For normal input form
      if (isset($form[$form_element_id]['widget'][0]['value'])) {
        $form[$form_element_id]['widget'][0]['value']['#attributes']['disabled'] = 'disabled';
      }
    }
  }
  return $form;
}


Drupal cannot generate the derived image ANYMORE?

In your settings.php file add this

$conf['image_allow_insecure_derivatives'] = TRUE;

In the future you should use image_style_url() when using image styles as this will then add in itok parameter for images. Usage: image_style_url doesn't create images

More info about this: https://drupal.org/drupal-7.21-release-notes


Help needed getting out of the habit of using TWIG as my Controller and Template files

You are right, this kind of code should be in your controller or in preprocess functions.
You should generate a  render array for each twig template, to be able to have a simple :

{{ image_with_zoom }}

In your twig file. Your controller could have something like :

  $renderArray = [];
  /* @var $item \Drupal\node\Entity\Node */
  if($item->field_main_images->count()){
    $image = File::load($item->field_main_images->target_id);
    $renderArray['image_with_zoom'] = [
      '#theme' => 'image_style',
      '#style_name' => '...',
      '#uri' => $image->getFileUri(),
      '#attributes' => [
        'data-zoom-url' =>  ImageStyle::load('item_zoom')->buildUrl($image->getFileUri())
      ]
    ];
  }

Have also a look at field formatters, it allow you to get your own controls for each field you wish to display.
You can generate some skeleton with the drupal command :

$ drupal gpff

Have a look at documentation on this point, and the one in the drupal console. That's quiet important if you wish to reuse some display for a particular field as it looks like.


Views - offset when displaying all results?

I'm pretty sure that's the way it's designed.  If you set the number of things to be displayed to display all results or 0 (which is the same thing), it doesn't make sense to have an offset because you already ordered it to show every single result.

If you want to use an offset, set a specified number of results.  If you don't know what number to set, just pick an arbitrarily high number that you are unlikely to exceed.

EDIT: If you just want to hide the first item, is there some way to configure one of the filters so that the item is removed?  That is another possible approach.


Map or Edit Query String Values in Views?

You can use the hook_views_pre_view function in your custom module to change the query parameters using PHP, so a rough untested example of the code could look something like:

function MODULE_views_pre_view(&$view) {
  switch ($view->name) {
    case 'YOUR_VIEW_NAME': {
      // change your query strings to
      if ($_GET['value']) {
        $value = $_GET['value'];
        $new_value = substr($value, 0 , 6); // remove the 'value%' from Site A querystring
        $_GET['value'] = $new_value;
      }
      break;
    }
  }
}


How can I replace a node reference field with a node edit form?

You can achieve this by Installing Entity Reference and Inline Entity Form


Change role of indirectly referenced users with Rules

Finally I managed to solve this issue. The Conditional Rules modul is the key:

{ "rules_oktato_hozzaadas_oktato" : {
"LABEL" : "Oktat\u00f3 hozz\u00e1ad\u00e1sa - oktat\u00f3",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"TAGS" : [ "Oktat\u00f3" ],
"REQUIRES" : [ "rules_conditional", "rules" ],
"ON" : { "node_update--course" : { "bundle" : "course" } },
"DO" : [
  { "LOOP" : {
      "USING" : { "list" : [ "node:field-teacher" ] },
      "ITEM" : { "list_teacher" : "List of teachers" },
      "DO" : [
        { "CONDITIONAL" : [
            {
              "IF" : { "entity_has_field" : { "entity" : [ "list-teacher" ], "field" : "field_related-user" } },
              "DO" : [
                { "user_add_role" : {
                    "account" : [ "list-oktato:field-related-user" ],
                    "roles" : { "value" : { "13" : "13" } }
                  }
                }
              ]
            }
          ]
        }
      ]
    }
  }
]
 }
}


Deleting the files associated with my node is VERY slow

I edited the cloudfiles.php API from Rackspace to uncomment the following line:

define('RACKSPACE_SERVICENET', 1);

That automatically causes the API to connect over the private network which is a lot faster than accessing cloudfiles via the public network.

This is only usable if you are hosting your site on a Rackspace server though.


How to display a newly created node (created using a form) in the view using ajax (without page reload)?

As mentioned by wwwWRX you should use the #ajax property for your submit button and with in your function make a few changes. Before that you would want to remove your view from the block because we would be putting that here using code.

the submit button would become

$form['submit'] = array(
    '#id' => 'update-submit-button',
    '#type' => 'submit',
    '#default_value' => t('Share'),
    '#ajax' => array(
        'callback' => 'add_update_page_submit',
        'wrapper' => 'update-list',
        'method' => 'replace',
        'effect' => 'fade',
    ),
  );

Add one more element to your form of the type #markup like below

$form['update_list'] = array(
 '#prefix' => '
',
   '#suffix' => '
',
  '#markup' => views_embed_view('views-machine-name','block_name', $arg);

);

you should replace views-machine-name with the actual machine name of the view and block_name with the name of the specific block in the view and $arg would be the argument passed to the view which can be left blank if you dont have one.

with in the function you need to make a few changes towards the end.

you need to get rid of $form_state['redirect'] = '<front>';

and add

return views_embed_view('views-machine-name','block_name', $arg);

That should do it.


how do I add javascript to a specific panel-page

I'd probably do this in the theme with template_preprocess_panels_pane() - http://drupalcontrib.org/api/drupal/contributions!panels!panels.module/function/template_preprocess_panels_pane/7

You can do (make sure you have devel.module installed first)

MYTHEME_preprocess_panels_pane(&$vars) {
  dpm($vars);
}

and get a full print out of everything that's going on in all your panel panes.  With enough digging, you should be able to find a $vars['_something_']['#attached']['js'] = YOUR_FILE; to hook into.  I think you can do this in a module too, if that's what you want.

EDIT: After actually thinking about it though..

I would probably advise against this and just put it in your theme js.  Unless it's an enormous amount of js, you're going to be taking better advantage of Drupal's js aggregation by not doing this.  If you put the js in your theme, it'll be compiled into the main site js file automatically, whereas if you do something different when only this panel pane is showing, it'll require that an entirely different js file be aggregated and downloaded on pages when it shows.

Assuming this is a performance tweek, I think you might actually be headed in the wrong direction with this one, since browsers should cache this file after the first time it's downloaded.

edit: hook name typo


Do Drupal websites have bad performance or are heavy?

What's your hosts memory limit?

For MySQL Run this MySQL command

SHOW VARIABLES LIKE 'innodb_buffer_pool_size'

If it's at the default I would see if you can increase it to at least the same size as your database. If you can not, I would look at converting some of your tables to MyISAM.
http://www.mysqlperformanceblog.com/2007/11/03/choosing-innodb_buffer_pool_size/


Place custom content field only on sidebar

You can do this with the Panels module.  From the Page Manager configuration screen (Pages in the admin interface), enable the node edit page override.  Then edit this override.

Create a new variant.  Set the selection rule to be "content has type" -> "my custom content type".  Then, under Layout, choose an appropriate layout (one with a right sidebar).

Afterwards, under content, you will need to add all of the fields for the content type to be edited.  Just place My_field in the right sidebar and it will be displayed there.


Aegir 3.0, need to copy and paste website ssl config to ssl.conf in centos

If you don't have any apache config for the domain https://example.com then you land in the default vhost.

Add https://example.com as a site in Aegir and it will generate the config for you.


How to conditionally load JavaScript with template.php

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

CSS_injector does the same for css.


Specifying the length of an integer in hook_schema

Please see the Data Types documentation, I believe you can use tiny, small, medium, big, normal


Alter a form based on where it is called from

The following worked for me.

  if ($form_id == 'comment_node_CONTENT_TYPE_form') {
    $view = views_get_current_view();
    if ($view->current_display == 'block_1') {
      //Alter my form
    }
  }

I checked views_get_current_view function. Since it is using caching there is no harm in calling it again.


Show all terms that are children of term with argument tid

If you add a contextual filter for taxonomy term with depth modifier, it should work, e.g terms/1/1


Why is my block not showing up on the Blocks page?

Here is an example for hook_block_info found in examples module. This defines the existence of block and this will make the block show up in the block page. You could use hook_block_configure to provide additional fields for you block in block page and save the it using hook_block_save.

function example_block_info() {

  $blocks['example'] = array(
 'info' => t('Example: configurable text string'),
 'cache' => DRUPAL_CACHE_PER_ROLE,
 'status' => TRUE,
 'region' => 'sidebar_first',
 'visibility' => BLOCK_VISIBILITY_LISTED,
 'pages' => 'node/*',
 );

return $blocks;
}


Use http://drupal.org/project/node_noindex for noindexing concrete nodes. Or modify robots.txt for excluding count of nodes, Disallow: /node/, for example, next help for you: Robots.txt Tutorial.
Do you mean that clicking on whole column should lead to cats/dogs? If so, create custom template (in Views editing you should see in "Theme:Information" -> "Display output" -> take latest filename and copy source from link. Create this with filename and paste source. Wrap whole code into ....


Views Criteria Filter - Changes Affect Master Display

Yes, that's the default behaviour. But you can change it easily.

When you're editing the filters in your cloned display, look to the top of the dialog. You'll see a select list like this:

That select list determines whether the changes you're about to make are applied to the whole view, or just the display you're working on. If you choose "This xxx" (where xxx could be any number of things like page, etc), the changes you save will not apply to the other displays.


I would say that one relatively easy way without relying on any additional modules is to use the book module that comes with drupal core.

If you put the nodes in a book then you can use the book navigation's previous and next button.

You can override book-navigation.html.twig to remove elements of the book navigation that you don't need.


The only way I've found of resolving this is to replace the two
 tags with one using a str_replace in the field preprocess function. I've placed an example below.

function theme_preprocess_field(&$vars) {
  switch($vars['element']['#field_name']) {
    // When pressing Shift + Enter in WYSIWYG editor to create a new line it outputs two
 tags, not one.
    case "field_description":
      $vars["items"][0]["#markup"] = str_replace("

", "
", $vars["items"][0]["#markup"]);

      break;
  }
}


How to show Content Titles only in Entity Reference drop down list, but restrict general access to the Content Type?

OK, so the only way I found to do this was install the field_permisssions module and restrict access to all the custom fields for specific roles.

Not ideal, but achieves the objectives. There are a lot of fields and it took quite a while. Also need to remember to restrict fields when creating new ones.


How to programmatically modify an exposed filter?

Maybe you should make a hook_form_alter to build only one box.

And in the validation or submit give the box value to both form_state options.

Another options is to use hook_query_alter to build your own query.

Oskar


Drush cc all doesn't flush and rebuild templates?

I did not try to reproduce your exact situation, but some operations called by cache_clear_all write / remove files from the filesystem. If your filesystem permissions are not correct, then drush cc all will do all of the database clearing just fine, but will leave the other operations undone.

There are two potential solutions to this:

sudo -u www-data drush cc all

Some folks don't like to use 'sudo' with 'drush', but if you run Drush as the webserver user, the cache-clear should work.

set the permissions of your webserver files so that the user that you run Drush as can read/write to the filesystem.

I usually make my webserver files owned by a 'www-admin' user in production, and I make them owned by the user I log in as on my development system.  I set the group of all files to www-data, and make those that the webserver needs to write to group-writable.  This works pretty well for Drush + Drupal access on Drupal 7.


Webform allow embed form as block, so you can build 3 webforms, then show one in main content, and other 2 as blocks...


It is it difficult/time consuming to set up a Drupal site that users pay to subscribe to?

I've just finished writing a multi-tiered subscription system for an online business directory, using Commerce. Without going into too many details (the clients might be watching ;) it took a fair bit longer than a week to complete and sufficiently test the subscription/payment element of the system, and I'm pretty familiar with how payment processors and Drupal Commerce work under-the-hood.

FWIW I took most of my inspiration from the Commerce subscription products PayPal module, which:

  integrates the PayPal Recurring Billing functionality into the Commerce subscription product module.

It's a feature module so you can just chuck it into a site and see what it does (sets up a product type of 'subscription', adds fields to the user and order entities for tracking subscriptions, handles the recurring IPN notification from Paypal, etc.)

If you read through that module code you'll get a good idea of what's required to set up a subscription system using Commerce. If you also need to write a payment processor from scratch then it'd be a good idea to look at the Commerce Paypal module at the same time so you can get a good overview of what needs to be done.

I'm afraid I can't comment on the UC Recurring Payments options as I've never used it.


What is the correct way to rename an uploaded file using tokens?

I had the same issue. The answer was buried way down in Browse available tokens.
I wanted to rename an uploaded file based on the responses to the last_name and first_name fields. The pattern that worked was [webform_submission:values:last_name]_[webform_submission:values:first_name].


hook_update_N() for more than 100 updates or 10 major releases

The one time I dealt with this, I just kept on going. After 7199, I moved to 71100, then 71101 etc. It wasn't a problem (Drupal 7).


What is causing pathauto to generate unwanted text in these URLs?

Pathauto creates the alias when a node is being added or edited, so, if you are using current-page:title it will include the title that Drupal generates for that page, eg, in your case, "Edit Site Article: This is a title", and not just the title of the node.  So I would look into using node:title instead so as to remove any of those potential prefixings.


simplenews. confirmation of subscription for registered user

well, since no one here, I will use:

simplenews_subscribe_user($email, $tid, TRUE, 'website');


I found the following module that does a great job: Comment Node Edit.

  Gives Site Administrators ability to mark field instances as "editable
  by comment." When a field is editable by comment, the field will show
  up in the "add comment" form.


Looking at the drush code this is the function that looks for the "hooks"

drush_command_invoke_all('drush_sql_sync_sanitize', 'default');

following the path at the end is calling to:

drush_commandfile_list()

which is going to look for hooks implementations in the next folders:

The "/path/to/drush/commands" folder.
Folders listed in the 'include' option (see example.drushrc.php).
The system-wide drush commands folder, e.g. /usr/share/drush/commands
The ".drush" folder in the user's HOME folder.
/drush and sites/all/drush in current Drupal site.
Folders belonging to enabled modules in the current Drupal site.

So as @Clive suggested probably MYMODULE.drush.inc and MYMODULE_drush_sql_sync_sanitize should work.


You must enable validation on your contextual filter.

More information found here:

https://drupal.org/node/1578564

http://nodeone.se/en/learn-views-with-nodeone-part-23-validation-of-contextual-filter-input


Drupal 8: "Page cache maximum age" is not working for anonymous users

There was discussion in the chat, but there are still some things that can be answered.

The maximum age setting actually has not much to do with the built-in caching mechanisms of Drupal, as confusing as that is. It only controls the Cache-Control max-age header that is sent if the page is considered cacheable.

If you don't see a X-Drupal-Cache: HIT/MISS header in the response then that means your page is not cacheable. There are a number of things that can cause that, check if you have a session cookie (if yes, you need to figure out what's in there and who sets it), check that no module that you are using disables the page cache. For example captcha.module does that if you display a captcha as that can't be cached (not something like the built-in image captcha at least).

If you see that header then it is working. The Page cache modules actually don't care about that setting, they cache the page forever. However, any relevant change on the page automatically invalidates that page and fresh content is served. See https://www.drupal.org/docs/8/api/cache-api/cache-tags for more information on how that works.


So continuing from the comments above.

You are calling theme('similetimeline', $html);, which in turn will call theme_similetimeline($html). So the main reason you don't get any output, is simply that you lack the theming function.

To get started, you can do away with theme() all together and just print $html;. Especially since you've already generated the markup, but on the other hand, it's great that you've already gotten far enough to know you should use theme(), considering you say you are a beginner. The reason for theme calls, is that you can separate the module and it's functionality, from it's markup, meaning this timeline can look different in different themes.

You will find a more extensive example, and a great answer by Clive, in a similar question I asked recently.


Your choice of site architecture (e.g. multisite or multiple drupal installations) doesn't necessarily play into performance. Meaning any site can be made performant using the right mix of modules (memcache, Varnish on the front end, etc.);

With that in mind, look at the following criteria when selecting multisite over multi-installation instead:

Will most of the modules on the sites be shared with one another?
Related, will the modules always be in sync via version? i.e. Context 3 vs. Context 2.
Will the versions need to be in sync? i.e. If you upgrade the main site, will the blog site also need to be upgraded?

If the answer to any of these questions is yes, use a multisite. If there is concern about them, use two document roots with one site a piece. Sharing content can easily be done through any of the following projects so multisite or multi-installation doesn't matter:

http://drupal.org/project/feeds
http://drupal.org/project/migrate
http://drupal.org/project/services


Having trouble POSTing value for a select element with SimpleTest

After talking this through, I realized that I had not created the database records necessary to fill the select element in the test case. So, during the test, there actually was no <option value="1">. The lesson is to think carefully about the entire context when writing test cases.


According to Drupal 7 Template (Theme Hook) Suggestions there is no page--content-type.tpl.php, only node--type.tpl.php
If you have to use a page-content-type.tpl.php you must create a template suggestion. This (d6) or this (d7) might help you doing so.


How can I add a special classes to all block of custom kind?

It's no problem to add classes in a block preprocess hook:

use Drupal\Component\Utility\Html;

  function mytheme_preprocess_block(&$variables) {
    $variables['attributes']['class'][] = Html::getClass('block-id-' . $variables['elements']['#id']);
    $variables['attributes']['class'][] = Html::getClass('block-plugin-' . $variables['elements']['#base_plugin_id']);
    $variables['attributes']['class'][] = Html::getClass('block-provider-' . $variables['elements']['#configuration']['provider']);
  }

This example simply adds the available information to all blocks. You can start with this and narrow it down to what you want.


Title a,Title b could be terms of a vocabulary
add this vocabulary as term reference to article
edit your nodes to include desired term
modify front page view to group by term on this vocabulary

to have specific sorting for each of the term articles you can add integer field position to article and use it as sorting criteria in the view

for ordering the terms sort them in the vocabulary term list and use term weight as sorting criteria on view

For sorting one could also use draggable views  and even nodequeue as suggested in the comments


How to print entity referenced fields (node) title in node.tpl.php?

OK, without knowing anything about stdClass Object these kind of questions are normal :)

So, after reading a question about stdClass Object in SO I did what I want as below:

<?php print $node->field_my_entity_reference['und'][0]['entity']->title; ?>

This prints the title as plain text.

Note: Is there another way or better way you're always welcome.


If i understand correctly this is not possible out of the box with your current setup and views only. Could you split the view into 2 seperate views instead? Use the second one as attachment for the first. So you could define the pager for each view. You could also look into Views Field View Module. With node specific pagers created with the Entity Pager Module it could possibly work even with your current setup.


Customizing Drupal Commerce Bundle module

IIRC you may have better results using Commerce Product Add-on, which allows you to have other products as add-ons. Product Bundles work well when you have fixed bundles - i.e. "A fork, spade, and bucket", not "Forks", "Spades", and "Buckets" you want to cross/upsell - if you know what I mean...!

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


There are 2 parts to this question:

How to make Drupal accept second paths? Go to http://example.com/admin/config/search/path and set aliases for them. You can use Pathauto to automate this process, or try one of the modules that allows wildcards in aliases.
How to make Drupal generate proper paths? Well, if above will not assure this, use Global Redirect - it'll make sure only aliases are visible to your users.


drupal_get_path() not working in subdirectories of my site

Its because drupal_get_path returns relative path.

Try this:

<?php
  global $base_path;
  $src = $base_path . drupal_get_path('theme', $GLOBALS['theme']) . '/imag/carrots.png';
  echo ''
?>

Edit with url function:

<?php
  $src = url(drupal_get_path('theme', $GLOBALS['theme']) . '/imag/carrots.png');
  echo ''
?>


How to retrieve value of start date with format end date?

Try using:

 $datum_deelname = $node->get('field_optional_enddate')->end_value;

This will give the optional end date.

If you want to get the normal date as you mentioned you can use as:

 $datum_deelname = $node->get('field_optional_enddate')->value;


Does backup and migrate include the users and login info?

If you want to move user data from a Drupal site to another, you need to use the Migrate module. The Backup and migrate module is for exporting and restoring database and files.


How to deal with module conflicts ("anti-dependencies")?

The module just needs to implement hook_requirements(); a requirement could be that a module is not installed, and if the module returnes an error from hook_requirements(), then it will not be installed.

The module should implement code similar to the following one:

function mymodule_requirements($phase) {
  $requirements = array();
  // Ensure translations don't break at install time
  $t = get_t();

  if ($phase == 'install') {
    if (module_exists('other_module')) {
      $requirements['mymodule'] = array(
        'title' => $t('My module'),
        'value' => $t('My module is not compatible with Other module.'),
        'severity' => REQUIREMENT_ERROR,
      );
    }
  }

  return $requirements;
}


Page Manager module.  Add a new page that has the Path of /taxonomy/term/% and as @Todd Young wrote, disable the default Taxonomy view.

However, there is a bug that this is not working at https://www.drupal.org/node/2785195


How do I get a form field value out of a config entity data blob?

The entity is already available with $form_state->getFormObject()->getEntity(). That basically answers your question.

Note that stuffing arbitrary keys into a config entity is not supported, you should use the third party settings API instead. See http://larowlan.github.io/meet-third-party-settings-interface/#/12 for a simple example (but make sure you also check the slides before about config schema). The initial part is not necessary anymore as all config entities support third party settings out of the box now.


How to retrieve value of hidden field in twig?

The variables in a paragraph template contain the fully loaded paragraph entity:

paragraph.html.twig

{#
/**
 * @file
 * Default theme implementation to display a paragraph.
 *
 * Available variables:
 * - paragraph: Full paragraph entity.

from which you can retrieve raw values of any field, not matter whether base field or configured field or displayed or not:

{% set value = paragraph.field_example.value %}

On the contrary {{ content }}

 * - content: All paragraph items. Use {{ content }} to print them all,
 *   or print a subset such as {{ content.field_example }}. Use
 *   {{ content|without('field_example') }} to temporarily suppress the printing
 *   of a given child element.

contains only the fields configured to be displayed in "Manage Display".


I need to access individual elements of a node in my module

1) You can use code like the following:

$render['my_list'][] = array('#markup' => '<div>'.$node->title.'</div>');
$render['my_list'][] = array('#markup' => $node->body['und'][0]['value']);

2) Forms can be added similarly to node_view():

$render['my_list'][] = drupal_get_form('mymodule_buy_form_'.$node->nid, $node->nid);

I'm assuming you want the forms built with a single function, but with different id-s to work correctly (attached $node->nid for that). I also added an extra argument ($node->nid) since you may want to add it to every form in a hidden field to determine which form got submitted. Then you use hook_forms() to get the same builder function called for all the buying forms:

function mymodule_forms($form_id, $args) {
  $forms = array();
  if (strpos($form_id, 'mymodule_buy_form_') === 0) {
    $forms[$form_id] = array(
      'callback' => 'mymodule_buy_form',
    );
  }
  return $forms;
}

The form builder function for this example:

function mymodule_buy_form($form, &$form_state, $nid) {
  $form = array();
  $form['nid'] = array(
    '#type' => 'hidden',
    '#value' => $nid,
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  return $form;
}

And a submit handler:

function mymodule_buy_form_submit($form, &$form_state) {
  drupal_set_message('Form for node '.$form_state['values']['nid'].' submitted.');
}


Why would I want to use Universally Unique IDentifier (UUID) in Drupal?

If you want to create an UUID for you content you should use the modules. UUIDs can be used for content staging and such.

The problem is that Drupal uses serial ids for the content (nodes), so if we have the same site installed different places, the id for the same content most likely will be different. (fx in one environment the node id might be 137, while it on another might be 153)
This makes it very hard to track changes on the same content in different environments. The idea with UUIDs is to create a id that is the same on all environments.

So you could have content writers work on a stage site, have it reviewed, and the put the changes out on the production server, without messing everything up in the process.


How to organize content via taxonomy, blocks, panels, views?

This is a very broad question Brian, but I think it boils down to 'how should I handle relationships between entities'.

Take a look at the Entity Reference module.  With that you can create links between your various nodes so that you can display them on the same page.

For instance let's say your main content type is exercise, on each exercise node you could use the module to create links to a video and a fingering diagram (or several).  Then for each other thing you wanted to display on the page, you create a view with a contextual filter that looks for the node id of the exercise which is being displayed.

I highly recommend finding some reading or videos on how contextual filters in views works.

Panels makes the handling of contexts a little bit easier in the long run.  There's an excellent tutorial on Page Manager.


Use field from current node in filter in view

Niall Murphy's concept is correct but there are some differences between how it's performed in D8 and D7. Here is the code I ended up using which was successful.

function my_module_views_pre_view(&$view, &$display_id,&$args){
    if($view->id() == 'news'){
        if($view->current_display == 'block_2'){
            $current_node = \Drupal::routeMatch()->getParameter('node');
            if(!empty($current_node)){
                $focus_area = $current_node->field_focus_area->entity->id();
                $args[0] = $focus_area;
                $view->setArguments($args);
            }
        }
    }
}


I found out that leaving the extension with an space instead of empty work, but I wonder how secure it this solution. In my case I remove the file a second after I upload it as I am only interested on its content.

Here is the code that worked for me:

$validators = array('file_validate_extensions' => array(' '));
$file = file_save_upload($i, $validators);

Thank you.


How can I display site logo, name and slogan?

function mytheme_preprocess_page(&$variables) {
  $site_config = \Drupal::config('system.site');
  $variables['site_name'] = $site_config->get('name');
  $variables['site_slogan'] = $site_config->get('slogan');

  // logo needs to be placed within specified folder
  $variables['logopath'] = file_url_transform_relative(file_create_url(theme_get_setting('logo.url')));

}

Then in page.html.twig you can use variables site_name and site_slogan as follows:

{{ site_name }}
{{ site_slogan }}

and for the logo:

<img src="{{ logopath }}" />

note: logo image file will need to be available in your current theme's root folder (or subfolder of your choice).


Alter default message presented to user on failed login attempt

You can set your own custom message according to the validation by adding your custom validation function with login form.

function custom_module_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'user_login_block' || $form_id == 'user_login')
    $form['#validate'] = array('custom_module_login_validate', 'user_login_authenticate_validate');
}
function custom_module_login_validate($form, &$form_state) {
  $uid = _custom_module_is_user_exists($form_state['values']['name']);
  if(!$uid) {
    form_set_error('name','Username not found.');
  }
  else {
    if(!user_authenticate($form_state['values']['name'], $form_state['values']['pass'])) {
       form_set_error('pass','Incorrect password.');
    }
  }

}
/**
 * Query user table to check if such username is already exists.
 */
function _custom_module_is_user_exists($username) {
  return db_query("SELECT u.uid FROM {users} u WHERE LOWER(u.name) = LOWER(:username)", array(':username'=>$username))->fetchField();
}


Chosen working on one select but not other selects

It looks like you have a 'Minimum number of options' setting of 20. I'm guessing the ones that don't display have less than 20 available options. Try setting this to 'always apply' on the Chosen settings form (admin/config/user-interface/chosen).


How to go about creating and formatting a custom HTML/PHP table to display SQL data

You can create a custom table to display whatever data you want in a custom module by building the information output in a function, first you have to implement HOOK_menu for defining you path for the page containing the table and afterwards implementing the callback function for that page. I'll give you a real example here:

/**
* Implement hook_menu().
*/
function HOOK_menu() {
  $items = array();

$items['admin/config/my_table'] = array(
      'title' => 'My Table Page',
      'description' => '',
      'page callback' => 'my_table',
      'access arguments' => ....,
    );

 return $items;
}

As you can see i have my path and the callback is defined to the function my_table. Let's create that as well

function my_table {

    // Create table header
    $header = array(
        array('data' => t('COLUMN 1')),
        array('data' => t('ANOTHER ONE')),
        array('data' => t('COLUMN EXAMPLE')),
        array('data' => t('BLA BLA'))
    );

   .... // create table rows

    $output = '
';
    $output .= '
' . t('Say whatever you want to appear'). '
';
    $output .= '
';

    // here we render the actual table
    $output .= theme('table', array('header' => $header, 'rows'=> $rows, 'attributes' => array('id' => 'something') ));

    // and return the html output to our page
    return $output;

}

Hope this helps! Cheers!


in the options you can put another field like this:

foreach($xsroads as $xsroad){
  $options[$xsroad['id']] = array(
    'xsr_name' => $xsroad['xsr_name'],
    'xsr_input' => array(
      'data' => array(
        '#type' => 'textfield',
        '#value => 'so you wanned a field',
      ),
    ),
  );
}


Trying to disable mail on contact form, but it's still required on submit

Are you talking about the site wide contact form or the personal contact forms that each user can have? I'll talk about the site wide form, but the following roughly applies to the personal one as well.

The email validation is hard wired in contact_site_form_validate, and the $mail is also needed in the submission handler, so there is no nice way around it.

Easy way: Set the default value for the mail field to an address that you own and then disable access to the field like this:

function contact_field_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'contact_site_form') {
    $form['mail']['#required'] = FALSE;
    $form['mail']['#default_value'] = 'me@my-site.com';
    $form['mail']['#access'] = FALSE;
  }
}

This will completely hide the mail field.

Hardcore way: In your form alter you could overwrite the default validation and submission callbacks (using $form['#validate'] and $form['#submit']) and replace them with your custom ones. This does not come without the risk of side effects. If you have other modules that want to add custom stuff and logic for contact forms, then this will probably break them.

As an alternative, you could use the webform module. It gives you a lot more flexibility concerning the information that you want to request and having an optional email field in there is very easy to do.

Update: You can also try the following (untested):

function contact_field_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'contact_site_form') {
    $form['mail']['#required'] = FALSE;
    $form['mail']['#default_value'] = '';
    // This makes our custom validation come first.
    array_unshift($form['#validate'], 'my_custom_validation');
  }
}

function my_custom_validation($form, &$form_state) {
  // This fills an empty mail value with a default one.
  if (empty($form_state['values']['mail']) {
    form_set_value($form['mail'], 'me@my-site.com', $form_state);
  }
  // After this the default validation will run.
}

This will remove the asterisk, hide any preset value and in the validation handler a default value for the mail field is set if none has been submitted by the user. That way the hard wired validation shouldn't have a reason to complain.


Right to left theme: Bootstrap or Zurb Foundation?

"Foundation was built to support right-to-left text direction out of the box, but you'll need to make a couple of adjustments to your markup and Sass to get everything up and running." This is just some minor changes, nothing special.
For bootstrap there's a special version that is focused on RTL support: https://github.com/Kaakati/RTL_Bootstrap


How do I have a dropdown select list for an entity reference?

Yes, you can. Drupal 8 does it out of the box as D7. The only difference is you can now choose the widget for any field in the Manage form display tab of a entity type.

E.g. Try changing the widget of the entity reference field - Tags - for article content type from /admin/structure/types/manage/article/form-display


How to render input fields in a custom page template page

You can customize your form using #prefix and #suffix in hook_form_alter(). They will add wrapper HTML markup into your form and then you can customize them with your custom CSS and JS attached to the form.

Here is an example code:

function MYMODULE_form_alter(&$form, &$form_state, &$form_id){
    if($form_id == 'article_node_form'){
        $form['title']['#prefix'] = '
';
        // more fields here
        $form['body']['#suffix']  = '
';

        $form['field_1']['#prefix'] = '
';
        // more fields here
        $form['field_5']['#suffix'] = '
';

        // attach additional css/js to this form page for your customization
        $form['#attached']['css'][] = drupal_get_path('module', 'mymodule'). '/mymodule.css';
        $form['#attached']['js'][] = drupal_get_path('module', 'mymodule'). '/mymodule.js';
    }
}

You can also add additional HTML using #markup.

$form["unique_id"] = array(
    '#markup' => "
some html
"
);


Redirect After Creating New Taxonomy Term

To add a redirection after creating new Taxonomy Term I suggest using the hook_preprocess_HOOK() in the MYTHEME.theme file.
E.g. here is code that add redirection back to the Vocabulary - list of all terms - for the Add term button:
/**
 * Implements hook_preprocess_HOOK() for menu-local-action templates.
 */
function MYTHEME_preprocess_menu_local_action(array &$vars) {
  if ($vars['link']['#title'] == 'Add term') {
    // Add redirection to the Terms list after creating a new term.
    $destination = Url::fromRoute('<current>')->toString();
    $vars['link']['#options']['query']['destination'] = $destination;
  }
}


manipulate form variables before render()

The Form API has #pre_render per element. You can use hook_form_alter to add your pre-render function to the list of functions that need to be called to show the value.

  #pre_render

  Used by: All elements and forms.

  Description: Function(s) to call before rendering in drupal_render()
  has occured. The function(s) provided in #pre_render receive the
  element as an argument and must return the altered element.

  Values: An array of function names to call.

  Note: If you are altering an existing form via hook_form_alter() or a
  similar means, be careful with this property! As demonstrated here,
  you will probably want to add to the existing array rather than
  writing over it.

I recommend being careful of when your module runs when trying to interact with Forms, Ajax, etc (your modules' weight). If needed I also recommend seeing hook_module_implements_alter if you want to adjust when your hook is called, without affecting your modules' weight.


How to display an image in a Views RSS feed

First add the Media RSS namespace to your views-view-rss.tpl.php

<rss version="2.0" xml:base="<?php print $link; ?>"<?php print $namespaces; ?> xmlns:media="http://search.yahoo.com/mrss/">

Then add the  tag to your views-view-row-rss.tpl.php

<media:content url="<?php print image_style_url('my_img_style_id', $node->field_image['und'][0]['uri']); ?>" type="image/jpeg" medium="image" height="800" width="600" lang="en" />

Lastly make the field data available to your theme's template

function mytheme_preprocess_views_view_row_rss(&$vars) {
  $view     = &$vars['view'];
  $options  = &$vars['options'];
  $item     = &$vars['row'];

  // Use the [id] of the returned results to determine the nid in [results]
  $result = &$vars['view']->result;
  $id   = &$vars['id'];
  $node   = node_load( $result[$id-1]->nid );
  $vars['node'] = $node;
}

Original article: https://blog.sam-thompson.info/images-in-drupal-rss-feed-without-additional-modules/


Use background images without knowing programming?

You should change the body background selector in the css file of the template, for example

body{ background: url("path to image");}

More info how to use background css


Long-running cron task never fully executed

After a long battle analyzing how to execute a long-running task as a Drupal Cron, finally I found a generic solution that involves the Queue API and Cron. Maybe this can help other people who is struggling with a similar problem. Here are the steps I followed:

Think about how to execute your long-running task as chunks in terms of Drupal Queue items. You need to represent all tasks as queue items. For example, the first item (or action) may be to initialize the complex work that needs to be done. Then, the following items may execute that work by pieces. Each item (or chunk) has to be processed individually, so no PHP Timeout or PHP Memory Exhausted error appear.
Create a new Cron that will create the queue and its items. Make sure that you also implement the hook_cron_queue_info().
Implement the queue item process function you defined in the above hook. If you need to pass information between each item process, you can use Drupal's variable_get(...) and variable_set(...). If you need a more complex structure, you can define a database with Schema API in the module my_module.install file.
Now create a new function that will read and process one or more items of your queue (if not empty).

For example:

function my_module_process_my_queue() {
  $my_queue = DrupalQueue::get('my_module_queue');
  if ($my_queue->numberOfItems() > 0) {
    $action = $my_queue->claimItem();
    if ($action) {
      my_module_queue_process_item($action->data);
      $my_queue->deleteItem($action);
    }
  }
}

Install a Cron module (such as Elysia Cron) or add a cron job in your server configuration. At least, you need to specify the execution of 2 Cron functions. The first one (from step 2) will run the moment you prefer. In my case, it has to run once a day. The second one will be a simple Cron that will call the function from step 4. That second Cron will run every X minutes. Where X means the maximum time execution that a queue item processing may take. If you do not install a Cron module, you do not need the second Cron function. In my case, I decided to use Linux crontab configuration and Drush.

For example:

*/2 * * * * cd /path/to/your/drupal/installation && export DRUSH_PHP=/path/to/your/bin/php && drush ev "my_module_process_my_queue();"

Finally, execute your crons or wait until they are executed. Once a day, the queue will be filled with new queue items. Those items will be processed during the first Cron execution and every X minutes with the other one. So, after some time, all queue items will be processed and the long-running task will finish.


How to sort autocomplete results by post date?

You should use views entity reference widget.you can custom you result like want you want.

this link is good tutorial for you achieve your job.I hope learn it and use  it in future project and issues.


How to show translated taxonomy terms in a view?

Instead of adding the term: name, add term: name (localized) to your view.


Watchdog "404 page not found" entries from spambot guessing urls

Block them using these modules, study these and related modules for perfect working solution to your need :

http://drupal.org/project/httpbl

http://drupal.org/project/badbehavior

http://drupal.org/project/antispam (Apart from blocking comment spam, disables bot showing 403 error)

http://drupal.org/project/botcha

Install http://configserver.com/cp/csf.html and use Real Time Block Lists (RBLs)

And finally a free-service like http://www.cloudflare.com/features-security will get things working.


How can I get the cid of the latest comment I saved using comment_save?

The cid value should be in the comment object after it has been saved. So you should simply be able to use something like this:

comment_save($comment);
drupal_set_mesage("ID is " . $comment->cid);


Custom user login in Facebook Auth modules

Provided that you're using v8.3 or higher of the module, a possible solution would be to create a form where the user decides which values are stored according to his/her needs and your requirements of course.
Then, using the provided events in the module, you can redirect the user to this form which will accept the $user object and apply the changes accordingly.
You should add an EventSubscriber service which listens to simple_fb_connect.user_created event as per the module documentation linked above. Thus you're only showing this form to the user once after the account has been created and not with every login.
Hope this helps.


You need to add a "date field" to the test content type.

And with views +date field + calendar you will be able to do it.


If you have a wysiwyg option you can insert images into the body field.  There is a wysiwyg module that provides good integration and management and lets you use one of several engines.  If it is okay to have the image at the start or end of the body text, and not in the middle, then go to the Display Fields tab at the top of your screenshot and drag your image field into the appropriate order.  Also you can set image display size and other options from that area.


When using a grouping field in an HTML list, is there a way to determine the group/loop number of the current content being rendered?

I don't know of a way to get the group number from within the grouping (e.g. views-view-list) template, but I would look to do this  split between two templates: views-view and views-view-list.
First, in the views-view template, e.g. views-view--my-view-id.html.twig.
{# ... etc ... #}
{# Loop through the rows, aka groups, and add a wrapper with index identifier. #}
{% for row in rows %}

    {{ row }}

{% endfor %}
{# ... etc ... #}

Second, create your views-view-list template, e.g. views-view--my-view-id.html.twig to build the content for each group:

{{ title }}

  {% for row in rows %}

      {{- row.content -}}

  {% endfor %}

Then you can target the contents of each group in css like:
.group--1 h3 { }
.group--1 ul { }
.group--2 h3 { }
.group--2 ul { }
.etc { }


COOKIE['session_api_session'] not working in drupal 7

Quoting value with " characters in MySQL is wrong. The MySQL string quote is '. The " character is the character used to quote table or columns names. With an empty value in $cookieid you have an SQL query searching session-id equals to a column named empty string, this is the

  PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column '' in 'where clause': SELECT sid FROM {session_api} WHERE session_id = "";

with 'foo' as session uid you would have a query searching for rows having session_id columns equals to value of "foo" column. It would also be wrong.

Use Drupal helpers to write queries. Field and value escapes will be the right ones for the right engine:

$sid = db_query(
  'SELECT sid FROM {session_api}  WHERE session_id = %my_sid',
   array('%my_sid' => $cookieid
)->fetchField();

Or even more D7 (untested but it's something like that):

 $query= db_select('session_api','s');
 $query->fields('s','sid');
 $query->conditions('sid',$cookieid,'=');
 $sid = $query->fetchField();

now the 1st error message says there is nothing in $_COOKIE['session_api_session']. So you should enclose your code in a:

if (array_key_exists('session_api_session',$_COOKIE)
 && !empty($_COOKIE['session_api_session'])) {
   ...
}

At least you will avoid the warnings and errors.

About session api usage I would certainly better use session api functions to retrieve the current id, something like session_api_get_sid():

/**
 * Return a Session API ID corresponding to the current session.
 * The session id is a created using the same method as Drupal core
 * as defined in includes/session.inc.
 * @param boolean create set this to FALSE if you don't want to create a session
 * cookie if it doesn't already exist.
 */
function session_api_get_sid($create = TRUE) {


What about just creating two different views, one for users and another one for content? If there is no relationship between users and content, this might be the easiest solution.

You can create two different blocks and then display them together in your page (using Blocks, Context, Panels or whatever method you prefer).

Hope it helps,


How can I roll the database back to the backup

You can use Drush.

All you need to do is to run, inside a Drupal instalation, the following command:

drush sqlc < path/to/backup.sql

*You may want to drop your current database before that. The command is:

drush sql-drop -y


How do I unset a region in template.php AND have it alter the body classes

If you look at the default template_preprocess_html, you will see

  // Add information about the number of sidebars.
  if (!empty($variables['page']['sidebar_first']) && !empty($variables['page']['sidebar_second'])) {
    $variables['classes_array'][] = 'two-sidebars';
  }
  elseif (!empty($variables['page']['sidebar_first'])) {
    $variables['classes_array'][] = 'one-sidebar sidebar-first';
  }
  elseif (!empty($variables['page']['sidebar_second'])) {
    $variables['classes_array'][] = 'one-sidebar sidebar-second';
  }
  else {
    $variables['classes_array'][] = 'no-sidebars';
  }

If you don't want this behavior, you should implement your own version which will run after.  Then, you just check your condition and muck with $variables['classes_array'] as needed.


add pre-registered links to user menu via hook_menu

You can use hook_menu_alter() to override properties for existing paths:

function MYMODULE_menu_alter(&$items) {
  $items['user/logout']['menu_name'] = 'primary-links';
}


JSON format for creating users with custom fields using services

The views datasource module is more handy. Try this module and create a view of the data you need to send.


How to fix Openlayers "Unable to load CTools exportable" errors

I just got an answer from the Openlayers issues cues. The unable to load CTools errors exist when the module is looking for a missing or deleted component of a map.

In my case, I had to re-install my OL module and reconstruct the map with just the components I needed. It took some trial and error to get there.


How to load entity by UUID from url argument?

Yes, you need your own param converter for this, the default implementation can only load by UUID.

Loading by UUID is less performant as long as the primary ID is still a serial ID, this means that it first needs to do an entity query to fetch the ID and then load that.


View with relationship to custom entity via computed property

Finally figured out a workaround: Pull every needed entity property as a "virtual field" into the node itself.

// define additional property information for node
function mymodule_entity_property_info_alter(&$info) {
  $properties = & $info['node']['properties'];
  foreach (array('myprop') as $property) {
    $properties[$property] = array(
      'label' => $info['mymodule']['properties'][$property]['label'],
      'description' => $info['mymodule']['properties'][$property]['description'],
      'type' => $info['mymodule']['properties'][$property]['type'],
      'computed' => TRUE,
      'queryable' => TRUE,
      'entity views field' => TRUE,
      'getter callback' => "mymodule_node_property_verbatim_get",
    );
  }
}

// getter callback
function mymodule_node_property_verbatim_get($data, array $options, $name, $type, $info) {
  $myentity = mymodule_get_from_node($data);
  return !empty($publication->{$name}) ? $publication->{$name} : array();
}

// obtain the related entity from the node
function mymodule_get_from_node($node) {

  // some custom code to get myentity

  return $myentity;
}

Thus, the properties can be adressed as views fields as well as for any other purposes. It's possible to extend this to access properties of nested entities, too.

One drawback, however: The fields cannot be used as views sort criteria.


Print module's default setting is annoying

Looking at http://drupalcontrib.org/api/drupal/contributions--print--print.module/function/print_form_alter/6, it seems to use a constant called PRINT_TYPE_SHOW_LINK_DEFAULT for the default value. That in turn is hardcoded to 1, see http://drupalcontrib.org/api/drupal/contributions--print--print.module/constant/PRINT_TYPE_SHOW_LINK_DEFAULT/6.

So you don't have a way to change that without hacking the module.

You could try to submit a feature request in the issue queue: http://drupal.org/project/issues/print


How can I trigger a rule when there's no more scheduled content?

You can make this work also by using Rules in combination with the Views Bulk Operations module, as further detailed below.

Step 1

Use the Views Bulk Operations module to create a view of all your "nodes to be published" (as in your question), in which you add a VBO field to it. Simply include a field like nid for each node (no need for any other fields). Just make sure you get exactly 1 row for each node you want to take into consideration.

Step 2

Create a Rules Component with a Rules Condition "Check number of results returned by a VBO view". And select the VBO view created in the previous step. If the number of results is below 1, then perform a Rules Action (in that Rules Component) to trigger your eMail.

Step 3

Create a Rule like so:

Use some relevant Rules Event related to those nodes to be published.
Don't use any Rules Conditions (there is no need for them in this rule).
Perform a Rules Action to execute the Rules Component from Step 2.

If you cannot think of any relevant Rules Event that would fit for such rule, then just create a Rules Component which has (only) 2 Rules Actions:

Perform a Rules Action to execute the Rules Component from Step 2.
Reschedule this (extra) Rules Component itself, eg after X mins or hours

Then trigger the very first execution of this Rules Component using the Rules UI.

Done!


Is it possible to get Views data in the views-view.html.twig file?


How to integrate properly Kerberos based SSO in Drupal 7

After some researches and tests, I finally made a choice.

In most cases, I'd prefer use native or add on features. This provide better integreation with the product (here Drupal) and it's more a Logic solution than a technical one (which is quite easier).
The LDAP_SSO module allow this kind of configuration.

Nevertheless, I was not able to configure it this time, mainly due to poor debug facilities. Even with watchdog, I am not able to know what is the matter. Moreover, my customer have clear procedure to install and use Kerberos, with Apache HTTP and mod_auth_kerb.
Hopefully, LDAP_SSO module allow this too.

After some tries, I will get back here to share with you more advanced comments, but at this time, we clearly go to apache+mod_auth_kerb+fowarded REMOTE_USER.

Edit a few monthes later :

That works great with Mod auth kerb on apache server and ldap module v1.0-beta12 on drupal.
Even if v2.0 is available, we were facing some issues because some fields were empty and this were causing troubleshootings.
But nevermind, we are able to authenticate et identify users, collect groups and map them to  drupal profiles etc.


Using Drush on shared hosting without `curl` and `wget`

Your use case is not supported. You'll have to update locally and then push to your provider.


Views module comes with the field Has new content that outputs New or Updated depending on the status of the node as being viewed by a visitor.

Anonymous visitors don't see anything because there is no history record about that users visits to a particular node.

Authenticated users will see the word New if they never visited that node. If they have visited that node in the past, but the node has been updated in the meantime, they will see Updated. Once they visit the node again, they won't see any output for that field.

So this doesn't work quite as you described in your question, but it still may be what you're after.

You can add that field to your Views, Exclude it from display, and then Rewrite the Title field to include it before the actual title text.

The way you've written your condition in the screenshot is criss-crossed, you're trying to output "updated" for nodes that are new (at least according to your logic of those times being equal).

Your rewrite would also always show output for all nodes, even the ones the visitor has seen. Visitors usually don't expect that to behave like that. That's why it makes more sense to use Has new content field, but it all depends on your project and your visitors' expectations.

The created and updated time always differ because the created time is the one when the Create node form was loaded in the browser, and the updated time is the actual time when the Save button was hit, when the node was actually saved. The difference in created and updated times is the time it takes to fill in the form ;)


Programmatically set the value of a date/Time field

The expiry_date from webform return something like 2021-05-25 11:26:02 +03:00 so you should to format it before you passe it to create like the following:

// Get 'Expiry Date' Value.
$ExpiryDate = $values['expiry_date'];
// Format the "Expiry Date" to return "Y-m-d\TH:i:s".
// Here use strtotime to format date correctly
$FormattedExpiry = date('Y-m-d\TH:i:s', strtotime($ExpiryDate));

Then passe $FormattedExpiry instead of $ExpiryDate:

$article = \Drupal\node\Entity\Node::create([
    'type' => 'article',
   // Set the node field values.
    'title' => $Title,
    'langcode' => 'en',
    'uid' => $CurrentUid,
    'status' => '1',
    'created' => $current_time,
    'field_expiry_date' => $FormattedExpiry,
    ]);

Update: your date already has +3h, if you want to not add 3 hours to your time there is two options i guess:

Change you webform field settings to work with UTC to get the value of $values['expiry_date'] something like 2021-05-25 11:26:02 without +03:00
Remove the +03:00 before date conversion from $values['expiry_date'] by change the line $ExpiryDate = $values['expiry_date']; with something like:

$ExpiryDate = explode('+', $values['expiry_date'])[0];


Fields are usually available as selector rules, so the solution to your problem: find out in which field the content is stored and use a empty/ not empty selection rule for your variant.

variants are selected by order, so the first variant that matches is selected. You could implement two panel variants, one with selection rule for empty, one for not empty, or use only one with selection rule and order the other on underneath that one.


Usually in Drupal, the ajax callback is business logic free. You should associate your title (ie string) directly in the form, when ajax had run.
I use this :

function contact_contact_search_form($form, &$form_state) {

$string = '';

//Retrive the string value
if (isset($form_state['values'])) { // Does ajax ran ?
   $string = $form_state['values']['string'];
}

$form['string'] = array(
  '#type' => 'textfield',
  '#title' => t('Name'),
);

$form['submit'] = array(
  '#type' => 'submit',
  '#ajax' => array(
      'callback' => 'contact_contact_search_ajax',
      'method' => 'replace',
      'effect' => 'none',
  ),
  '#value' => t('Submit'),
);

// Display the result in the form, but should work if the results are outside of your form
$form['table'] = array(
  '#type' => 'item',
  '#prefix' => '
',
  '#suffix' => '
',
  '#markup' => contact_contact_display_searches($string),
);

return $form;
}

function contact_contact_search_ajax(&$form, &$form_state) {

   $commandes[] = ajax_command_replace('#search-table',drupal_render($form['table']));

   return array(
     '#type' => 'ajax',
     '#commands' => $commandes,
   );
}

// Create your table
function contact_contact_display_searches($string) {
// The query
  $query = db_select('node', 'n')
      ->fields('n')
      ->condition('n.title', '%' . db_like($string) . '%', 'LIKE');
      ->range(0, 20)
      ->execute()->fetchAll();

 // Prepare and clean the results
foreach ($results as $result) {
  $rows[$result->nid] = array(
      'type' => check_plain($types[$result->type]->name),
      'title' => l(check_plain($result->title), 'node/' . $result->nid),
      'email' => check_plain($result->field_pers_email_email),
  );
}

// Simple table theming
$out = theme('table', array(
    'header' => array(t('Type de contenu'), t('Intitulé'), t('email')),
    'rows' => $rows,
    'empty' => t('Aucun résultat avec ces critères de recherche')
        )
  );
}
return $out;

}


Why do I get the "Class 'Drupal\Core\Database' not found" error?

Drupal\Core\Database is the namespace of the class, which is not what the use statement requires. It needs the full-qualified class name, which, for that class, is Drupal\Core\Database\Database.

use Drupal\Core\Database\Database;

That is what Drupal core uses, for example in the DbLog.php file.

namespace Drupal\dblog\Logger;

use Drupal\Component\Utility\Unicode;
use Drupal\Core\Database\Connection;
use Drupal\Core\Database\Database;
use Drupal\Core\Database\DatabaseException;
use Drupal\Core\DependencyInjection\DependencySerializationTrait;
use Drupal\Core\Logger\LogMessageParserInterface;
use Drupal\Core\Logger\RfcLoggerTrait;
use Psr\Log\LoggerInterface;


How to send auto login email using Email Auto Login drupal module?

First of all to send out an email automatically you will need a triggering event – and probably also some condition, under which the action of 'sending' should be fired. Otherwise drupal will not know when to send out an email – and to whom.

I suppose you have a look at the Rules Module (https://www.drupal.org/project/rules). It might first look quite complex, but basically it consists of these three main elements you have to configure to add a new Rule to your webpage: Event, Condition and Action. With that you can automate almost everything, especially sending reminder-emails etc. – and most probably you can also trigger Email Auto login.


How to disable a permission for a moderator role which is granted to an authenticated user?

Your key challenge is to get around what seems to be a contradiction, which is that a user with role "moderator" is, by design of Drupal, also an authenticated user.

By using the Rules module, it is possible to implement something that looks like restricting access to URLs that start with node/add, and this for one or more selected role(s). So you could use this as a kind of workaround, as further detailed below.

To "add content to a site" (as in your question), a user needs to enter such URLs (starting with node/add) to actually start doing so (or click some link that matches with such URLs). By "redirecting" those URLs for users with a specific role you can implement what you're asking for.

Here is a rule (in Rules export format) which should be pretty close to implement such access restrictions like you're asking for:

{ "rules_limit_access_to_node_add_urls_" : {
    "LABEL" : "Limit access to URLs to add nodes",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "4" : "4" } }
        }
      },
      { "text_matches" : {
          "text" : [ "site:current-page:path" ],
          "match" : "\/node\/add",
          "operation" : "starts"
        }
      }
    ],
    "DO" : [
      { "redirect" : { "url" : "no_access" } },
      { "drupal_message" : {
          "message" : "You are not allowed to use such path...",
          "type" : "warning"
        }
      }
    ]
  }
}

The above rule performs a redirect for users who have a role with role id = "4". Just adapt that role id to fit your moderator role (if needed) and import (using the Rules UI) the above rule and you should be good to go.


Convert link from node/nid to Pathauto url?

I would, as Splat mentioned, check out the Global Redirect module, which will help out with google not seeing node/FOO and pretty/path pointing to identical content.  If, however you are wanting to make sure that when engines scan your page content and pretty/path shows up inside the HTML, you can either continue to hardcode the paths, or create a function that returns the aliased path based on the nid.

function make_my_path($nid) {
  $pretty_path=drupal_get_path_alias('node/' . $nid);
  return $pretty_path;
}

Then use that (or drupal_get_path_alias() directly) in your templates or preprocess functions, or just use l().  If it is passed 'node/FOO' as the path, it will return the aliased path if one is set. (Unless you explicitly tell it not to; see url().)

So, for example, print l('Hello World','node/23'); should return Hello World.


How to disable sortable headers in Admin theme tables

Found the answer by reading this fine article

https://knackforge.com/blog/karalmax/drupal-7-creating-drupal-style-tables-paging-sorting-and-filter

"If you do not want a particular column to be sortable, do not specify the 'field' parameter for its header."

My headers array is now simply

   $headers = array(
      array('data' => 'UID'),
      array('data' => 'Username'),
      array('data' => 'Given Name'),
      array('data' => 'Family Name'),
      array('data' => 'Email Address')
    );

with no 'field' value specified, and the clickable headers have disappeared.


How to trigger / launch a colorbox programatically?

Install colorbox module. Read its README.txt to find out how to build links for loading inline and iframe content in a colorbox.

Set the id #cbox_trigger_on_page_load for your link and place it somewhere in your page and hide it with CSS.

If you are loading inline content, place the content in a block and hide the block too with CSS.

The mechanics of how to place the hidden colorbox link on the right page is not really what the question is about, is it?

So, lets stick with how to trigger the colorbox.

/**
 * Implements hook_preprocess_html();
 */
function MYMODULE_preprocess_html(&$variables) {
  // The overlay content from the site in an iframe should have cbox_overlay
  // as first path argument.
  // i.e. http:/mywebsite.com/cbox_overlay/content-title.

  // This will prevent a triggering loop.
  $is_cbox_overlay = FALSE;
  if (arg(0) == 'cbox_overlay') {
    $is_cbox_overlay = TRUE;
  }

  $settings = array(
    'is_cbox_overlay' => $is_cbox_overlay,
  );
  drupal_add_js(array('MYMODULE' => $settings), array('type' => 'setting'));

  drupal_add_js(drupal_get_path('module', 'MYMODULE') . '/js/colorbox_onpageload.js', array(
    // Making sure our JQuery code runs after colorbox's.
    'scope' => 'footer',
    'weight' => '15'
  ));
}

In the /js/colorbox_onpageload.js file:

(function ($) {
  Drupal.behaviors.MYMODULE = {
    attach: function (context, settings) {
      if (!settings.MYMODULE.is_cbox_overlay && $('#cbox_trigger_on_page_load').length) {
        $('#cbox_trigger_on_page_load')[0].click();
      }
    }

};})(jQuery);


Using group and rules modules to automatically create group for new user

You didn't mention any errors, but for starters your group name should be:

test group {{ user.uid }}


how to apply two themes for an element in custom module?

**
* Implements hook_theme().
*
* Defines the theming capabilities provided by this module.
*/
function YOURMODULENAME_theme() {

  return array(
    'THEMENAME1' => array(
    'template' => 'PATHTOTEMPLATEFILE',
       // EXAMPLE URL FOR ABOVE - 'templates/mymodulename--event--list-item',
       // This will make the module look for mymodulename--event--list-item.tpl.php
       // in the template folder within the module's directory
    'variables' => array(
      'SOMEVARIABLETOPASSTOTHETEMPLATE' => NULL,
      'ANOTHERVARIABLETOPASSTOTHETEMPLATE' => NULL,
      ),
    ),
  ),

}

Then when you have to return the content for the block or page, just call this function:

$output = theme("THEMENAME1", array('SOMEVARIABLETOPASSTOTHETEMPLATE' => "this is the variable that gets passed to the tpl", 'ANOTHERVARIABLETOPASSTOTHETEMPLATE' => "Another variable that is being passed to the template"));
return $output; // You could also just return the theme function above

Now, within your mymodulename--event--list-item.tpl.php file (Or whatever you named it) you can print any of the variables that you defined above.

<div class="somemarkup">
  <?php print $SOMEVARIABLETOPAsStOTHETEMPLATE; ?>
</div>


The module Special menu items lets you create menu items that aren't links.

Using Taxonomy doesn't seem like it would do anything to solve this, unless you want a different list of links to show depending on what node it's being displayed on.

So basically you just create a new Menu and add menu items you want in the list. A Block showing the list is automatically created for each new Menu, so you just have to go to Block configuration and place it in a region of your theme to make it appear. On Block configuration you'll also be able to restrict which pages to display the links on, maybe just the one node.

The thing you asked about using NID is concerning Path aliases. You can use the module Global redirect to make the system always output the alias instead of the NID link. With Pathauto you can configure patterns to automatically create path aliases when creating new content.