How to move custom code into template.php

First off, don't use 'und'. You should use field_get_items(). This is a change from D6, which is likely why you can't use those articles as a reference.

Secondly, you are using = and not ==, so you're assigning the value instead of comparing it.

So, you can probably just do the following:

function THEMENAME_preprocess_node(&$variables) {
  THEMENAME_field_division_helper($variables);
}

function THEMENAME_preprocess_page(&$variables) {
  THEMENAME_field_division_helper($variables);
}

function THEMENAME_field_division_helper(&$variables) {
  if ($node = $variables['node']) {
    $field_division = field_get_items('node', $node, 'field_division');
    if ($field_division[0]['tid'] == 1) {
      $variables['cta'] = $GLOBALS['base_url'].'/node/6';
    }
    else if ($field_division[0]['tid'] == 2) {
      $variables['cta'] = $GLOBALS['base_url'].'/node/6';
    }
  }
}

And then in your node.tpl.php and page.tpl.php file,

<?php if (isset($cta)): ?>
  <div class="some-wrapper">
    <?php print $cta; ?>
  </div>
<?php endif; ?>


How to get field values of a just created (or not yet) node?

All that I needed to do was using

$node = node_load($nid, null, true);

instead of just

$node = node_load($nid);

and now the node is loading as expected.


Tried to create a custom page template for my home page and now get a 404 error

I figured out the answer. I needed to install the Panels module so that I could use it as a variant. And that allowed me to set my home page template the way I needed it to be. Sorry for any confusion I may have caused with my question. And thanks for the help!


Call a JS function when a views ajax request completes?

You can find ahah/ajax success by this function.

Not a Drupal Way.

$(document).ready( function () {
 $('body').bind('ajaxSuccess', function(data, status, xhr) {
  alert('Ajax Success');
 });
});

This function will get invoked on every ajax success.


small php script used in drupal module not clear with arrays in php

In your first section of code, that function is creating a form using Drupal's Form API and $form['beeps'] contains the settings for a single form element, in this case a textfield.

The second function is the one is used to validate the form values and will display an error for any unacceptable value.

$beeps = $form_state['values']['beeps'] fills the variable $beeps with the value of the "beeps" textfield from the form generated in the first function.


Change the submit function for user login

Is you module named mymodule? The prefix of the hooks has to be the same as the machine readable name of your module. After checking that, try clearing the cache. After that, is should work because the code looks all right.


Can you override a library per environment?

Look at hook_page_attachments. In the sample snippet provided behind that link there is a simple if-request which attaches a certain library only when a certain condition is met. Do the same.

MYTHEME/MYMODULE.libraries.yml

foo-bar-dev:
  version: 0.0.x
  js:
    js/foo-dev.js: {}
foo-bar-prod:
  version: 0.0.x
  js:
    js/foo-prod.js: {}

MYTHEME.theme/MYMODULE.module

function MYTHEME/MYMODULE_page_attachments(array &$attachments) {

  // Conditionally attach an asset to the page.
  if (\Drupal::request()->getHost() == 'example.com') {
    $attachments['#attached']['library'][] = 'MYTHEME/MYMODULE/foo-bar-prod';
  }
  else {
    $attachments['#attached']['library'][] = 'MYTHEME/MYMODULE/foo-bar-dev';
  }
}

More info on base URL: how to get base url of a site?.


PDOException: SQLSTATE[40001]: Serialization failure: 1213 Deadlock found when trying to get lock;

This is a known issue in drupal 7.x core and has been resolved in the latest release (see this bug report for more information). Make sure you've upgraded to the latest version of Drupal 7, or try applying the patch if you need to get your site operational.


Display Taxonomy Field vs Default Taxonomy text w/out New modules

Ok... so following all of the steps above, I was able to cobble together what I wanted.

In template.php I have a custom function:

THEMENAME_field__CONTENT_TYPE($variables)

Inside this function, I check for $variables['element']['#field_name'] in a switch statement. IF the switch statement equals the field that has the taxonomy reference (i.e., 'field_faction_affiliation') then I do the following:

case 'field_faction_affiliation':
    $base_path = base_path();
    $faction_icon_href = $base_path . $variables['element'][0]['#href'];
    $faction_icon_title = $variables['element'][0]['#title'];
    $faction_icon_url = file_create_url($variables['element']['#object']->field_faction_affiliation['und'][0]['taxonomy_term']->field_faction_icon['und'][0]['uri']);
    $output = "";
    return $output;
    break;

I'm almost 100% certain that the base_path hobble I did is NOT drupal 'Best Practices' so if anyone has a suggestion for correcting that, please let me know. Otherwise. This is how I got what I wanted.


How to show translated taxonomy terms in term listing in content listing style

Yes, it kind of is a bug.

The page is I think one of the the only two lists (the other is comments) that is hardcoded and not a view.

Views have configurable behavior to show show the entity in the best translation, or show the default translation.

You can replace this list with a view yourself, just create a view that lists terms on that path. Views doesn't support a few features of that UI however, specifically, that is the drag and drop hierarchy and weight handling. if you don't need that, fine. If you do, you might need to look for contrib modules that offer such features, I'm not sure if there are some for Drupal 8.


Overriding permissions of existing page blocks all users

Is there any special reason that you're using 'taxonomy/term/%' instead of 'taxonomy/term/%taxonomy_term' in your implementation of hook_menu_alter()? If not, I would change that and clear the cache, see if it helps.

Edit...Here's a code example from the Term Per Role module:

function term_per_role_menu_alter(&$items) {
  $path = 'taxonomy/term/%taxonomy_term';
  if (isset($items[$path])) {
    $items[$path]['page arguments'] = array_merge($items[$path]['page arguments'], array($items[$path]['page callback']));
    $items[$path]['page callback'] = 'term_per_role_taxonomy_term_page';
  }
}

(A module which I would have recommended but the last commit on the project was over 3 years ago.)


how to remove element from node__product__type.tpl.php commerce kickstart

If you want to remove both the class and the label, 'tshirt size:', you don't have to do it via code. You can use the "Display settings" of the product and make the label hidden. ie, Go to content type -> Manage Display -> Node and select hidden for the size label.


Try this

$form['call-to-actions-widget']['internal_link']['#states'] = [
  'visible' => [
    ':input[name="call-to-actions-widget_select"]' => ['value' => 'internal_link'],
  ],
];

In case when it doesn't work use another selector

':input[name="call-to-actions-widget[call-to-actions-widget_select]"]'

Or check in the browser name of the needed field. See e.g. where the name is password[pass1]


Using hook_page_alter to move node render items into blocks

Well this ended up being a real pain in the bum - but ultimately got it solved. There may be a cleaner way of shifting the content so please comment if it could be done better.

I'll start by answering the question, then I'll try to go through what I think was going on under the hood to exacerbate the problem(s).

The answer is to use hook_page_build() instead of hook_page_alter(). hook_page_build() doesn't trigger from template.php so you need to build a custom module.

MYMODULE.module simply contains:

<?php
/**
 * Implements hook_page_build()
 */
function MYMODULE_page_build(&$page) {
  $node = menu_get_object();
  if($node && $node->type == "imagegallery") {
    // edit only imagegallery nodes
    $page['sidebar_first']['thumbs'] = array(
      'content' => $page['content']['system_main']['nodes'][$node->nid]['field_image'],
      '#prefix' => '
',
      '#suffix' => '
',
    );
    unset($page['content']['system_main']['nodes'][$node->nid]['field_image']);
  }
}

And that's all there is to it.

Now to go through the various 'gotchas!'.

$page['content']['system_main']['nodes'][$node->nid]['#node']->field_image is not $page['content']['system_main']['nodes'][$node->nid]['field_image']! This took a freaking day to find. Using devel_themer I kept on inspecting the node-level elements rather than the block-level elements. No matter what I did ['#node']->field_image stayed where it was but I think that #node is just a reference of what was generated and isn't even ultimately rendered. Once I found that ['nodes'][$node->nid]['field_image'] was the render element for the thumbnails it was down-hill from that point. Lesson learned: Even if you find what you think is the actual render element keep checking up the tree.

hook_page_alter() is great if you are ALTERING existing content but not great if you are moving stuff around. By that I mean if you have content in a region and you just want to clean stuff up then fine, use hook_page_alter. But one of the problems I had was that I had no existing content in the sidebar_first region so by moving things across using this hook, the system already thought that sidebar_first was empty. So while it placed the content where the region should have been, it didn't actually render the region itself. This really screwed up my page display. I'm guessing that Drupal builds the page elements during hook_page_build(), then works out what is what as far as the regions it is going to render out, then allows final altering during hook_page_alter() for the absolute last-step tweaking before render() is run. By using hook_page_build() the system then knew that the sidebar_first region was active.

It also took a little while to figure out hook_page_build() didn't trigger from template.php. I should have started with a debug message in there to test that as well.


Not sure if that works in all cases, but in mine - I managed to enable shipping form this way:

go to Home >> Administration >> Commerce >> Configuration >>
Order types >> Edit [your order type]
(/admin/commerce/config/order-types/[order_type]/edit/form-display)
select "Manage form display" there
find "Shipments" line there
switch it to Inline entity form - Complex

And instead of autocomplete for shipments I got form with edit button that allows me to change shipping address for order.

Order display settings screen:

Edit order page shipping block after update:


I found my answer.
Features creates a module that I need to import in the destination site.


The Best Answer module extends the 7.x-3.x version of the Answers module (disclosure: I'm a (co-)maintainer of it). However, this module has been integrated as a sub-module of the 7.x-4.x release of Answers. This release also has the new theming stuff (if you enable the brand new answers_theme sub-module) as in this sample screenprint of it:

Note the checkbox in the bottom-left of it (shown to the left of the accepted answer), which I believe is the equivalent of the best answer field that your question is about.

So unless you have good reasons to continue with the 7.x-3.x, I strongly recommend you to first upgrade to the 7.x-4.0-rc2 release of Answers, which might possibly obsolete what you're trying to achieve.

Even though the 7.x-4.x release is not yet an official release, it is fairly stable/functional, and only has a few more minor glitches to be resolved. The next release that will become available, will include the newest features as you can see in the demo site already. More important: if you're just starting with the module, you won't have to "migrate" from 3.x in the future (some type of migration will be needed, which is still an open issue for now).

Try the most recent 7.x-4.x release

To experience it yourself, try out a demo of it. Here are the steps to do so:

Head over to the demo site.
Just accept the defaults to create a sandbox demo site (make sure you're using the most recent 7.x-4.x release). Then hit the create sandbox button, and wait for the process to complete. Make sure you also enable the Answers Theme (sub-module of Answers, new as of 7.x-4.x).
Create at least 1 question using either the "Add content" menu link and then selecting "Question", or just enter relative path /node/add/question. And complete the title and body of the question.
After you save the question, you'll see the question that's created (in view mode). And below the question, you should see "No answers yet." (since you just completed posting the question). And then there is the "Your Answer" form right below that. That is the form you can use to post an answer to the question.
If you then use that (answer) form to post your answer, and also save that, the (first) answer is shown below the question, and below that answer there is now the "Your Answer" form again (to allow for posting an additional answer).
Use the Questions tab (or enter relative path /questions, to get a list (a tabular display) of all existing questions so far (there should be at least one if you completed the previous step).

Demo site

Have a look at the demo site of the Answers module. This link shows various menu options within the block with title Answers Menu, i.e.:

Questions (= a view):

All: of all existing questions (= default tab).
Answered: all questions which have a "best" (= accepted) answer (= sub-tab).
Unanswered: all questions which do not yet have a "best" (= accepted) answer (= sub-tab).

Answers (= a view): lists all existing answers for any of the existing questions and which does not (yet) have any submenu options (implemented as tabs).
Rankings (= a view): contains a list of users with their actual ranking (= reputation points implemented via user points), and with each user a link to either the questions or answers from that user.
Ask Question: to post a new question (the equivalent of node/add/question), which is only shown for authenticated users though.

These Views also use the dataTables format, but you could easily replace that with any views display format you'd want. And because of the search box that comes with dataTables, there is no need for extra menu links to search within questions, answers or rankings.

These new/enhanced views were created starting from the 7.x-4.x-rc2 release of Answers, and will be included in the next release of it also (together with various other enhancements not yet visible in the demo site).


You could use this in your theme:

function template_preprocess_input(&$variables) {
  $variables['attributes']['class'][] = 'your_class';
}

and maybe even check the type like:

function template_preprocess_input(&$variables) {
  if ($variables['attributes']['type'] == 'email') {
    $variables['attributes']['class'][] = 'your_class_email';
  }
}


The DBTNG Migrator module is in fact a great choice. I've used it very successfully.


Two module you can use to accomplish your requirement (1) entity reference and (2) node reference. Both directly added field to your content type as field which would be reference to another content type.

Select "entity reference" or "reference" in data type select of cck field.


Drupal places a  after text automatically?

I didn't see this problem before but maybe try to rewrite code above as follows:

<?php
//Drop Down Select
$sql = "SELECT user_id, concat (user_firstname,' ', user_surname) as username                       FROM   user_tbl WHERE coordinator='True'";
    $result = pg_query($sql);
         echo "Coordinator:<select name='user_id'>";
       while ($row = pg_fetch_array($result)) {
          echo  "<option value='" . $row['user_id'] . " '>" . $row['username']     ."</option>";
 }
         echo "</select>";
?>


How to put pager between multiple views?

IMHO, you might have to rethink your content architecture. The type of pager your are looking for ideally applies to content and not views.
drupal.org uses the book navigation that comes from the book module in Drupal 7 core.

If you do not want to use the book module, you could also go with the Nodequeue module, which provides a similar pager (except the middle link Up).

If you still really need to add such pager to connect the views, you can do it by adding the markup to the view footer to link to other views (and theme it as per the design). Or to make it dynamic, implement hook_views_pre_view (or any similar hook) and change the link from from the footer. Note: This however, is very hard to maintain and not recommended.


You can use Style Settings in the field setting and and use replacement tokens as a css class.


How do I get the UUID for a current logged in user?

You can load the UUID from entities with the method uuid(). If you have an account from the current user service then you have to load the user entity first:

$account = User::load($account->id());
$uuid = $account->uuid();


Here is a simple solution to scroll to top of the views results using jquery scrollTop

THEMENAME/js/views-scroll-top.js

(function ($, Drupal) {
  Drupal.behaviors.viewsScrollTop = {
    attach: function (context, settings) {
      //var scrollto = ".view-content"; // top of results
      var scrollto = ".view-filters"; // top of filters
      var url = window.location.href.split('?');
      if (url.length > 1 && $(scrollto).length) {
        $("html, body").animate({ scrollTop: $(scrollto).offset().top }, "slow");
      }
    }
  };
})(jQuery, Drupal);

THEMENAME/THEMENAME.libraries.yml

views-scroll-top:
  js:
    js/views-scroll-top.js: {}

THEMENAME/THEMENAME.theme

function THEMENAME_preprocess_page(&$variables) {
  // attach library only on specific view
  $route_name = \Drupal::routeMatch()->getRouteName();
  if ($route_name === "view.article.page_1") {
    $variables['#attached']['library'][] = 'THEMENAME/views-scroll-top';
  }
}

Change THEMENAME to your theme's name


The User registration form in drupal 7 site

change the "Country status" of the user's field for country to "both" or enable all country you want


How to redirect toward a specific node from front-page in Drupal 7?

page--front.tpl.php simply allows you to create a different page template than the default page.tpl.php template. When drupal loads the homepage and there is a page--front.tpl.php it will laod that template instead.

If you want to check if you are on the homepage you can use the is_front variable. It would be best to use hook_boot in a custom module.

hook_boot(&$vars) {
  if($vars['is_front']) {
    // do your redirect
  }
}

You can use drupal_goto() to handle the redirect.


Drupal 7 Views filter between start and end date

This module should do exactly what you need: https://www.drupal.org/project/views_between_dates_filter


You can achieve your requirement by installing and configuring Taxonomy Image module.

  The taxonomy_image module allows site administrators to associate
  images with taxonomy terms. With the association created, an admin can
  then make a call to 'taxonomy_image_display()' from their theme or
  other PHP code to display the appropriate image.

Please follow this link as well.


Is it possible to alter the behavior of the Ajax pager?

The way I fixed this was to take advantage of the way the Drupal/jQuery script for the "Views PHP" module's Ajax loading is working:

It looks for elements in the DOM with such structure : ul.pager > li > a
it listens to a click event and calculates the data to be retrieved based on the "href" tag.
It operates its magic on the DOM.

My tweak is to modify line 8 of the "ajax_view.js" file so it also looks for ul.pager > li > span elements. Then, I add a hook in my theme's "template.php" file with the following code:

function THEME_pager($variables) {
  $output = "";
  $items = array();
  $tags = $variables['tags'];
  $element = $variables['element'];
  $parameters = $variables['parameters'];
  $quantity = $variables['quantity'];

  global $pager_page_array, $pager_total;

  $pager_middle = ceil($quantity / 2);
  $pager_current = $pager_page_array[$element] + 1;
  $pager_first = $pager_current - $pager_middle + 1;
  $pager_last = $pager_current + $quantity - $pager_middle;
  $pager_max = $pager_total[$element];

  $i = $pager_first;
  if ($pager_last > $pager_max) {
    $i = $i + ($pager_max - $pager_last);
    $pager_last = $pager_max;
  }
  if ($i <= 0) {
    $pager_last = $pager_last + (1 - $i);
    $i = 1;
  }
  $li_previous = ($pager_current > 1) ? '' . (isset($tags[1]) ? $tags[1] : t('previous')) . '' : NULL;
  $li_next = ($pager_current < $pager_max) ? '' . (isset($tags[3]) ? $tags[3] : t('next')) . '' : NULL;
  if ($pager_total[$element] > 1) {
    if ($li_previous) {
      $items[] = array(
        'class' => array('prev'),
        'data' => $li_previous,
      );
    }
    if ($i != $pager_max) {
      if ($i > 1) {
        $items[] = array(
          'class' => array('pager-ellipsis', 'disabled'),
          'data' => '…',
        );
      }
      for (; $i <= $pager_last && $i <= $pager_max; $i++) {
        if ($i < $pager_current) {
          $items[] = array(
            'data' => '' . $i . ''
          );
        }
        if ($i == $pager_current) {
          $items[] = array(
            'class' => array('active'),
            'data' => l($i, '#', array('fragment' => '', 'external' => TRUE)),
          );
        }
        if ($i > $pager_current) {
          $items[] = array(
            'data' => '' . $i . ''
            );
        }
      }
      if ($i < $pager_max) {
        $items[] = array(
          'class' => array('pager-ellipsis', 'disabled'),
          'data' => '…',
        );
      }
    }
    if ($li_next) {
      $items[] = array(
        'class' => array('next'),
        'data' => $li_next,
      );
    }
    return '
' . theme('item_list', array(
      'items' => $items,
      'attributes' => array('class' => array('pagination')),
    )) . '
';
  }
  return $output;
}

It works perfectly for my usage.

Note : I know a "href" tag is technically illegal in a "span" element, but I didn't want to dig too deep in Drupal's JS ;)

~Stéphane


Configure the link click count module
Add new field in content type and set 'count the click happened on the link' in manage display
Use the default link click count stats view
In sort criteria, add the link node id and chooose the you wanted order.

whenever you click the field in the node, It will be get counted
The sorted result based on the click of the link will be shown in the view's result


Parsing XML files to populate form fields

I suggest you use the Feeds module. (I believe you may need to also read up on its SimplePie integration to help with the XML.)

Basically, it provides you with the form and functionality for importing, storing, and reading your XML file. It is also designed to create a node using the info read from the XML file.

If you don't want a new node, then you can interrupt the process using hook_feeds_presave to work with the info that Feeds has read from the uploaded file. (For example, to load and populate a form with the imported info. I'm looking into doing just that, myself.)

If you didn't want to use Feeds, then read up on the File interface and File API, which let you work with the uploaded file, store it temporarily, read data from it, etc. I've found that very useful.


Unfortunately not; an EntityFieldQuery is just an interface to a normal SQL query.

All values for computed fields are determined after the data has been loaded from the database (in the _computed_field_compute_value() function) so this won't be possible using the TableSort extender.


Applied JS to Drupal theme doesn't work correctly, but it works fine outside Drupal

}(jQuery));

should be

})(jQuery);

in your last line of code.


How to display list of nodes that share the same Parent taxonomy term as current node

Yes, add a relationship for the taxonomy field and the parent contextual filter will be available.


What is replacement of SSL/HTTPS in drupal to encrypt login credentials

Save yourself the headache and use TLS/SSL. Drupal won't, and isn't meant to, solve your problem. It isn't worth trying to cobble something together. If the cost of the certificate is an issue, go to https://letsencrypt.org/ and get a free cert.


drupal_add_js() does not add .js file from libraries folder

That seems apply to your issue :

  This problem occurs because the path to library is often incorrectly
  set as

libraries\colorbox\jquery.colorbox-min.js

  The solution should be to correct the path. You need to place the
  whole Colorbox plugin directory after unpacking it in
  sites/all/libraries This means the path should look like

sites/all/libraries/colorbox/colorbox/jquery.colorbox-min.js

Source


I found the answer in the webform.module file:

/**
 * Return the access token for a submission.
 *
 * @param object $submission
 *   The submission object.
 *
 * @return string
 *   The access token for the submission.
 */
function webform_get_submission_access_token($submission) {
  return md5($submission->submitted . $submission->sid . drupal_get_private_key());
}

So it's an MD5 hash of a concatenation of the submission date, submission ID and a random private key, set by the webform module.


How to export the contents of nodes in a view

The module I use for this is http://drupal.org/project/views_data_export

You create a new style and attach it to your existing page/pane, you can export:

CSV
Microsoft XLS
Microsoft DOC
Basic TXT
XML


Pathauto module doesn't have to do anything with this view. I think you are not supplying any default value to contextual filters used in your block type of view.

For creating the related content view, please try following steps

Create a Block type of display.

Add Contextual filter for the taxonomy term -> goto settings of this filter -> select "default value" -> select "taxonomy term id from url" -> select limit by vocabulary -> select "vocabulary" -> select appropriate option from "Multiple-value handling" -> expand "more" fieldset and set allow multiple values.
Enable Aggregation settings, and add the same taxonomy field in sort criteria and from aggregation settings select "COUNT DISTINCT"
Add "Nid" as contextual filter -> go to settings -> select "default value" -> select "Content Id from URL" -> From "more" fieldset -> select "Exclude" - now results will not show the current node.

Place this block now on your node page, and this block will list all the related content.


Adding target _blank to ajax form based on response

I believe the answer is, you can't.  Pop-up blocking is intended to prevent the browser from opening a new window or tab when the action was not initiated by the user (they click on a link).  There are several ways to open a new window or tab; however, unless you can truly trick the browser into thinking the user actually clicked it (no, $(a).click() will not fool it) or the user has pop-up blocking turned off, you will always have the pop-up blocker doing it's intended duty.

I'm sure you're advising the user that you intend to open another window for them, why not just provide the link upon successful form submission? Alternatively, you can do a delayed redirect such as is often seen on, I believe, phpBB login screens (the ones that say, "Thank you for logging in.  You will be redirected to XXX in 5 seconds").


Show block only in user own page and for administrator role users

This is almost a replica of your code with a small change. I hope it helps.

If you want to allow the admin to see the block on every other user profile page

global $user;
if (arg(0) == 'user' && ($user->uid == arg(1) || in_array('administrator', ($user->roles))) && arg(2) == "my-isn10") {
  return TRUE;
}
else {
  return FALSE;
}

If admin or normal user do not have a difference both can see only on their profile page.

global $user;
if (arg(0) == 'user' && $user->uid == arg(1) && arg(2) == "my-page" ) {
  return TRUE;
}
else {
  return FALSE;
}


How to filter the view2 fields and show by clicking on view1 node

Step 1)

I added a Entity Reference field called 111 to my Content Type

Step 2)

In view1 in RELATIONSHIPS click Add

in search type ref
select Entity Reference: Referenced Entity

Step 3)

In FIELDS click add, select File Usage: Entity ID.

Under Relationship, select your entity reference
check mark exclude from display.
Thousand Marker, select none

Step 4)

Move your title field below the File Usage: Entity ID field.

Step 5)

Click on your Title field.

Uncheck link this title to the original piece of content
Under Rewrite results, checkmark output this field as a link
link path: /view2/[id]

Save view1

Open View 2

Step 1)

Add a Contextual Filter of File Usage: Entity ID (Do the same as picture below)

Step 2)

In RELATIONSHIPS click Add

in search type ref
select Entity Reference: Referenced Entity

Step 3)

Change the page path settings to /view2/%

DONE :)


Display Suite and Views - how to troubleshoot why a View content pane is not being applied?

Unless I'm missing something I think you might be confusing the functionality of Display Suite with that of Panels.  Views content pane displays can be accessed from the Panels UI and added to a page but I've never seen that functionality within Display Suite.  Are you using any additional modules to add this functionality?

There's various ways you can do this but a really quick and easy approach is to use EVA.  Here is it's project page description.

  "Eva" is short for "Entity Views Attachment;" it provides a Views display plugin that allows the output of a View to be attached to the content of any Drupal entity. The body of a node or comment, the profile of a user account, or the listing page for a Taxonomy term are all examples of entity content.

  The placement of the view in the entity's content can be reordered on the "Field Display" administration page for that entity, like other fields added using the Field UI module.

  In addition, the unique ID of the entity the view is attached to -- as well as any tokens generated from that entity -- can be passed in as arguments to the view. For example, you might make a View that displays posts with an 'Author ID' argument, then use Eva to attach the view to the User entity type. When a user profile is displayed, the User's ID will be passed in as the argument to the view magically.

  That's right: magically.

Basically, create an EVA variant of your view, there's a couple of settings to say what entity type (node) and bundle (Guitar lesson) to attache it to.  save this and go to the manage display page of your content type and the view will be there.

It will work with Display suite turned on or off.


How to display a block view on demand triggered by clicking content of another view?

A link just takes you to a different page. Since blocks are associated to pages, you just need to link to a page to which the block is associated.

Linking to the same page that should then show the block is not possible, since blocks appear right when the page is shown. There isn't a way to delay the block appearing on pages.


Tabledrag in grid shape for media form field widget thumbnails

Plup seems a good place to start altough it looks abandoned.

Additionally there is this wiki page for comparison of similar modules.


Fetching and rendering custom-library generated blocks in twig

I render my custom library blocks like this:

{{drupal_entity('block', 'block_id')}}

So you have to search your block at your library and use this block's machine name where i say block_id.
Hope it helps.


AFAIK there are no modules that provide the functionality of 1), 2) & 3) out of the box.

There is an awesome module Comment Permissions that can help you achieve better customization of comment permissions than Drupal core provides. You can take it as an example and expand the functionality that it already has to suit your needs.

  The Comment Permissions module enables control of commenting by user
  role and by node type. Additional user permissions for selected node
  types are added to the user access system so you can configure
  commenting with more control than Drupal core provides.

Permissions provided by module (accessible via Permissions page & can be configured for each content type):

administer comment settings on any page content
administer comment settings on own page content
comment on any page content
comment without approval on any page content
comment without approval on own page content
edit own comments on page content

Hope this helps.


Display blog posts from Wordpress to my Drupal site and filter it by taxonomy terms

This is a bit complicated. You'll need to fetch the data somehow from WordPress and make it Drupal data. Fortunately, there's the Feeds module that can help you getting data from your WordPress and transforming it into Drupal nodes. You'll need to configure the Feeds to also parse WordPress categories and create taxonomy terms from it.

I recommend you to read the Feeds documentation before start using it.


I want to save data using ajax. But AJAX callback function replace method not working ? why?

Fun issue here.  I pulled your code out and stuffed it into a test module and the ajax appeared to work once, eg, on first click of the ADD button, it replaced the
foo</foo> I had also stuffed into my page.tpl.php.  But then each successive click put up the throbber without any further apparent change.  Throwing a watchdog() into the callback showed it was indeed being called upon each click and then the voila moment:

return '
count value is:' . $prod_1 . '
';

is needed because it was replacing the original
 with just the count value is.... text, and then when clicked again, the DOM no longer contained a #countvalue for it to replace again :)


Unfortunately as far as I am aware, Drupal cannot do this out of the box. However, you can use the Special menu items module to create a new menu item, and place "nolink" in the path settings.


Have a look at Steven Ward's site for a bit of a hacky way to do what you're looking for.


Passing an array stdClass Object from custom module to template

I don't know why it was not working because after I've done a simple

    {{ dump(myvariable) }}

In order to check if the array was passed to the twig template, everything is working.

So the solution is in my-template.html.twig

{% for key, value in myvariable %}
    Key : {{ key }}

    Date: {{ value.dateDebut }}

    Societe : {{ value.societe }}

{% endfor %}


Flush cache in case of WSOD without Drush on shared host

I get used to using Drush, especially when Drupal 8 website
  encountered an unexpected error, without this option I don't see the
  way how to clear the cache without UI.

Run www.mysite.com/update.php. This clears the cache, even when no updates are to run.

If you don't have access set $settings['update_free_access'] = TRUE; temporarily in settings.php.


How do I change the position of "sidebar first" for the Arabic version of website?

Install the Context module.

  Context allows you to manage contextual conditions and reactions for
  different portions of your site. You can think of each context as
  representing a "section" of your site. For each context, you can
  choose the conditions that trigger this context to be active and
  choose different aspects of Drupal that should react to this active
  context.

Make sure that Multilingual select which is part of the Internationalization module is also installed (this will provide the proper condition).

You can now create a new context that has a condition of 'Language' and a reaction of 'Blocks'.

You will create a condition-reaction pair for two cases. First for all the LTR languages, second for all the RTL languages.

Allthough this does not directly answer your question as to regions, you can play around with the reactions, such as template suggestions etc to achieve your objective.


How do I set cron using performance page?

Please go to Cron Settings (http://example.com/drupal7/admin/config/system/cron) to set it, default is 3 hours.


Is there any way to reset a node's properties?

In your theme folder you can override the default output using custom template files.
Let's say you want to modify the output of a standard 'Page' (the machine name for this content type is 'page' -- you can check it in /?q=admin/structure/types).
Go to your theme folder (under /sites/all/themes) and add/modify 'node--page.tpl.php' file.
A standard node template file will have something like:

<?php print render($title_prefix); ?>
<?php if (!$page): ?>
<h2<?php print $title_attributes; ?>>
  <a href="<?php print $node_url; ?>"><?php print $title; ?>

<?php endif; ?>
<?php print render($title_suffix); ?>

This piece of code is used to show the title of the current content. You can delete (or comment) the entire code and your title won't appear when you display this page.
To hide the entire content (including custom fields attached to this content type) simply comment (or delete) this line:

print render($content);

After that, you can add your custom code to display anything in place of the original title (or content) for this page.

You can find an extensive tutorial on working with custom themes here: Theming Guide


The Video module supports storing videos on Amazon S3. Restricting node access can be done by creating a special content type for your videos and only giving view access for that content type to a role that you assign to some users, possibly by using the Content Access module.


What happened to array-shift.com (Drupal Stackoverflow Clone)

What "happened" is what commonly happens to an idea that is generally solid but not (yet) popular: it's not being used and therefore not being actively maintained.

The best way to combat "disuse" is to use it. Create your own sandbox copy and start improving it. Ask Eaton for permission to take over the module and he'll give it to you.


Comments only showing subject, no comment

I found the solution and it was pretty obviously now that I found it. In content type --> Edit --> Comment Display --> The Comment field was hidden! DUH!! :)


Force native taxonomy-term pages to only show  and not all content

You can override the default listing with the built-in view, see here https://drupal.stackexchange.com/a/165052/3218

To only show the title you then need to adapt the view:

go to the view's edit page (admin/structure/views/view/taxonomy_term/edit)
change the format-display from rendered entity, to fields
remove all fields and add the title field as only field


The problem is that the old version of Drush is still in your $PATH, and comes before the new version.

The Drush installation instructions says:

Now add Drush to your system path by placing export PATH="$HOME/.composer/vendor/bin:$PATH" into your ~/.bash_profile (Mac OS users) or into your ~/.bashrc (Linux users).

What it does not mention is that changes to your .bashrc file are not immediately reflected in your running system.  You need do one of:

Restart.
Close and re-open all of your terminal windows.
Type source ~/.bashrc in all of your open terminal windows.

(Listed in order from easiest and most disruptive, to more work but less disruptive.)  Substitute .bash_profile in place of .bashrc if you made your modification there.


Programmatically change redirect after logout

hook_user_logout() doesn't expect a redirect response object and won't respond to it.

One alternative here, if you don't need a programmatic forcing of redirection, is to use the destination query parameter. The path supplied in the parameter will be redirected to upon logout. For example: http://example.com/user/logout?destination=user/login will return a user to the login page following logout.


Dynamically prepend or append a path element to content urls?

The hooks that can actually change the links used from Drupal are hook_url_inbound_alter() and hook_url_outbound_alter().
I have never used them to alter a link basing on the URL of the currently viewed page, but in the case of hook_url_outbound_alter() that should not be difficult, as it would require to use arg(); in hook_url_inbound_alter(), it would be more difficult, since you would need to be able to understand in which cases you happened a string to the URL. If the added part comes from a vocabulary of taxonomy terms, that would be probably easier, hoping that the taxonomy terms don't cause any conflict with enabled modules.

Appending the term at the end of the URL would avoid conflicts. It would also be easier to understand when a URL has been modified from your module.


Aegir+ Ubercart + Freetrial + ARB. Not working

While this question is now 6 years old, the way to go about this nowadays is via Aegir Site Subscriptions, which isn't quite ready yet, but is on the way.  So far, there's code for Recurly, but no other recurring billers.


How do I change the content text programmatically?

This value is defined in the comment_form function. More specifically, it is the description in this section:

  // Add author e-mail and homepage fields depending on the current user.
  $form['author']['mail'] = array(
    '#type' => 'textfield',
    '#title' => t('E-mail'),
    '#default_value' => $comment->mail,
    '#required' => (!$user->uid && $anonymous_contact == COMMENT_ANONYMOUS_MUST_CONTACT),
    '#maxlength' => 64,
    '#size' => 30,
    '#description' => t('The content of this field is kept private and will not be shown publicly.'),
    '#access' => $is_admin || (!$user->uid && $anonymous_contact != COMMENT_ANONYMOUS_MAYNOT_CONTACT),
  );

You could create a custom module and implement hook_form_FORM_ID_alter. Your custom module file would contain below lines in a .module file and a basic .info file.

<?php

function MODULENAME_form_comment_form_alter(&$form, &$form_state, $form_id) {
  $form['author']['mail']['#description'] = t('E-mail address will not be shown publicly.');
}

Alternatively there are some options for overriding strings outlined here: Drupal 6 & 7 - Change default strings (text) without using full translation system


Pass data from a hook to (be used in another hook)

You can't, there's no mechanism to pass data from one arbitrary function to another (which is what two separate hooks essentially are). You'll have to make the data available another way.

Drupal uses a pattern like this all over the place:

function MYMODULE_get_data() {
  $data = &drupal_static(__FUNCTION__, NULL);

  if (!$data) {
    $data = some_function_to_build_data();
  }

  return $data;
}

function MYMODULE_commerce_cart_order_refresh(...) {
  // Get the data, populating it if it doesn't already exist.
  $data = MYMODULE_get_data();
}

function MYMODULE_form_alter(...) {
  // Retrieve the data.
  $data = MYMODULE_get_data();
}

That's a contrived example, it'll make more sense when you plug your own requirements into it.


Your best option for remote images is the Filefield Sources module, however this will not provide the ability to manually create the thumbnail, medium, large, etc versions.

You can achieve auto-creation with image-styles and preset the dimensions or criteria that you would like for the "cropped/smaller" versions.

Lastly, if you want manual creation of those files you would have to create a new field for each version and have them pre-cropped/sized, and paste in the url from the CDN.


Entityfrom spam protection module without captcha

You may be looking for Hidden CAPTCHA.

Even though you need the CAPTCHA module for this, Hidden CAPTCHA module will not display any captcha field and you don't absolutely need to have a human enter a text, number, etc.


How to add to index unpublished content by apachesolr?

You may want to follow this thread: Index unpublished nodes. There is no available patch right now but you'll find some hints to build your own custom module if you need to.


Drupal gives error to admin, anonymous users can browse pages

The reason is that the error message only prints when an admin is logged in, you can disable that by going to Administer > Site configuration > Error reporting, anyway you can still fix the problem, by rebuilding your permissions, it mostly can cause by enabling permission dependent modules, like content access or something else.


how to select particular product from bunch of products

You could use the Rules module to react on a node save, check if the field has only one value and alter the values of the node as needed.

Or you can write your own module and use the form_set_value() function to change the submitted values in a (custom) validation function. Your validation function can be attached to the node edit form by implementing hook_form_FORM_ID_alter() and adding the function to the $form['#validate'] array.


In terms of performance, is it better to lazy load, inline, or hook_init a Javascript library?

You could also hook into the node's presave, check whether the body contains whatever it is, then set a flag on the node (perhaps using flag or taxonomy) if it does. Then on view, you look for the flag and use drupal_add_js if necessary. This will survive the cache and let you aggregate the script if you want to. If you'd prefer, rather than storing the flag in the DB, you can check for highcharts on every view (via hook_nodeapi()) and just add the JS there directly.

Btw, strongly recommend against the hook_init() approach - there are definitely better ways imho. hook_init is called on every full bootstrap, which includes eg. 404s and imagecache generation (as well as every normal node view). Generally it's a good idea not to use this if your code is only needed in specific circumstances (eg. only when there's Highcharts code embedded). In those situations, you want to find a way to add your code only to appropriate pages.


The best way to accomplish this is using hook_form_alter() with custom module. For example,

function your_module_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'user_register') {
    drupal_set_title(t('Create new account'));
  }
  elseif ($form_id == 'user_pass') {
    drupal_set_title(t('Request new password'));
  }
  elseif ($form_id == 'user_login') {
  drupal_set_title(t('Log in'));
  }
}


Where can I find complete documentation of hook_field_info?

The only documentation you find about those arguments is the one you already linked (hook_field_info()).
The reason that documentation is not very specific is that each field implemented from a module can use any value it needs. For example, the Image field implemented from the Image module uses the following keys for the settings (see image_field_info()):

uri_scheme
default_image

Vice versa, the Decimal field implemented from the Number module uses the following keys (see number_field_info()):

precision
scale
decimal_separator

The default formatter, and the default widget are (respectively) the machine name used for the default formatter, and the machine name of the default widget. The different between formatters, and widgets is that a formatter shows the value of the field, while a widget requests the values necessary for a field.

If you want to see which values are used from a field, you need to check the implementations of the following hooks done from the module implementing the field:

hook_field_info()
hook_field_widget_form()
hook_field_widget_info()
hook_field_formatter_info()


Why doesn't the token for the node title work?

[message:field_node_reference:entity:title] is not replaced with the node title because, for a example_create_comment message template, the field_node_reference field doesn't contain any valid node reference.

In fact, the Message example module uses the following code to return the value of the [message:node-title] token. (See message_example_tokens().)

    case 'node-title':
      if ($message->bundle() == 'example_create_comment') {
        $replacements[$original] = $message->field_comment_reference->entity->getCommentedEntity()->label();
      }
      else {
        $replacements[$original] = $message->field_node_reference->get(0)->entity->label();
      }
      break;

When the message bundle (the message template) is example_create_comment, it gets the node title using the field_comment_reference field ($message->field_comment_reference->entity->getCommentedEntity()->label()), not the field_node_reference field that is used for the other message templates.

The [message:field_node_reference:entity:title] token is added from the Token module, which adds a token for each field a content entity has. (Message is a content entity, and Message template is its bundle.) The Token module doesn't know if there is another field to use when the field_node_reference field doesn't contain any valid reference, so the token is not replaced.

If you want to get the node title in any case, you need to use the [message:node-title] token.


Create a view of users to show their profile visits

You can achieve this by simply creating a rule for profile clicks and add an action i.e. a counter that accepts +1 everytime the event occurs (Rules module).
To create a profile click action, all you need is the uid (user ID) which can be like this example.com/user?q=uid.
create a field in my accounts which stores this value and keep it hidden with display suite. In views, show the profile as fields and choose the uid and your recent field to display profile visits. Style it with css. sorry for bad english I am spanish


Views Conditional module, can help you.

  Views Conditional is a simple module that allows you to define
  conditionals (if xxx then yyy) with fields in views. Conditions
  include:

  Equal To Not Equal To Greater Than Less Than Empty Not Empty Views
  conditional allows you to output text based on the result of the
  condition.

Example screenshots

Added Fields in view

Views Conditional Field configuration


Why is my '#id' transformed into 'data-drupal-selector'?

It's intentional as @clive says. You can select it using jQuery or CSS of the this way:

div[data-drupal-selector=your-selector-id]

If you want to use a id you can declare like this:

$form['referent']['#attributes']['id'] = 'foo';


How to rename or choose twigs file name suggestions?

Given a block name of 'Custom Search form', you can add to the file name suggestions using a preprocess hook in your theme.

An example of code to add to the .theme file:

/**
 * Add an alternative to file name suggestions the Custom Search form block.
 *
 * Implements hook__suggestions_HOOK_alter().
 * @return array Suggestions.
*/
function mytheme_theme_suggestions_block_alter(array &$suggestions, array $variables) {
    if($variables['elements']['#id'] == 'customsearchform'){
        $suggestions[] = 'block__custom_search_form';
    }
}

This will result in an additional file name suggestion:

<!-- FILE NAME SUGGESTIONS:
   * block--custom-search-form.html.twig * block--customsearchform.html.twig
-->


Easiest way to make body of text wrap around image

Put the field before the text and apply a float class to the field.

.field-field-event-image {
float: left;
}


The Drupal process is Core -> Module -> Theme. Trying to work backwards on that route is bad design, and should be avoided at all costs. Modules should not be based on themes, nor should they have any dependencies on themes, as themes are entirely dependent on modules, and downstream of modules.

If you need to make changes based on theme, it should happen in the theme.

Example. In your module, define hook_theme()

function hook_theme($existing, $type, $theme, $path)
{
  return array
  (
    'my_theme_hook' => array
    (
      // the template will be in [MODULE_ROOT]/templates
      'path' => $path . '/templates',
      'template' => 'my-theme-hook', // leave off the .tpl.php
    ),
  );
}

The above defines a new theme hook called my_theme_hook, and the output of that theme hook is built in the template [MODULE_ROOT]/templates/my-theme-hook.tpl.php

Now you can use [MODULE_ROOT]/my-theme-hook.tpl.php, or even [MODULE_ROOT]/templates/my-theme-hook.tpl.php (this location works automatically for any templates). Clear your cache, and now the template in your theme will be used instead of the template in the module. Again, don't forget to clear your cache - the template will not be picked up until then.


Form processing issue while generating a dynamic form and preparing via API calls directly

I fixed it this way, it started to invoke form submit handlers.

function MODULE_init() {
    if (!empty($_POST) && $_POST['form_id'] == 'form_user_confirmation') {
        $form_state = form_state_defaults();
        $form_id = 'form_user_confirmation';
        drupal_build_form($form_id, $form_state);
    }
}


Create validation to input alphanumeric and with specified symbols for field type password in user module

You should use user_validate_current_pass().


How do I unpromoted existing node when new node is promoted to front page (Programatically)?

The settings for FrontPage is provided by default in Drupal 8. Because the Frontpage in Drupal 8 is a View, so it opens all kind of setting feasibility.

Hence if you go at Admin/structures/views you will find a view named FrontPage.

Hence, you just need to change the Pager setting. Change item 10 to item 1.

And in sort criteria It is already Content: Author on (desc), so it will automatically will show new item first. So as you publish new item it will replaced and you have set item 1 in pager, so only 1 item will be shown on front page which is latest one.


Create Drupal User when creating commerce customer

It is not a usual workflow to create customer profiles "by hand" even if the UI allows for this, the normal workflow would be when the user performs an action, the profile is generated, normally when they progress through the checkout process. At the end of the checkout, order, profiles and user are linked together in case of an anonymous purchase.

The same way you can't create a node and assign the author to an unexistant user, you can't create a customer profile and expect that the references appear magically.

Of course you can build a workflow that makes more sense to you and build a useful solution for your use case, one thing you could do is use Rules to generate a user every time you create an anonymous customer profile, but this will probably conflict with the normal checkout process as customer profiles are assigned to anonymous users when there's an anonymous purchase.

I'd create a boolean field attached to the customer profile that reads "Create a user for this profile" or similar and on the Entity creation event in rules, you can add an action that creates the user. You've got a very similar example in the default commerce Checkout rule "Create a new account for an anonymous order" for how to create an user.


How to get an generic image icon for image field type (like Generic File formatter for file field)

It seems this issue is being worked on at : #2568289: Not possible to reuse field formatters between entity_reference, file, and image fields
For now I've used the following code - included in the mytheme.theme file. (view mode custom_generic_file)
use Drupal\file\Plugin\Field\FieldType\FileItem;

/**
 * Implements hook_preprocess_field().
 */
  function mytheme_preprocess_field(&$variables, $hook) {
    __mytheme_preprocess_field__generic_download_icons_view_mode($variables, $hook);
  }

/**
 * Ensure generic icon view mode for image media entities.
 *
 * Image field type doesn't have a generic file formatter.
 *
 * Called by hook_preprocess_field().
 *
 * @see Drupal\file\Plugin\Field\FieldFormatter\GenericFileFormatter::viewElements()
 * @see https://www.drupal.org/project/drupal/issues/2568289
 */
   function __mytheme_preprocess_field__generic_download_icons_view_mode(&$variables, $hook) {
  if (isset($variables['entity_type'])
    && ($variables['entity_type'] == 'media')
    && isset($variables['field_type'])
    && ($variables['field_type'] == 'image')
    && isset($variables['element']['#view_mode'])
    && ($variables['element']['#view_mode'] == 'custom_generic_file')) {

    foreach ($variables['items'] as $key => $item) {
      /* @var Drupal\image\Plugin\Field\FieldType\ImageItem */
      if (isset($item['content']['#item']) && $item['content']['#item'] instanceof FileItem) {
        /** @var \Drupal\Core\Entity\Plugin\DataType\EntityReference $entityReference */
        $entityReference = $item['content']['#item']->get('entity');
        /** @var \Drupal\Core\Entity\Plugin\DataType\EntityAdapter $entityAdapter */
        $entityAdapter = $entityReference->getTarget();
        /** @var \Drupal\Core\Entity\EntityInterface $file */
        /** @var \Drupal\file\Entity\File $file */
        $file = $entityAdapter->getValue();
        $item['content'] = [
          '#theme' => 'file_link',
          '#file' => $file,
          '#description' => NULL,
          '#cache' => [
            'tags' => $file->getCacheTags(),
          ],
        ];
        // Replace for real.
        $variables['items'][$key]['content'] = $item['content'];
      }
    }
  }
}


Composer updates .htaccess file when updating

"extra": {
   "drupal-scaffold": {
       "source": "http://cgit.drupalcode.org/drupal/plain/{path}?h={version}",
       "excludes": [ ".htaccess", "robots.txt" ]
       }
}

Put this above code in your composer.json file.


How to create a chart using an uploaded CSV file as input?

You might want to use the Google Chart API module with Views integration. Here is a post that might help you - Add Charts To Your Drupal Site. It uses the Node Import module to create a node of statistics by way of importing a CSV file.


In-place editor buttons in footer missing

Did you enable Node template in page manager? -> /admin/structure/pages
That should make the toolbar appear.


How can I replace the Forum's vocabulary 'Forums' with my existing vocabulary 'tags'?

After you enable the D7 core Forum module, you'll also have a "Forum topic" content type (and a "Forums" vocabulary as shown via admin/structure/taxonomy/forums).

Using the "Manage fields" tab of this content type (located at /admin/structure/types/manage/forum/fields), you can see the various fields for this content type. One of its fields is the "Forums" field (with machine name "taxonomy_forums"), with "Term Reference" as Field type.

Click the "Term Reference" link of the "Forums" field there, which brings you to /admin/structure/types/manage/forum/fields/taxonomy_forums/field-settings, where you can change its "Field settings".

There you will be able to change the (default) "Forums" vocabulary to (e.g) your existing "Tags" vocabulary (or any other vocabulary you have defined).

Attention: if on the "Field settings" screen the Vocabulary drop down is disabled (= you cannot select another vocabulary, as in the screenprint in the "PS" of the question), and you get an error message like "There is data for this field in the database. The field settings can no longer be changed.", then you'll have to think of a way to get around it somehow. A few more links that provide some more details on this (and possibly other alternatives):

Support issue ( = Error on changing field type: "There is data for this field in the database. The field settings can no longer be changed.").
Support request nr 1378894 ( = modifying "Field settings" with data in database).

Be careful when trying to get this fixed! Because things may get worse ...
You might consider a possible approach like this:

Create a new term reference Field for the Forum topic content type, and for which you then select the desired taxonomy.
After that, it should be OK to "delete" the original taxonomy_forums (machine name) field.

However, in doing so, the new term reference Field will have a machine name starting with a prefix field_. But if you then try to use that field (as part of the Forum module functionality), the Forum module might not use such  field_ prefix (you might get errors about that mismatch).

An alternative approach might be to uninstall/reinstall the Forum module, and then check if after enable you can change the taxonomy term field. However, in doing so, be aware that the taxonomy term "General discussion" of the taxonomy "Forums" (used by the module) is NOT deleted as part of the uninstall of the module. So before re-install (enable), you may want to try to manually delete that term and taxonomy first. If you don't do that, then you might end up with a taxonomy term like "General discussion" multiple times.


First of all: This introduces redundant data into your DB. Generally this isn't a good idea.

If you must for some reason:

You can implement hook_node_presave for content type B. You get the fully populated $node. This gives you the possibility to load the referenced node type A and grab the value you want to set in B.

Maybe you want to consider to implement the same for content type A. This gives you the possibility to propagete this value every time it changes.


You'll find the settings to skip field settings under

  admin/config/media/file-settings


Empty response after a callback in form_alter

I have resolved.
Exposed form fields don't are the same of 'normal' form fields in drupal. I have applied the patch #46 listed here: http://drupal.org/node/1183418


How do I add a "Please select"/ "none" option to a required select input in a form?

As they explain in the documentation URL provided in your question you should add the #empty_option or #empty_value property to the render array of the select button.

#empty_option: (optional) The label to show for the first default option. By default, the label is automatically set to "- Select -" for a required field and "- None -" for an optional field.
#empty_value: (optional) The value for the first default option, which is used to determine whether the user submitted a value or not.

If #required is TRUE, this defaults to '' (an empty string).
If #required is not TRUE and this value isn't set, then no extra option is added to the select control, leaving the control in a slightly illogical state, because there's no way for the user to select nothing, since all user agents automatically preselect the first available option. But people are used to this being the behavior of select controls.
If #required is not TRUE and this value is set (most commonly to an empty string), then an extra option (see #empty_option above) representing a "non-selection" is added with this as its value.


How to programmatically determine whether a node is a og group type node?

I found a way to do this using og_get_group_ids() :

og_get_group_ids('node', array($nid));

If the result is not empty then the node is an og group type node.


Print module and missing breadcrumbs of Crumbs modules

It seems the router path for print/.. pages is always "print". See the print_menu() hook implementation in print.module.

You could write new Crumbs plugins for these paths (one for parent-finding, another for title-finding), with a logic somehow like this:

The parent path for "print/a/b/c" is "print/" + the parent path of "a/b/c".
The breadcrumb link title of "print/a/b/c" is the same as for "a/b/c".

The plugin could live in a custom module, or in the print module, or in the Crumbs module (patch welcome).

(This still needs some tinkering and experimentation. I'm afraid if I put it all into this answer, then I can as well just write the plugin myself and add it to the module - sorry..)


Any module or way to add line item in existing order?

It's available out of the box from commerce module...

See screenshot below of Edit Order


display views3 output at page--mypage.tpl.php


Commerce- How can I modify order details with hook_commerce_paypal_wps_order_form_data_alter()?

When you can not see the HTML output of debugging tools such as dpm(), you should use the utility function dd() instead. The logging data will be stored in a file called drupal_debug.txt which you can inspect later.


You use Workbench Access and a Roles per department and 1 Marketing Role to make this happen.

  Workbench Access creates editorial access controls based on
  hierarchies. It is an extensible system that supports structures
  created by other Drupal modules.

  When creating and editing content, users will be asked to place the
  content in an editorial section. Other users within that section or
  its parents will be able to edit the content. A user may be granted
  editorial rights to a section specific to his account or by his
  assigned role on the site.

So you place Finance Editors (a role) users in the finance section, and Finance Manager(s) in the finance section. And the Marketing role is assigned to the root level section (which implies all subsections -- and secretly adds that role to each section).

So prior to using the site you would have to assign each user into sections of the site, which Workbench has an Administration page for.

Workbench Access provides 2 means to define sections out of the box. A section can be a menu path, or Taxonomy terms. Additionally you can create your own section logic using the supplied API functions of the workbench suite.

Be aware that Workbench only works on Node based content (unless this has since changed since I last checked). So for instance you cannot create Messages and moderate them, messages are (custom) Entities.

EDIT:

I suggest seeing the official linked Documentation of Workbench Access and reading all the info and further 3rd party videos/documentation on that page.


Menu link that uses title from router item's title callback?

Menu links that are registered through hook_menu() do this already, so if you are using the system-provided menu link, it should pick up whatever you have altered "title callback" to be instead.

The system-provided 'user' menu link is being altered by user.module to prevent it from showing up to anonymous users (see user_menu_link_alter(), user_translated_menu_link_alter()). That might be getting in the way of what you want, in which case you could bypass/unset the user module implementation in a hook_module_implements_alter() function.

If you're using a custom menu link created through the UI, I don't believe you will be able to make that link title dynamic short of implementing hook_menu_link_alter() and hook_translated_menu_link_alter(). That's probably more work than intercepting it at the theme layer, though.


One-time URL to change a user's field value

Unfortunately Drupal requires that users reset their passwords when using the one time login link.

The easiest way to avoid that would be to use a module like URL Login, which generates login links for each of your users. There are a couple of modules which cater for similar use cases so you'll need to find out which one works best for you.

You can then use LogginToboggan to redirect your users to your custom page where they can edit the custom field. You may need to create a custom User Role depending on the need for access control.


How do I write a template file for a specific input field?

If you want to add a more specific template name to an input element use a theme name suggestions alter hook:

mytheme.theme

function mytheme_theme_suggestions_input_alter(&$suggestions, array $variables) {
  $element = $variables['element'];
  if ($element['#type'] == 'textfield' && strpos($element['#id'], 'edit-subject-') === 0) {
    $suggestions[] = 'input__textfield__subject';
  }
}

function mytheme_theme_suggestions_textarea_alter(&$suggestions, array $variables) {
  $element = $variables['element'];
  if (strpos($element['#id'], 'edit-comment-body-') === 0) {
    $suggestions[] = 'textarea__comment_body';
  }
}

You find more information here hook_theme_suggestions_HOOK_alter.

If you don't find the data you need in the elements variables, then you have to add it in the form build process, for example in a form alter hook. In this case the form build has already provided the necessary information in the element id.


The syntax error you are seeing implies that you are actually running php 5.3.  I can see that /usr/bin/php56 is version 5.6.22, but does $(which php) really point to /usr/bin/php56? Double-check your $PATH.


Rules scheduled email empty when using php variable, but not when hardcoded

Instead of scheduling a rule to execute and send an email with no context, you could use commerce_messages to create a message entity with all the data saved and then schedule the message_notify rule to send an email.

Messages: https://www.drupal.org/project/message

Commerce Message: https://www.drupal.org/project/commerce_message

Message Notify: https://www.drupal.org/project/message_notify


Try what I suggested here: Getting a field's value from an entity

Replace field_get_items('entityform', $entityform, 'field_myfieldname')

with

field_get_items('node', $node, 'field_myfieldname')


Product display and taxonomy term ID filter (with depth)

Clone the default view called "taxonomy term" and start from there.
Add a relationship to your product, and save.
Add fields as you like.


Is there a better way of getting specific pieces of data from taxonomy_term_load()?

The field_get_items() function is very useful for this sort of thing. It doesn't produce shorter code, but it's more structured and a lot easier to get your head round than the endless arrays of data:

// Get the items for a particular field
$field_items = field_get_items('taxonomy_term', $track_tax, 'field_track_icon');

// Get the first item (fields can have multiple items so field_get_items always returns an array)
$first_item = array_shift($field_items);

// Get the URI
$uri = $first_item['uri'];

Using that method has the added benefit of automatic language negotiation, so you can avoid having to get that from context or just relying on 'und'.

I should also say the use of this function isn't limited to taxonomy terms; you can use it to get field values for any type of entity.


How to offset only a subselection of a set of nodes in a view

Here is one approach.

Make a view that lists all articles, no filter on "promoted to front page"

Now sort first by "promoted to front page", descending (so promoted articles come first), then by post date (or what ever else you want)

Now  limit it to 6 items.

Clone the view (or block display)

Change the limit setting so there is an offset of 6 (if you cloned the block display) make sure you save the new setting only for the new block (an override)


Search through a specific field - Drupal 7

You could:

create a new separate view for searching across all nodes and display it in a block on the taxonomy term page, or
use solr search and set up facets (requires a lot of setup)


Radioactivity module. "how-to" most popular article in one day questions

According comparison of the Radioactivity results and a Analytics service, seems that 12 hours (in seconds) is the time needed to track 1 day.


Updating status through user_save() is a good way of doing it.

Also note that when you set status to a value different from 1, $op will get set to 'status_blocked', for which no email will be sent.


How to enable configuration translation on custom module

The problem as commented above is the type of the translatable properties on the schema. Needs to be changed from string to label also the translatable: false can be safely removed since is default behavior, and also no needed for label or text types.

For more information about config translation check the cheatsheet.


Entityform send email to entity referenced node email

Your rule should first use condition "Entity has field" on your entity reference field from the form -> the field where user selects businesses. In this case your form submission is the primary entity that your rule will target.

And then you'll have to loop through selected businesses and extract business email from each business that was selected by user in that form submission.

You can use components for getting email field out of your business entity or you can install "Conditional Rules" module (CR), which will allow you to write all the logic in rule's "actions" section without using components.

So your rule (if you installed CR) would be as follows:

Events: After saving a new entityform submission

Conditions: 1) Entity has field [entityform:field-select-business]

Actions:  Your actions will look something like this.

Loop: here you loop through your Entity Reference field -  [entityform:field-select-business]. You cannot loop through your Email field directly - every email is taken from refernced entity.

IF - here you will select conditional "Entity has field" Entity: [list-item], Field: [field_business_email] <- your email field. This brings email field into the rule's scope, otherwise your rule can't see the email field. This part is not possible to achieve in Actions section of a rule without "Conditional Rules" module.

And in the end - nest "Send Email" action under IF condition and you should be good to go.


Drupal System cron temporary file/folder error

For the reference, solving this issue is locating particular file under database table "file_managed" column "filename" and then manually deleting it.


How to edit fields' values in the hook_node_load function?

I'd go with entity_metadata_wrapper(), see this blog post for more info on that.

$node = node_load(323);
$wrapper = entity_metadata_wrapper('node', $node);
$wrapper->title = 'New title for the node';
$wrapper->save();

It works for any property: title, fields, author, etc.


No. An entity query always returns a list, if you want just one record, you have to get that from the array.

The intval() isn't really necessary though, Drupal/PHP doesn't care if you use the tid as string or integer. Also, it always returns an array, and key() also works on an empty array, so you can really simplify that to just return key($communie);. And I'd actually recommend to use current() or reset() because the key is the revision ID and the value the ID and while terms currently do not yet use revisions, they will likely soon support that.

So...

$commune = \Drupal::entityQuery('taxonomy_term')
  ->condition('field_zipcode', $postalCode)
  ->condition('vid', 'commune')
  ->execute();

return current($commune);

Is all you need.


How to style a byline field in an article content type?

It would be helpful to see the markup that surrounds the newsbyline field. I'm guessing there's a div or some other element around field_newsbyline that's a block element by default. If you change the CSS for that element to display: inline that may solve the problem.

Alternatively, if the above code is in your node template, you could adjust the markup in the field template instead:

Copying field.tpl.php from the base theme you're using or from Drupal core's /modules/field/theme/ into your theme
Rename it field--field-newsbyline.tpl.php (assuming field_newsbyline is the machine name of your field)
Edit that template to add <?php print t('By'); ?> in the appropriate spot.

By making the change in the field template, you should be able to get your code inside the wrapper div, rather than having it outside.


How can I detect a "page's" content type?

A few quick answers to your questions:

If you view source on any page, you should see a class name on the body element, something like: node-type-article. This is one way to see the content type. Also, if you edit a page, you'll see that the edit title will look something like this: Edit [content type] [title]
Alternatively, navigate to: [domain]/admin/content to see a list of all content, which includes the 'type' column
The "clone content" link content comes from a module called "node clone" https://www.drupal.org/project/node_clone, designed to allow in-place duplication of content (fields that should not be duplicated are reset to safe values)
There is another module that will allow you to export/import nodes between drupal installs: https://www.drupal.org/project/node_export It's probably not worth it to get into this unless you have quite a lot of content to move.


How to get product image URL from product page?

I have found a quick fix for this issue.

$product = commerce_product_load($productId); // loads the product by id
$productImage = drupal_json_encode(file_create_url($product->field_images['und'][0]['uri'])); // gets the main image of the product if it has multiple images and formats the link properly


You could potentially add a "data comparison" condition to your existing discount rule that would effectively do this:

current-user:order:line-items:0:commerce_product:id != product:id

Which would say "only continue if the first line item's product id isn't the same as this product id" but would totally fail if you had some other line item added to your cart before your first product. If that is the case, then you would need to create a custom rules condition.


Do you have control over your array structure?

Why not just change it to this:

[
  0 => ['alt' => 'alt text', 'img' => 'image-path'],
  1 => ...?
]

Because then your logic would work, but right now you have the reversed structure. What you could do is loop over the image paths with {% for key, path in gallery_images.img %} and use the key toaccess gallery_iamges.alt[key]` (not 100% sure about the exact syntax). Certainly more complicated that way.


In case it helps anyone else, I believe I was running into memory limit issues in PHP. Adding the following to my sites/default/settings.php seems to have resolved the issue:

ini_set('memory_limit', '128M');


Display a code snippet based on a taxonomy term

The value you're looking for would be stored like so

$content["field_authors_type"]["#items"][0]["tid"]

You could, if you wanted to be tidier, put this if statement in your theme's template.php in a template_preprocess_node or template_preprocess_page function (more on that here: https://api.drupal.org/api/drupal/modules%21node%21node.module/function/template_preprocess_node/7.x).

You would store your boolean value $variables['author_is_expert'] and then in your node.tpl.php, you can just use if ($author_is_expert)


The problem is solved by just using another hook

function mytheme_preprocess_links__language_block(&$variables)
{
    $variables['links']['en']['link']['#title'] = "ENG";
}

Thanks


How do I turn a select list into a radio button?

step 1 : choose the field type is  "list(text)".

step 2 : change the "Allowed number of values" as limited in Field settings

step 3 : change the "field widget" as Check boxes/radio buttons in Manage form display


How do I stop HTML entities appearing in an e-mail client's subject header?

you can use !responder and !title instead of @responder and @title in your code (by using ! instead @ or % it tells drupal to use the string as is ; by using @responder Drupal will run the string through check_plain to escape html characters).


How do I know what variables are available for a theme function?

The Devel module, and it's fantastic dpm() function, is the most widely used debug method for Drupal (at least I'm pretty sure it is).

It can be used on any variable, including arrays and objects, and will post a message to the standard message area containing a nicely structured representation of the variable. It looks something like this:

You would use it as simply as:

function mytheme_menu_block_wrapper__1($vars) {
  dpm($vars);
}

FYI I think all theme functions in Drupal 7 will receive at least one argument which will contain the data for that theme function. That argument is represented by $vars in the above example.

If you're looking to get hold of a list of variables that have been defined for the whole page request you might want to look at the PHP get_defined_vars() function instead.


Entityform: email submitted form to someone who is not admin?

go to admin/config/workflow/entity_rules/entityform_submission and clone "Entityform Notification Email Submitter" or "Entityform Notification Email Admin", edit accordingly. If that does not works, please add a custom rule (admin/config/workflow/rules):

event: After saving a new entityform submission
Condition: Entity has field: [entityform], Field: token of your field
Action: send email, use the token for your email field or any email you want.


How to assign ImageCache setting to an imagefield in content type

in order to work, imagecache relies on a tmp folder that needs to sit on your server. While developing local the tmp directory is located under the local webserver directory obviuosly and that needs to be changed when you go online. Administer » Site configuration - then file system is where you change it do a directory that is compatible with a server on your host. Setting the permissions to 777 then allowed imagecache to store the necessary image files and solved my issue.


I don't believe there is a really easy way to do this with d7 yet. Views bulk operations will probably be your best bet for the future, as there is work going on to provide this functionality (see: http://drupal.org/node/1142062).

In the meantime, vbo does work with the rules module, so it looks like it might be possible to use rules and vbo together to accomplish bulk taxonomy updates, although I don't think this is trivial. This screencast: http://vimeo.com/26884701 and this comment: http://drupal.org/node/1057158#comment-4792118 might help to get you started.


you are missing a hook_theme() function

see you defined a theme for your block by using:

$block['content'] = theme('coolmodule', array('myvar' => 'helloworld'));

but you never told it how to relate your theme with the template file, this work is done in hook_theme() function.

function coolmodule_theme() {
    $items['coolmodule'] = array(
        'template' => 'coolmodule',   // here comes your template name
        'render element' => 'content'
    );

    return $items;
}

Don't forget to clear your cache


How to make user profiles editable by site administrators

Yes, you can add the fields to the user entity at

admin/config/people/accounts/fields

While I think you can save the account form without updating the user password (don't enter a value for password when saving), if you want to move the password to a separate tab, you can use the module

password_tab


It really feels like there should be a better way to do this (but I can't find one at the moment, theme_menu_link() isn't context-aware of its parent menu); however this will work:

function MYMODULE_menu_tree(&$variables) {
  // Load the current HTML into a DOMDocument to count the links
  $doc = new DOMDocument;
  $doc->loadHTML('
' . $variables['tree'] . '
');

  // XPath query to find only top-level
s
  $xpath = new DOMXPath($doc);
  $lis = $xpath->query('//ul[@class="identifiable-string"]/li');

  // Get the count based on the number of elements returned
  $count = 0;
  if ($lis) {
    foreach ($lis as $li) {
      $count++;
    }
  }

  return '
' . $variables['tree'] . '
';
}

It seems like a huge amount of effort (not to mention processor power) for not much reward, but if you're struggling then this method will definitely work.


Set default form values after AJAX callback

I finally found a way to do this, though it appears this isn't the best way to do it - but it works.

You can not set #default_value for a field if the field is set in $form_state['input']['field_name'].

So before I try to set the field to the newly generated value, if I put this before then I can reset the default value.

unset($form_state['input']['registration_information'][$name][$subname]['field_name']);


I'm not sure I totally follow what you're trying to achieve, but Fivestar is a very flexible module

https://drupal.org/project/fivestar

I use it to vote for a few different content "dimensions" (2-3 votable fields) and then with views you can output it as a table with click sorting by any one of the ratings fields.


Writing a custom Rules Action for VBO- do I need to use Entity?

[I'm assuming you have a custom table to store these email addresses and are not related to any other entity]
With the latest version of VBO, yes, you have to define an Entity.
See this issue in the VBO queue for more information.

FYI, the below steps worked for me.

function module_entity_info() {
  return array(
    'MY_NEW_ENTITY_TYPE' => array(
      'label' => t('MY_NEW_ENTITY_TYPE'),
      'base table' => 'MY_NEW_TABLE',
      'entity keys' => array(
        'id' => 'your_tables_primary_key',
      ),
    ),
  );
}

Note that in entity keys array, set the table's column as the key, and VBO will pick it up and will pass as an object to the action. See below:

function module_action_info() {
  return array(
    'module_remove_something' => array(
      'type' => 'MY_NEW_ENTITY_TYPE',
      'label' => 'Remove URL',
      'configurable' => FALSE,
      'behavior' => array('deletes_property'),
    ),
  );
}

In your views integration file, you will probably need to define the tables as an entity too.

function mymodule_views_data() {
  $data['mymodule_emails'] = array(
    'table' => array(
      'base' => array(
        'field' => 'eeid',
        'title' => 'Extracted E-mails',
        'help' => 'Email addresses collected by parsing the remote URL',
      ),
      'group' => 'E-mail',
      'defaults' => array(
        'field' => 'email',
      ),
      'entity type' => 'MY_NEW_ENTITY_TYPE', // attention here!
    ),
   // Rest of the table definition...


To know what fields you have available to your View, you can use a custom module, and there you write the following:

function hook_views_pre_render(&$view) {
     if($view->name == "YOUR_VIEW_NAME"){
         foreach($view->result as $key => $r){
             echo "<pre>"; print_r($view->result[$key]); echo "</pre>";
     ....
         } // foreach
      } // if view->name
} // function


How do I resolve the "Argument 1 passed to drupal_attributes() must be an array" error on my system_settings_form()?

$items['admin/structure/types/manage/%/attach/images'] = array(
    'title' => 'Attach: Images',
    'page callback' => 'attach_images_settings',
    'access arguments' => array('access administration pages'),
    'weight' => '10',
    'type' => MENU_LOCAL_TASK,
);

This should be 'page callback' => 'drupal_get_form', 'page arguments' => array('attach_images_settings'). (don't forget to clean the cache after making the change)

Also, form callbacks in Drupal 7 have a mandatory $form argument.


How do I add custom CSS styles to the body field?

Use the "html inspector" of your browser (Ctr-Shift-I for Chrome) to find the the css classes of thoses fields.

Then add the proper css code in /themes/bartik/css/style.css.

That will be the quickest way to do it but I strongly recommend you to create a sub-theme of the bartik theme (https://drupal.org/node/225125) so if the theme gets updated, you won't loose your changes.

You should check out Display Suite too (https://drupal.org/project/ds), it a fantastique module to change the way nodes are displayed.


How to get the attachment display of a view to show up in a PDF display (created using Views PDF module)?

I never was able to get the Attachments to show up in the PDF, but here is my workaround:

I was able to get the output that I needed by using the Reference module and the Viewfield module.

Created Content type A and content types B, C, and D. B, C, and D are all associated with Content type A via Reference fields.
Created contextual/relationshipped views for B, C, and D, relating it to the title field of Content Type A.
Created a Viewfield on Content Type A for each of the sub-content types (B, C, and D).
Created a View for Content Type A, contextualized with Content:Title, and added the Viewfields to this new View (using reverse relationships with the node referenced field). I then added a PDF Page view using Views PDF, and that did the trick!

I can provide more detail if needed. Just let me know...


Having trouble understanding private files in Drupal 7

Whenever possible it's recommended that you choose a directory located
  outside of your Drupal root folder (or actually outside your web
  root), which may be tricky if you are on a shared host. If you do have
  access though, you can choose a private directory which will be on the
  same level as your web root directory (often called public_html or www
  or similar).

From Working with files in Drupal 7 and Drupal 8.

The best practice is to place your private files outside of your webroot, so they should not be inside /var/www as that would make them accessible over the web. Place them in /var/somefolder instead, make sure your webserver has read write access to that folder. After that you should only be able to access them via /system/files/test.example.doc and it should not work for anonymous users.

UPDATE:

Above is based on the assumption you were accessing the file via example.com/drupal-private-file-system/test.example.doc. this can be prevented by using the linked best practise guide.

If an anonymous user can access your files with on url like example.com/system/files/test.example.doc you have a problem with your permissions and anonymous users are given the permission to download private files.


In Drupal 8, contact forms are entities listed in admin/structure/contact. Once you created the new contact form, on that page select Manage fields in the Operations column; it's a drop-down selector, so you will need to select it to see that operation, since the default operation for contact forms you create is Edit.

On the page you will see, you can add new fields.

The tricky part is understanding how to show checkboxes: You need to select the right field type. For example, if you want to show 4 checkboxes, then you select Text (list) as field type.

Enter the 4 values you want to show, and enter 4 as Allowed number of values.

To show it as checkboxes, you go to the Manage form display of your contact form (in my case, admin/structure/contact/manage/test/form-display, since test is the machine name of the contact form I created). For the field you created, it should show the following.

Change it to Check boxes / radio buttons and save.

Since the allowed values are 4, the contact form will show checkboxes, not radio buttons.


How do I fix a ReflectionException error (class doesn't exist)?

It has to be the file structure.  Check again that it's at /modules/custom/mdm_user/src/Routing/RouteSubscriber.php

Also, in your class, you don't need to add the route again, it's passed by reference.

You can remove

$collection->add('user.login', $route);


Rendering a region in region--footer.tpl.php

as you wrote, you can override the region.tpl.php files, following the template name conventions - I would post a link, but drupal.org is down right now. A quick web search should get you to the right url and you can create a region specific tpl file.

you shouldn't try to render one region in another, but you can duplicate the code in both region files, or of course, you could also include the code in two blocks, one for each region


Have you looked at Geofield and Geocoder modules?

I believe you can configure the geofield as a field on your taxonomy to hold the Lat/Lng. Then, you can configure your geofield widget as Geocode from another field.

For batch back-filling, Geocoder provides the drush command:

geocoder-backfill     Geocodes all nodes that have a geocoder widget but no geodata.


How to solve the huge HTTPRL error that fills down all of Cron \ Status report?

The solution (or at least work around?) could be what is described in Comment # 8 of Issue # 2450725 related to the HTTP Parallel Request & Threading Library module:

change "'timeout' => 7," to "'timeout' => 1,"
This timeout is used in lock_acquire() that probably locks Drupal for 7 seconds, but in httprl config httprp waits only 5 seconds for a response.

Comment # 17 in that issue also contains a corresponding patch, which looks like so:
diff --git a/httprl.install b/httprl.install
index d7e2963..e2d4f04 100644
--- a/httprl.install
+++ b/httprl.install
@@ -177,7 +177,7 @@ function httprl_install_http_test($mode, $blocking = FALSE) {
       // Setup options array.
       'options' => array(
         'blocking' => $blocking,
-        'timeout' => 7,
+        'timeout' => 1,
         'max_redirects' => 0,
         'headers' => $headers,
       ),


In Drupal 8 type-hint $form_state with the FormStateInterface & do not pass it by reference:

hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id)

See hook_form_alter() for further reference.
I see some confusion on your usage of the $form_id / $form['#id']. Dump your $form_id in the hook & see which is the correct form you want to alter. Because as others have mentioned already: edit-field-gen-list is not your form id but your field_gen_list field id. For example: the form id of the contact Website feedback is contact_message_feedback_form.
Given the HTML in your question, your $form['field_gen_list']['widget']['#options'] will not have a key for 'all'. So adding that as default value will not work unless you add such a key value to the options array

So instead try this:

function project_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id)
{
    kint($form_id, 'Find correct form id');

    if ($form_id == 'contact_message_feedback_form') { // Change this

        // Add an 'all' key value option
        $form['field_gen_list']['widget']['#options']['all'] = '- All -';

        // Set newly added key 'all' as default value
        $form['field_gen_list']['widget']['#default_value'] = 'all';
    }

}


Go to admin/config/people/accounts, Under Emails click Account Activation and then change as per your requirement. Use html and css for customization. See the below image

(or)

Use the second option below:

All the emails are being sent from the system and the content is editable as we want. To stylize the emails, use html mail module http://drupal.org/project/htmlmail

This module allows you to theme emails leaving the system as you would theme a normal Drupal site, and replaces the outgoing emails with those HTML versions per your settings.

hope it helps you!!!


How to get the View Header and Footer in Custom Module?

Step1 - You will create two files header.php and footer.php.
Step2 - Create a folder "include" in your theme directory.
Step3 - Suppose that your theme directory is "abc" sites/all/themes/abc. Put header.php and footer.php file in "sites/all/themes/abc/include" theme folder.
Step3 - By using html and php you can write code in header.php and footer.php.
Step4 - Now you can include both files in page.tpl.php in header area and footer area like PHP.

  include_once($theme_path.'/include/header.php');
  include_once($theme_path.'/include/footer.php');

hope this will help


Basing on this comment by Damien Tournoud, the idea was to support arbitrary string identifiers.
Since Drupal uses a service to generate UUIDs, using a VARCHAR(128) as database field for the UUID would allow a module to override the current service with one using a different implementation, and using more bytes for the UUID.


Can I use drush to compare the running modules on two sites on the same server?

I don't know if there is a direct way, but this should work with bash or a similar shell. No idea about how to do that with Windows :) Please comment and I'll integrate it into the answer.

First, save the enabled modules of both sites into a textfield with this command:

drush pm-list --status=enabled > enabled_modules_site_x.txt

Then, you can easily compare the output of these two files with diff.

diff first_file second_file


Add / Remove column in admin/content/node

Of course you can modify this page by implementing hook_form_alter in your custom module.

But the best approach is using Views and VBO module create your own contant admin page with columns and filters that you need. Module Administration Views will help replace Drupal core admin page with your own.


Is there a way to supress particular messages or a class of messages on the screen?

You can use Disable Messages or look how they do it. Among other features you'll get a permission to specifically hide all messages of a given type from any role.

  Gives a site owner options to disable specific messages shown to end
  users. The core drupal message system as offered by drupal_set_message
  is an excellent way for modules to send out messages to the end users.
  However not all drupal site owners are keen to show all the messages
  sent out by drupal core and all modules to their users. This module
  gives site administrators a reasonably powerful way to filter out
  messages shown to the end users.

  Features

  Filter out messages that match a full text string exactly.
  Filter out messages that match a regular expression.
  Permissions to specifically hide all messages of a given type from any role.
  Disable all filtering for specific users.
  Disable all filtering for specific paths.
  Apply filtering only for specific paths.
  Debug system to get messages in the HTML without showing it to the end users.

Apart from that I found this little gem:

function MYMODULE_preprocess_status_messages(&$variables) {

  // The exact message you want to filter.
  $message = 'Further instructions have been sent to your e-mail address.';

  if (isset($_SESSION['messages'])) {
    foreach ($_SESSION['messages'] as $type => $messages) {

      // Limit it to a certain type if you want to.
      if ($type == 'status') {

        $pos = array_search($message, $messages);

        if ($pos !== FALSE) {
          unset($_SESSION['messages'][$type][$pos]);
        }
      }
    }
  }
}

Source: https://api.drupal.org/comment/51793#comment-51793

Here's another alternative to filter all messages of a certain type.

/**
 * Implements hook_page_build().
 */
function MYMODULE_page_build(&$page) {

  $hide_types = ['status', 'error', 'warning'];

  if (isset($_SESSION['messages'])) {
    foreach ($_SESSION['messages'] as $type => $messages) {
      if (in_array($type, $hide_types)) {
        unset($_SESSION['messages'][$type]);
      }
    }
  }
}

You could also easily get the $account = global $user and check its roles to tighten this request if you need.

Last but not least – not recommended - you can remove or if-wrap the <?php print $messages; ?> variable in your theme's page.tpl.php. But editing templates for this kind of logic should be considered bad practice.


In which step in the checkout process is an user account is created?

This happens in Commerce Checkout through Rules.

Rule commerce_checkout_order_convert will check the order's given mail against existing users and automatically assign it.
Rule commerce_checkout_new_account creates a new account if the mail given doesn't match a user.

See the rule "Create a new account for an anonymous order". It creates a new user based off of the mail provided by the anonymous user during checkout.


drupal_page_is_cacheable can also be used.

Calling:

drupal_page_is_cacheable(FALSE);

Should do the trick.

And for Drupal 8:

Drupal::service('page_cache_kill_switch')->trigger();