How to implement date filters with operators like = in a JSON query string?

OK, below is what appears to be the solution for it ... We need to pass the query string as follows (all string, sorry for the formatting ...):

  http://web.com/drupal/api[endpoint name]/chart(view service pathname).json?field_invoice_date_value[min][year]=2013&field_invoice_date_value[min][month]=12&field_invoice_date_value[min][day]=1&field_invoice_date_value[max][year]=2014&field_invoice_date_value[max][month]=1&field_invoice_date_value[max][day]=1

Things to notice in what is shown above:

No (more) <= or >= (can't use that in such JSON string).
Use notations like [min][month], [max][day], etc. instead (rather self explaining ... if you know about this syntax of course).

Done, works as designed ...


How do I assign a template to the user edit form?

To add an additional template level to a form, add the #theme key to the form array:

$form['#theme'] = ['bs_user_form'];

and in my_module.module:

/**
 * Implements hook_theme().
 */
function my_module_theme($existing, $type, $theme, $path) {
  return [
    'bs_user_form' => [
      'render element' => 'form',
      ],
  ];
}

The template name is then bs-user-form.html.twig, where you can print the form with {{ form }} or theme it like for example:

entity-moderation-form.html.twig

{{ form.current }}

{{ form.new_state }}

{{ form.revision_log }}

{{ form.submit }}

{{ form|without('current', 'new_state', 'revision_log', 'submit') }}

You can add theme suggestion to the theme name, but don't use form__ as base hook, because this is already used for the Form element, which caused the error.


The .htaccess files are ignored if the AllowOverride directive is set to None.


get all parent terms of a term using php - Notice: Array to string conversion

I think this is closer to what you want:

<?php
    //term id of term that you are checking for top parent
    $term_tid = '9';
    $parent_terms = taxonomy_get_parents_all($term_tid);

    //top parent term has no parents so find it out by checking if it has parents
    foreach ($parent_terms as $parent) {
      $parent_parents = taxonomy_get_parents_all($parent->tid);
      if (empty($parent_parents)) {
        //this is top parent term
        return $parent;
      }
    }
?>

Explanation:

You don't need the $top_parent_terms variable. You can return the first $parent you encounter that doesn't have a $parent_parent.
You were also probably having issues because you declare $top_parent_terms, but reference $top_parent_term (missing an 's').
Also, this bit $top_parent_term[] = $parent would produce a result like this:
$top_parent_term = array(0 => $parent) when you probably want $top_parent_term = $parent.
Note that the returned $parent variable will be an object, not an array. taxonomy_get_parents_all returns an array of term objects.


New VBO bulk operation button not get translated

Sharing a link below:-

http://www.drupalcontrib.org/api/drupal/contributions!views_bulk_operations!views_bulk_operations.api.php/function/hook_views_bulk_operations_form_alter/7

Here a function
function hook_views_bulk_operations_form_alter(&$form, &$form_state, $vbo) {
}
We can use this function and here we can actually do custom code for this particular action and set the label accordingly.

Would be able to answer more appropriately if you share some more details with your question that what you basically did.


How do I save a new field value for node without saving the node?

You could directly update the field table in the database ?

$database = \Drupal::database();
  $result = $database->query("UPDATE node__field_download_count SET field_download_count = field_download_count + 1  WHERE entity_id = " . $entity_id);


I found my answer, see:

dsm(entity_get_info());
dsm(field_info_bundles());

so my code should be:

$instance = array(
    'field_name' => 'field_image',
    'entity_type' => 'comment',
    'bundle' => 'comment_node_article',
    'label' => t('Images'),
    ....


Layering fields on top of each other in views

I find that the easiest and simplest solution is pure css. All you need to know, is the height of the box with text, then it's a simple matter of using margin-top: -?px; and creating a background with opacity. One option could be an image.


Using Date Popup widget with custom format Date field

Drupal's Date module includes a 'Date Popup' sub-module which handles date pop-up widgets. These widgets are available in the FAPI (form api) and can be configured with custom formats via the #date_format property.

You could implement hook_form_alter() and change the #date_format property on the date field you're working with. I believe this property will support all formatting available in PHP's standard date() function.


After looking a little deeper in the Drupal core I found out that in this case I shouldn't overwrite #theme, but use #theme_wrappers instead.
So my theme definition:
function mymodule_theme($existing, $type, $theme, $path) {
  return [
    'my_custom_fieldset' => [
      'render element' => 'children',
    ],
  ];
}

In my form:
$form['some_fieldset'] = [
  '#type'  => 'fieldset',
  '#title' => 'Some title',
  '#theme_wrappers' => ['my_custom_fieldset'],
];

$form['some_fieldset']['some_field1'] = [
  '#type' => 'textfield',
  '#title' => 'Some title',
];

$form['some_fieldset']['some_field2'] = [
  '#type' => 'textfield',
  '#title' => 'Another title',
];

And then my template my-custom-fieldset.html.twig:
<fieldset>{{children}}</fieldset>

Or for example:
<fieldset>
  {{ children.some_field1 }}
  Some customization here
  {{ children.some_field2 }}
  Something custom here
</fieldset>


How to move the Forena report parameters block further down and give it a separate heading?

Rendering of the report parameters input form

Forena's custom renderer FrxParameterForm allows you to customize various aspects of the rendering of the report parameters input form. More details about it can be found in the tutorial included with Forena, located at relative path reports/help.renderers#frxparameterform. Here is part of what it says:

  Use it on a div tag anywhere within the body part of your report to control various aspects of the rendering of the parameter form.

Here is a sample of how to use it within the body tag of your report:

  put your actual report parameters here ...

{submit}

  here goes the rest of your report specifications ...

Some more details about the above example (also from the same documentation):

frx:title: The title of the parameters field set.
frx:collapsible: Indicate if the form should be collapsible or not:

set to "1" to make the parameter form collapsible.
set to "0" for a parameter form that cannot be collapsed.

frx:collapsed: Indicate how a collapsible parameter form should be shown:

set to "1" for a collapsed form.
set to "0" for a not collapsed form.
The default behavior is to expand the form only if no data was returned by the report.

frx:submit: The label of the submit button.

Theming the report parameters input form

For the actual positioning of the parameter form, I suggest you use a custom (new) CSS file, by adding 1 line to the "skin" used in your report (which is either the default skin, or your custom skin). To do so, just add a line that looks like so (name the CSS file whatever fits):

stylesheets[all][] = custom_forena_styling.css

Within that CSS file, you could (eg) add this CSS coding to make the parameter form be shown to the very right of your page (I prefer to do so by showing it "collapsed" as detailed above):

/* Apply some styling to the parameters form */

#parameters-wrapper fieldset.collapsed {
  float: right;
}

More details about "Report Skins" can be found in the tutorial included with Forena, located at relative path /reports/help.skins, or in the demo site. An example that uses these skins is to enable dataTables (to enhance the display of tabular reports).

Summary

With that, it's up to your own imagination to make the parameter form of your report (or chart) fit your needs, ie:

using the custom renderer options.
add whatever xHTML tags you want.
style it using your custom CSS.

Disclosure: I'm a co-maintainer of Forena.


Overwrite twig (template) files from a contrib module in my custom subtheme?

Since you didn't clarify any specific module, i'll explain it with Paragraphs.

In the Paragraphs folder there is a folder called "templates", this will be the default template used by all fields that use paragraphs.

If you copy these templates and paste them into your own custom theme you can edit them as much as you like, using twig debug you can specify it per field.

Don't forget to clear your cache when editing!


As an addition, just in case someone runs into the same trouble as I did - when using the #markup or #prefix/#suffix trick on a form's actions group, the submit callback function won't be called at all, unless a submit type element is present. My workaround was like this:

$form['actions']['submit'] = array
(
    '#type' => 'submit',
    '#value' => '',
    '#attributes' => array( 'style' => array( 'display: none' )), // hide the input field
    '#submit' => array( 'my_callback_for_the_form_submit' ),
    '#prefix' => '<button type="submit" class="btn btn-primary">Add <i class="fa fa-plus-square-o">',
    '#suffix' => '</i></button>',
);

That way you can use custom HTML for submit action groups.


How to list all available reviews for coder?

The list will depend on which modules you have that implemented hook_reviews(); hook implementations return a keyed array that has the name of the review. These items are combined with a default list that come from the coder_review module.
The default list come from that dir is: upgrade47,   upgrade5x, upgrade6x, upgrade7x, upgrade8x, comment, druplart, i18n, i18n_po, production, security, sniffer, sql, style


You probably want to install Menu Attributes.

  The module currently allows you to set the following attributes for
  each menu item: Id, Name, Target, Rel, Class, Style, Accesskey


I can't save changes of settings of an Omega subtheme. Problem just happens in remote server

this thread may answer your question: http://drupal.org/node/1388196

for some it is a suPHP request.max_vars and  post.max_vars issue


Is the X-csrf-token only available for authenticated users?

Drupal still doesn't use CSRF tokens for anonymous users. The CSRF token is also checked only when a session is available for the currently logged-in user, and only when the request method declared from the route is not one of the following: GET, HEAD, OPTIONS, TRACE.
There are some issues opened for Drupal core, which (at the moment I write this answer) still have to be fixed for Drupal 9.1.x, such as Allow form tokens to be used on anonymous forms in some cases, CSRF check always fails for users without a session, and X-CSRF-Token request header is missing when using Bearer authentication (which needs the steps to reproduce it).
The only way to add CSRF tokens for anonymous users is creating a new service that duplicates almost all the code in CsrfRequestHeaderAccessCheck, possibly using a route requirement that is different from _csrf_request_header_token used from Drupal core, and add that route requirement to the routes of your module that needs to be accessible also from anonymous users. Such service should also create a session, if it has not been already created.
Keep in mind that CSRF tokens are requested for those routes that alter data (for example, a route that deletes data from the database). If the route is simply showing data, the CSRF token is not requested.


When to use drush_log() or drush_set_error()?

In general, you should avoid using the status code 'error' when calling drush_log directly. Use drush_log to signal non-terminal events, usually with a status code of warning or notice.

If a function fails and cannot continue, the best thing to do is to exit with return drush_set_error(...);. This sets internal state, so that Drush knows that there was an unrecoverable error, and calls through to drush_log('Message', 'error');.


What is the purpose of using node_submit() before node_save()?

node_submit() is a small helper function that makes sure the uid/author and creation date is set. Its main purpose is to map ->name to uid and ->date to created. Those two are used in the node edit/create form.

So if you set these two properties yourself anyway (and the validated flag but I haven't found anything that cares about it, likely some sort of left-over from earlier code), there is no need to call it.


How do I link to the homepage from a node?

You can just create a link to the path / (slash with nothing else).
That will take the user to the homepage.


Maybe you should try with different images. It works perfectly on my tablet and phone (both w8.1) you just can't drag it with your mouse, maybe thats why you tought it didn't work?


Which hooks should I implement in Drupal 7 that are the equivalent of hook_comment() and hook_nodeapi()?

I will reply to your question basing on the value for $op shown in your code snippet.
hook_nodeapi(), "insert"
The equivalent for Drupal 7 is hook_node_insert(), which receives just one parameter: $node.
hook_nodeapi(), "validate"
The equivalent for Drupal 7 is hook_node_validate(), which receives three parameters: $node, $form, &$form_state.
The implementations of hook_node_validate() don't usually use the last parameter, but they check the values of the properties for the $node object.
hook_comment(), "insert"
The equivalent of that hook, in Drupal 7, is hook_comment_insert(), which receives the comment object as unique parameter.
hook_comment(), "validate"
Unfortunately, in Drupal 7 there isn't hook_comment_validate(); you need to add a validation handler for the comment form.
function mymodule_form_comment_form_alter(&$form, &$form_state, $form_id) {
  $form['#validate'][] = 'mymodule_comment_validate';
}

function mymodule_comment_validate($form, &$form_state) {
  /**
   * Validate the comment.
   * $form_state['values']['name'] is the name of the user who wrote the comment;
   * $form_state['values']['is_anonymous'] is TRUE if the user is anonymous (not logged in);
   * $form_state['values']['mail'] is the email address of who wrote the comment;
   * $form_state['values']['homepage'] is the URL of the website of who wrote the comment;
   * $form_state['values']['subject'] is the title of the comment;
   * $form_state['values']['comment'] is the text of the comment;
   * $form_state['values']['language'] is the language associated with the comment;
   * $form_state['values']['uid'] is the user ID of who wrote the comment.
   * $form_state['comment'] is the comment object.
   */
}

Notice that mymodule_comment_validate() doesn't get any $comment parameter, and $form_state['comment'] is an object, not an array. You are using a $comment variable that is not defined, nor is one of the parameters.
The code I wrote works independently from the content type of the node where the comment appears. In Drupal 7, the hooks called to alter a form build from another module are hook_form_alter(), hook_form_BASE_FORM_ID_alter(), hook_form_FORM_ID_alter(). The base form ID for the comment form is "comment_form."
If you just need to alter the comment form for a specific content type (e.g. the "Article" content type), then you replace mymodule_form_comment_form_alter() with mymodule_form_comment_node_article_form_alter().


... Am I correct to understand that Group module does not allow content to exist in more than one group at a time ...

Yes that is correct, but you seem to not take into consideration that the Group module has the notion of Group Types, and when you create "a" Group, you have to specify which its Group type is (compare to creating nodes, which you can only do if you first specify the content type for that node).

Moreover, a user can:

have multiple levels of access (none, read, update) to some group (outsider, member, etc).
be member of multiple Groups.

  ...  and hence based on my requirement OG is the better choice?

That's a matter of preference (opinion based), e.g. if you prefer to go for D8, at this time, IMO, the Group module is way more stable ...

  Should I assume that OG 8.x-1.0-alpha2 is not stable enough to use for a production site, and that I should stick with OG 7.x-2.10 on Drupal7 for now, and wait on the benefits of Drupal8 until OG matures at least to RC1?

If you do decide to go for OG, then for the sake of stability, at this time, D7 seems to be the way to go.

Read more: What are the features of the Group module versus Organic Group module?


How do I include my library on the page?

So you defined a custom library that includes CSS and JavaScript. This is done by creating the ng.libraries.yml file and adding the base library definition.

Next, you need to tell Drupal to include this library and attach it to all the pages, if your ng theme is used for rendering the output. You can do so by adding a libraries section to your theme's ng.info.yml file:

libraries:
  - 'ng/base'

After clearing your caches, the library should be included.

Additionally, you may want to have a check for the syntax of the .libraries.yml file. CSS inclusion should follow the syntax:

css:
  theme:
    css/styles.09e76a721be8ced0c439.bundle.css: {}

Observe the theme part.

EDIT:

After you also added your html.html.twig template, another issue seems a missing js-bottom-placeholder tag. It will be replaced by any JavaScript that is not attached to the head region:

<js-bottom-placeholder token="{{ placeholder_token }}">


Using call_user_func_array on the db_select object

Breaking this down...

<?php
$x = call_user_func_array('db_select', array('watchdog', 'w'));
$x = call_user_func_array(array($x, 'fields'), array('w', array('wid')));
$x = call_user_func_array(array($x, 'orderBy'), array('wid', 'DESC'));
$x = call_user_func_array(array($x, 'range'), array(999, 1));
$x = call_user_func_array(array($x, 'execute'), array());
$min_row = call_user_func_array(array($x, 'fetchField'), array());
?>

In-lining everything... so it can be done.

<?php
$min_row = call_user_func_array(array(call_user_func_array(array(call_user_func_array(array(call_user_func_array(array(call_user_func_array(array(call_user_func_array('db_select', array('watchdog', 'w')), 'fields'), array('w', array('wid'))), 'orderBy'), array('wid', 'DESC')), 'range'), array(999, 1)), 'execute'), array()), 'fetchField'), array());
?>

---Solution below---

<?php
// Setup data array.
$args = array(
  array(
    'db_select', array(
      'watchdog', 'w',
    )
  ),
  array(
    'fields', array(
      'w', array('wid')
    )
  ),
  array(
    'orderBy', array(
      'wid', 'DESC'
    )
  ),
  array(
    'range', array(
      999, 1
    )
  ),
  array(
    'execute', array()
  ),
  array(
    'fetchField', array()
  ),
);

// Helper function.
foreach ($args as $data) {
  if (!isset($last)) {
    $last = call_user_func_array($data[0], $data[1]);
  }
  else {
    $last = call_user_func_array(array($last, $data[0]), $data[1]);
  }
}

// Get output
echo $last;
?>


How do I get a view of all flaggable nodes?

If these content types are never going to change, the quick and dirty would be to just create a View filtering on those content types.

If this is not the case, then you are going to have to get down into some coding as I am not aware of any built in Views/Flags integration on this level.  Sure, you can list all flagged or not flagged content, but I don't see a way to list flaggable content.

So, to get the node types, you should be able to do something like this:

$flag=flag_get_flag('NAME_OF_THE_FLAG');

and now

$types=$flag->types;

should be an array of node types this flag can be applied to.  So now you need to tell Views about this.

So, using the quick and dirty View created above, you could then alter it up with something along these lines:

function YOURMODULE_views_pre_view(&$view, &$display_id, &$args) {

  if ($view->name=='NAME_OF_THE_VIEW') {

    $flag=flag_get_flag('NAME_OF_THE_FLAG');

    $filters = $view->display_handler->get_option('filters');
    // you may want to dpm() or drupal_set_message() or watchdog() or otherwise look at $filter to see what you have to deal with on your system
    $filters['type']['value'] = $flag->types;

    $overrides = array();
    $overrides['filters'] = $filters;

    foreach ($overrides as $option => $definition) {
      $view->display_handler->override_option($option, $definition);
    }

  }

}

which on my box here, changes the types filtered to those in the flag.

Your $flag and $filters may/will most probably vary, so check to see what you have to work with as these are the broad strokes.

Lots of information about flags here: Flag 3.x PHP API

Information about Views hooks here:  Views Hooks


Add a new field to your content type:

Name: Pick a view
Type: boolean
Widget: [doesn't matter]

Then add this code to your block or node or page tpl.php file.

<?php

if ($node = menu_get_object()) {
  // Get the nid
  $nid = $node->nid;

$node = node_load($nid);
$wrapper = entity_metadata_wrapper('node', $node);
$field_value = $wrapper->field_pick_a_view->value();

if ($field_value == 1) {
  print views_embed_view('my_view', 'block_1');
  } else {
  print views_embed_view('my_view', 'block_2');
  }
}

?>

replace view_name with your view name
replace block_1 or block_2 with your machine name

So if your field is check-marked, it prints view 1. If it's not checked-marked, it prints view 2.


Make sure you're implementing the right Drupal API syntax which requires $form_state to be the reference to the original array, so it can be properly modified through certain hooks.

For example if you're using form_load_include() in hook_form_alter(), make sure you're following the right API syntax which is:

hook_form_alter(&$form, &$form_state, $form_id)

(note the &) otherwise form_load_include() can't perform alterations of your current state of the form ($form_state).


Can I use I18N or another module to house regional variations of a site in a single installation?

Af far as building and configuring such a project relying on Drupal multilingual features is a no-brainer, you should definitely go that way. Entering content in different languages has to be done either way, but with the multilingual setup, you don't have to repeat the work you do around the structure.

There probably is a very small number of special cases where not using multi-lingual features would be faster. Cases where you build one site, polish it, then just clone and do tiny adjustments for the other two languages. But the reality of web projects doesn't make it very probable that your project specs and necessary ongoing work will be so clearly defined to justify avoiding the multilingual setup.

Detection and Selection of Languages will allow you to choose URL as the detection method, and further in that configuration, you choose Domain (instead of the Path prefix) as the Part of the URL that determines language.

You'll have to do some planning around the menus, which ones you can share and translate, and whether you'll need to create some language-specific menus.

You'll be able to have language-specific paths, dates, other configuration... I found multilingual projects always take a lot more time to build than it seems, so don't underestimate it. It's not simply entering all the translated expressions into some interface and you're done. You have to learn about different places where to setup the structure for different languages etc. But in the end, it is faster to setup and maintain one site with multilingual features and translate it, than it is to build and maintain 3 separate ones.

Definitely learn about Hreflang for multilingual SEO, there's a link to Google support page explaining it there.


How to fix the useless 'favicon.ico page not found' log message?

It's not really a Drupal bug, but a browser bug (I think Firefox might be a culprit)

The best way I found to fix it is to put:

<Location /favicon.ico>
  ErrorDocument 404 "No favicon"
</Location>

This code should work in your vhost file or should also work in the .htaccess file, see http://httpd.apache.org/docs/2.4/sections.html for more details


As I commented on the question, this was a file permission problem..


Possible conflict with multiple jquery plugins

You can run two separate versions of jQuery, which is what your situation seems to require.

This module offers hope to an easy resolution . https://drupal.org/project/jqmulti

Otherwise this document offers more clarity: https://drupal.org/node/1058168

Generally speaking, you only need a single instance of jQuery installed on the server, which might be called from many different scripts scattered all over the place. However sometimes you'll have a requirement for jQuery more recent than your current stock-Drupal installation. This is when you want to run multiple jQuery versions (because you don't want to simply upgrade your single instance, which would break standard Drupal jQuery stuff like the admin-menu).

(function($){
    // your code here, using jQuery 1.7.1 setup w/ jqmulti module
    alert("jQuery version = " + $().jquery); //proves jquery version being used
})(jq171)


Check if user registration field is set to visible or hidden on the registration form

If you look at the code of user_register_form(), you will notice it uses the following code.

  foreach (field_info_instances('user', 'user') as $field_name => $instance) {
    if (empty($instance['settings']['user_register_form'])) {
      $form[$field_name]['#access'] = FALSE;
    }
  }

If you are implementing hook_form_alter() (or other similar hooks), it's quite easier to look at the #access property. If you need that in other functions, you can use code similar to the following one.

  foreach (field_info_instances('user', 'user') as $field_name => $instance) {
    if (empty($instance['settings']['user_register_form'])) {
      // $field_name is not supposed to be added to the account registration form.
    }
  }

Clearly, checking for the #access property in a hook_form_alter() implementation is the safer method, since it consider the field can be made accessible from third-party modules (or third-party modules can hide a field that should be visible).
The other method is more for getting a specific field setting.


Add classes to programmatically added fields

Do something like this to wrap this field in a DIV class --

...
    'background_color' => array(
        'field_name' => $fields['field_background_color']['field_name'],
        'label' => 'The stroke color',
        'bundle' => 'nji_map',
        'entity_type' => 'node',
        'attributes' =>array('class'=>array('minicolors')),
        'widget'      => array(
            'type'    => 'text_textfield',
        ),
        'settings' => array(
          'prefix' => '
',
          'suffix' => '
',
        ),
        'display' => array(
            'default' => array(
            'label' => 'above',
            'type' => 'text_textfield',
            ),
        ),
        'description' => 'The background color is the color between.',

    )....

You would notice I have added settings along with other properties of the instance, where we can add prefix, sufix, min, max etc. I hope it works..


Command pm-enable needs a higher bootstrap level to run

Is your settings.php file in sites/all/default?  If not, you'll need to add the --uri option.  If your settings.php file is in sites/all/foo.com, then add --uri=foo.com.

drush --uri=foo.com en seo_checklist

Or, change your working directory to the same folder that contains settings.php.

Or, define a site alias @foo that defines 'root' and 'uri', and then use:

drush @foo en seo_checklist


Secure Login

For sites that are available via both HTTP and HTTPS, Secure Login
module ensures that the user login and other forms are submitted
securely via HTTPS, thus preventing passwords and other private user
data from being transmitted in the clear. Secure Login module locks
down not just the user/login page but also any page containing the
user login block, and any other forms that you configure to be
secured.
For Drupal 7 and 8, Secure Login module enforces secure authenticated
session cookies, thus preventing session hijacking. For previous
versions of Drupal, PHP's session.cookie_secure flag must be enabled
on the HTTPS site to enforce secure session cookies.

Login Security

With Login Security module, a site administrator may protect and
restrict access by adding access control features to the login forms
(default login form in /user and the block called "login form block").
Enabling this module, a site administrator may
limit the number of invalid login attempts before blocking accounts,
or deny access by IP address, temporarily or permanently. A set of
notifications by email or Nagios may help the site administrator to
know when something is happening with the login form of their site:
password and account guessing, bruteforce login attempts or just
unexpected behaviour with the login operation.


There is no such setting unfortunately. There is a module for 7.x, but not 8.x port yet: https://www.drupal.org/project/watchdog_filtering.

You could use a different watchdog backend that supports filtering, or log to syslog or some other system that is better at dealing with a lot of log entries.

And if those notices/warnings are caused by PHP notices/warnings, then you should fix them.


How can I add jQuery to DOM element through drupal.behaviours?

Here's a skeleton of how you can add functionality to elements using Drupal.behaviors.

(function ($, Drupal) {
  'use strict';

  // Create a new function for each element the file attaches
  // handlers to. In this case, $(.secondary-action')
  function secondaryEventListener(context) {
    // Find the elements, ensure that any internal code is executed
    // a single time using $.once(), then loop through the found elements
    // using $.each()
    $(context).find('.secondary-action').once('secondary-event-listener').each(function () {
      // $(this) refers to the current instance of $('secondary-action')
      $(this).click(function () {
        alert("clicked");
      });
    });
  }

  Drupal.behaviors.someArbitraryButUniqueKey = {
    attach: function(context, settings) {
      // Call your function containing the handlers
      secondaryEventListener(context);
    }
  };
}(jQuery, Drupal));


How can I make the coupon code field in commerce mandatory?

You must do this in a hook_form_FORM_ID_alter().

You wouldn't use hook_form_alter() unless you are checking on a dynamic form ID. In this case it's better to use hook_form_FORM_ID_alter().

The reason for this, is that hook_form_alter() is called on every form render and hook_form_FORM_ID_alter() is only called when that specific form is being rendered.

Add this code to your .module file to make the field required:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MY_MODULE_form_commerce_checkout_form_checkout_alter(&$form, &$form_state, $form_id) {
  if (!empty($form['commerce_coupon']['coupon_code'])) {
    $form['commerce_coupon']['coupon_code']['#required'] = TRUE;
  }
}


how to prevent node revision update when node is updated?

@camcam, have in mind that even when you are not using revisions (keeping separate node revisions for each update you make to your node content), the revisions table will still always have one record in the node_revisions table associated for each record in the node table that it keeps track of.

On the other hand, if you have enabled revisioning, you will have multiple entries in your node_revision table associated with each node, corresponding, not just to the current revision, but all past revisions too.

My suggestion is to make sure you really want to mess with that functionality before you go ahead and do anything - because what you're seeing is actually standard behavior.  :-)

If you look at the code in node_save, you can see that a revision is created or updated in each instance of a node_save() call.

If this really doesn't work for you, I'd suggest using the hook_form() function to edit which function is called when your specific node content type is saved, and you can choose not to call the standard node_save() function (this should only be done if really necessary).  The api documentation, along with some code samples in the comments, can be found here: https://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook_form/7.


To do this, you need to create a *.libraries.yml file, with the path to your css file in it:

MODULE.libaries.yml:

star-field:
  version: Version
  css:
    theme:
      path/to/stylesheet.css: {}

Then you can attach that library to your element:

$element['#attached']['library'][] = MODULE/star-field;

This can be overridden in a theme if/when necessary, so this styling should be considered the default styling that the module creates.

More reading: https://www.drupal.org/docs/8/creating-custom-modules/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-module


Go to /admin/structure/menu/manage/main-menu and it can be deleted from there.


Set the default value for a password field on a custom form

I think you are choosing password type field. Like below  for password and confirm password fields.

'#type' => 'password',

Password does not support '#default_value' property. So fields getting cleared.


Form fields created via Ajax are missing element attributes

It seems like a good idea to invoke the callback in the form build to include the form elements of the callback in $form to allow the form builder to process these elements. But then you overwrite the same form elements that the form builder has processed with the unprocessed form elements when the ajax triggers the callback.

Solution: Move all form elements in buildForm(). Leave the callback empty, only return the wrapper part of the form.


How to display 12 grid for development purpose in bootstrap?

You could try adding a image of the grid as a css background image to the container class. This might fail if you are overriding it for any reason.

A more difficult way of achieving this would to try having a grid fixed position over your site that you can maybe toggle with JavaScript.


Permissions are stored per user role in roles yaml files.

You'll find the permissions for 'Authenticated User', for example, in user.role.authenticated.yml and for 'Administrator' in user.role.administrator.yml


Prevent page creation for a published custom content type

One easy method would be to add Rabbit Hole module and set it to "Page Not Found" when that content types view route is accessed.


If you choose "Node" as an active search module it will index the full node including taxonomy terms:

Here you can see the tag "bros" is returned in the core search:

Are you sure that the site is fully indexed?


Should I down-grade to Drupal 6.x? There seems to be much better support!

D6 is certainly an option, and will likely retain a sizable installed-base for some time to come.  That said, D7 is where the focus is, now, and will continue to be in the future.

In my experience, the simple/basic/popular modules are already quite well supported in D7; it's the more 'exotic' modules that are not quite there yet.  I've moved my site to D7 with relatively few issues -- D7-specific documentation, or lack of it, can be a challenge.

With regards to drop-down menus, Superfish is provided as a D7 module now -- http://drupal.org/project/superfish.  Works well enough here, and the project seems active.


How to get product variations inside webforms?

You should be able to use the hook_form_alter() to achieve this in a custom module. As long as there is a relationship between the product and its variations you can use the hook_form_alter to add and remove variations from the form. You could also use the module controller to generate a custom twig template that renders content pull from the DB.

hook form alter -
 https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Form%21form.api.php/function/hook_form_alter/8.4.x

custom twig template -
https://www.drupal.org/docs/8/theming/twig/create-custom-twig-templates-from-custom-module

custom webform twig template -
How to access webform elements in webform.html.twig


creation token rest post via postman Access Denied

I eventually figure out what the problem was after many many attempts.

There was actually an issue with postman access to Drupal, it's because Drupal was configured in services.yml to allow access only to Angular API (for my project) by:

Configure requests allowed from specific origins.

allowedOrigins: ['http://localhost:4200']

I changed it to test with postman by:

Configure requests allowed from specific origins.

allowedOrigins: ['*']

Consequently, my token was created in postman with post method which means: bye to 403 error!!!

Hope that can help someone :)

Thank you!


Change the Order of Fields on Teaser node.tpl

Example

<?php if ($teaser): ?>
    <?php print render($content['YOUR_IMAGE_FIELD']); ?>
    <?php print render($title_prefix); ?>
        <?php if ($title): ?>

<?php print $title; ?>

        <?php endif; ?>
    <?php print render($title_suffix); ?>
    <?php hide($content['YOUR_IMAGE_FIELD']); ?>
    <?php hide($content['links']); ?>
    <?php print render($content); ?>
    <?php print render($content['links']); ?>
<?php else: ?>
   //...show default view mode
<?php endif; ?>

Most of the fields are bundled together into the $content variable.

We can remove them from being output in the $content variable by using the hide() function just before we render it (see above).

We can then print the specific field anywhere we like in the template like. See above where weve put the image field.

To determine what fields you have to play with do a var_dump($content) at the top of the template or even better use the Devel module to do this.


Webform questionnaire with scoring and reports

If you want to create charts from the survey results of the Webform module, there are 2 typical/popular alternatives to pick from:

Webform Charts (used in about 400 sites), to display Webform results in a graphical manner using a charting library.
Webform Chart (used in about 220 sites), which integrates with the "Analysis" tab of a Webform (created with the Webform module) to provide charts for each individual component's analytical data.

The Drupal 7 version of both modules, requires the Charts module (dependency).


Share single CUSTOM function across multiple themes

Two options that I can think of:

Make the themes sub-themes of a parent theme and put the function in the parent theme's template.php file. (I like this solution because other assets (css, js, templates) can easily be shared as well. But unless the function has to do with presentation, it probably doesn't semantically belong in a theme at all.)
Create a simple module that contains the function.


How to get back the text formats like filtered_html, full_html or php_code for wysiwyg

You soudln't disable text formats on config > content authoring. Now you only can edit your site's database tables. Table "filter_format" has column "status" and rows with text formats names. Change values in "status" column to 1 for each format you want be enabled.


Try

<?php print $content_column_class; ?>

and see what is exactly printed

I think you should try something like this instead

<section class="<?php print "myclass ".$content_column_class; ?>">

Hope This helps
Cheers


How do I get the node type label from a node object?

The following code works, as pointed out from @Clive.

$type_name = $node->type->entity->label();


Is it possible that search could index token content?

The search index includes the content of the nodes after they are rendered.

node_update_index() is an implementation of hook_update_index(), the hook that is invoked when the search index needs to be updated; it calls _node_index_node() which contains the following code.

  $node = node_load($node->nid);

  // ...

  // Render the node.
  $build = node_view($node, 'search_index');
  unset($build['#theme']);
  $node->rendered = drupal_render($build);

  $text = '
' . check_plain($node->title) . '
' . $node->rendered;

  // ...

  // Update index
  search_index($node->nid, 'node', $text);

Similar code is present in _node_index_node() for Drupal 6.

  $node = node_load($node->nid);

  // ...

  // Build the node body.
  $node->build_mode = NODE_BUILD_SEARCH_INDEX;
  $node = node_build_content($node, FALSE, FALSE);
  $node->body = drupal_render($node->content);

  $text = '
' . check_plain($node->title) . '
' . $node->body;

  // ...

  // Update index
  search_index($node->nid, 'node', $text);

In your case, if the node body contains a token such as [global:test], whose content is test, the search index will contain test, not [global:test].


Users restricted from editing own profiles

It turned out that the permissions needed to be rebuilt as well as verified that that the user had the ability to edit the "Group", which are actually there own user profiles, albeit confusing with the labels.


Custom authentication provider returns 403 for _access: 'TRUE'

Routes need to specify the authentication providers they want to support.

By default, that's session, so authenticating with something else is not allowed.

You do this by specifying _auth: ['your_authentication_provider'] within the options: key of your route.


Notify users of new logged heartbeat activity

Try to use Notify or Notifications module. I think from these modules you can solve your query.


Create a wrapper around specified number of fields in views

Semantic Views module will let you configure HTML output easily.


So, with help from Clive (see his comment below the original question) I have identified two issues:

The correct path for the ActiveProjectsSelection.php file should be src/Plugin/EntityReferenceSelection/ActiveProjectsSelection.php.
The id of the plugin in the annotation should be default:active_projects.
(not related to the original problem) The correct timestamp for the date comparison is DrupalDateTime::createFromTimestamp(time()).

With these changes, my code works perfectly. Also, it does not matter whether I extend NodeSelection or DefaultSelection, it works with either of them.


Creating a loop condition in Rules for Commerce Line items

Figured it out.

Firstly, you'll need Conditional Rules.

Create a new rule component.

For the variables, add Commerce Line Item as a Parameter and add a Integer as Provided.

Under Conditions, add Entity has field, select commerce_product. Then add another Entity has field and select your field_dangerous_goods field from line-item:commerce-product. Lastly add a data comparison to check the status of the dangerous goods field. In my case I just had a checkbox, so I used Data value is empty and checked the Negate box.

This makes the condition return TRUE if the current line item is a dangerous item.

Under Actions, choose Add action and select the Set a data value option. For this set the parameter to the variable you created when you set up the component. Set the value to 1.

{ "rules_dangerous_goods" : {
    "LABEL" : "Dangerous goods",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "line_item" : { "label" : "Line Item", "type" : "commerce_line_item" },
      "dangerous_goods" : { "label" : "Dangerous Goods", "type" : "integer", "parameter" : false }
    },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "line-item" ], "field" : "commerce_product" } },
      { "entity_has_field" : {
          "entity" : [ "line-item:commerce-product" ],
          "field" : "field_dangerous_goods"
        }
      },
      { "NOT data_is_empty" : { "data" : [ "line-item:commerce-product:field-dangerous-goods" ] } }
    ],
    "DO" : [ { "data_set" : { "data" : [ "dangerous-goods" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "dangerous_goods" ]
  }
}

Then for your shipping service rule, under Actions, choose Add action. Select Add a variable, I called mine Contains Dangerous Goods (contains_dangerous_goods). Set the value to 0.

Add a loop.

Then Add action to the loop. Select your component. You'll need to set the variable name, this has to be different to the Contains Dangerous Goods variable from before, I just called mine Dangerous Good (dangerous_good).

Now choose Add conditional to the loop. Then for the conditional, choose Add if. Select the *dangerous_good* which we just set in the loop in the component action. Set the value to 1.

Within the If, choose Add action. Select Set a data value. For the field, choose the contains_dangerous_goods value. This is the initial variable we set for the shipping service rule. Set the value to 1.

Now outside of the loop, Add conditional. Then Add if. Choose the *contains_dangerous_goods* field and set the value to 0.

Then within the If, add your shipping rate.

{ "commerce_shipping_service_standard_up_to_0_5kg" : {
    "LABEL" : "Rate Standard - Up to 0.5kg",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [
      "commerce_order",
      "commerce_physical",
      "rules",
      "rules_conditional",
      "commerce_shipping"
    ],
    "USES VARIABLES" : { "commerce_order" : { "label" : "Order", "type" : "commerce_order" } },
    "IF" : [],
    "DO" : [
      { "variable_add" : {
          "USING" : { "type" : "integer", "value" : "0" },
          "PROVIDE" : { "variable_added" : { "contains_dangerous_goods" : "Contains Dangerous Goods" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [
            { "component_rules_dangerous_goods" : {
                "USING" : { "line_item" : [ "list-item" ] },
                "PROVIDE" : { "dangerous_good" : { "dangerous_good" : "Dangerous Goods" } }
              }
            },
            { "CONDITIONAL" : [
                {
                  "IF" : { "data_is" : { "data" : [ "dangerous-good" ], "value" : "1" } },
                  "DO" : [
                    { "data_set" : { "data" : [ "contains-dangerous-goods" ], "value" : "1" } }
                  ]
                }
              ]
            }
          ]
        }
      },
      { "CONDITIONAL" : [
          {
            "IF" : { "data_is" : { "data" : [ "contains-dangerous-goods" ], "value" : "0" } },
            "DO" : [
              { "commerce_shipping_service_rate_order" : {
                  "shipping_service_name" : "standard_up_to_0_5kg",
                  "commerce_order" : [ "commerce-order" ]
                }
              }
            ]
          }
        ]
      }
    ]
  }
}


Exposed Filters Search : remove parameters from URL

Looks like there is a module that changes the views arguments from a GET to a POST.

Views ExPost


you can achieve that by jCarousel module

This module allows developers and themers to make use of the jCarousel jQuery plugin. It includes a developer API that other modules can use, as well as Views integration in the 2.0 version so that you can turn any list of content or images into a carousel.


Taxonomy term title not displayed as page title in Panels when paged

Your pager IDs are conflicting.  Adjust the pager settings for one of the views to have a pager ID of 1 rather than 0.


I'm not sure if you've had this answered yet, but in Drupal 7 and the latest version of Views, this is possible by doing the following:

Under Fields, click the one you want to configure, in your case it probably looks something like:
Content: Departments

Select Multiple Field Settings and it will drop-down to where you see a check mark in the box labelled:
Display all values in the same row

Uncheck this box and it should list your members twice, once in each department they are specified under.


How to disable creating links for content types?

I always use the Rabbit Hole module in this situation.

  Perhaps you have a content type that never should be displayed on its
  own page, like an image content type that's displayed in a carousel.
  Rabbit Hole can prevent this node from being accessible on its own
  page, through node/xxx.

You can set redirects from the pages too, so you can add a 301 or a 404 (for example)


By default, the taxonomy term view lists content (nodes) and not users. If you want to use a new view on the default term page path, taxonomy/term/%, you have to disable the default view, create a new one, and give it that path. But it will also be in use for your others taxonomy terms pages !

So my advice is to disable and ignore this view, give a path to your full working new view, and set your term path pattern for this vocabulary the adress of your new view's page.

More simply :

Make a new view of users, set a "page" display and set it like this : /mypath/%
Add a taxonomy term ID argument
Add your fields
Go to your pattern url alias setting page, and for your vocabulary "gender", set terms URL to /mypath/% .

Now, all gender terms on your site will be linked to that view.


What's the most efficient way to get D8 to notice changes to .yml files?

In your development.services.yml file turn twig cache off and debug true. This will assist in theming, twig files are also cached.

Secondly, I think the command you want for yml changes is drush cr. However if they are install yml files, (I believe) they'd only register when a theme is enabled/uninstalled like modules are. So if that's the case you'd need to do that. I've also needed to use cr with libraries.yml changes.

Third, what VM are you using? I can run drush cr and it only takes ~5 seconds on the DrupalVM stack.


What causes the 'DB Error: unknown error' after adding custom fields to a report in CiviCRM?

After turning on the debugging tool,it appears the field label was changed at some point and now cannot be referenced through reporting because the database is expecting the old field label and set name of the database cell to be referenced. It doesn't affect exporting the data though. If you have no access to the actual server then a solution is to create a new field and export and import all the data from the errant field to the new field, as far as I understand.


Is there anyway to cross reference a view?

For this you could use the advance option of the view where you could add the contextual filters and relationships.
This would help you in filtration.

For php filtration you could use the Views PHP module; that would help you in your filtration.

  This module allows the admin account (user 1) to add fields, filters and sorts to views which use PHP code. It also supports additional accounts when the core PHP Filter module is enabled.

For information about how to use the module you could refer to README.txt of the module.


How can i programmatically trigger a Lightbox window using Drupal

I achieved this by using ajax_command_invoke(NULL, 'nameOfCustomFunction', array('select')); with the following JavaScript code:

(function($) {
  $.fn.nameOfCustomFunction = function(data) {
    alert(data);
  };
});


How to create a rule triggered when saving a node to schedule sending an email at specified date?

Part 1 - Make sure to include "Entity has field"

First eliminate the possibility that the missing piece to make your rule work is because you didn't include a Rules Condition like "Entity has field" (related to your Reminder date field), as the first Rules Condition.

If you didn't do that yet, then to Rules it is like the value of your Reminder date is simply blank. If needed, enable Rules debugging to double check if the value of that Reminder data has indeed the value that you expect. Refer to my answer to "How can I display the value of a variable inside a condition?" for more details about Rules debugging.

Part 2 - Rework your rule to use the Rules Scheduler

This seems to be a perfect case to actually use the Rules Scheduler (sub-module of Rules). Have a look at my answer to "Rule to store user's last post date and scheduled rule based 30 day reminder", which contains an example of how to use the Rules Scheduler for a variation of your question. The variation is that it is to only eMail 1 user instead of a list of users as in your case, though it uses a field that is similar to your Reminder date field.

The approach using the Rules Scheduler differs from what you tried to do (but couldn't get to work):

it does NOT use a Rules Condition like "check if this the right moment to send such eMail (now)".
instead it performs appropriate Rules Action to schedule such eMails for somewhere in the future. Moreover, it takes into account that the actual date for that eMail may even change in between (ie if the Reminder date field gets updated, then don't send that previously requested eMail anymore).


I can't set a default value on hook_form_alter()

According to this Documentation you can do something like

 $form['field_code_postal']['widget'][0]['value']['#default_value'] ='COUCOU1';

and for another guys help if you want to fill entity referenced field( also files are entity in drupal 8) use

 $form['field_image']['widget'][0]['target_id']['#default_value']= $file; //


How can I stop full page HTML from being cached?

(Anyonymous) Page cache can not be controlled by max-age or contexts. You need to call \Drupal::service('page_cache_kill_switch')->trigger(); to prevent that kind of caching.

However, if it is a block that is displayed on all pages, then that becomes pretty pointless to even try and you could uninstall the page_cache module completely.


how to perform versioning content between users?

You should take a look at the project module. This is used on the drupal site as well.


A CMS like Drupal is a way to create structured content types to make it easier to author large numbers of pages with the same structure. This is actually great from a user experience perspective, as the user expects information to be presented to her in a consistent manner from one page to the next.

The user will be fine with multiple presentation types if the information architecture is consistent, but if your structure is all over the map, the user will quickly tire of having to figure things out.

So for the majority of your site, plain old content types will probably serve you best.

If you are talking about overview pages, then getting used to Panels will probably make it something other than a 'last resort'. It is quite powerful, and customizable. The alternative, if you wanted daily customization, would be to create a single content type, and add and remove fields at will. However, I believe that after a while you are going to wish you had selected to use panels. Eventually you are going to want to re-use something you had before.

When you are using a CMS, think in terms of building blocks, and how to combine them to reach your goals.


How can I programmatically get an entity's validation errors?

This code worked for me, not sure if best approach:

    $errors = $my_entity->validate();
    //see if there were any errors
    if ($errors->count() == 0) {
      //there are no validation errors, move to next step
      $this->my_success_action($my_entity)
    }
    else {
      //there were validation errors, report them
      for($j = 0; $j < $errors->count(); $j++) {
        $error = $errors->get($j);
        //the entity field that failed validation
        $property = $error->getPropertyPath().'_my_weird_field_suffix';
        //the error message about how validation failed.
        $message = $error->getMessage();
        $form_state->setErrorByName($property, $message);
      }
    }


Change interface lang to the node target lang

The configuration you describe will always only allow one language when creating new nodes: the current language of the interface.

That is because you have Set custom language as default for new content. (and the current one as the default).

If you want to create content in other languages, you have to visit the node creation page in that target language (/fr/node/add/article if you're using prefixes).

Or allow other langs to be chosen

But if you want to be able to choose which language to assign to a node no matter what interface language you're currently using you have to untick the   Set custom language as default for new content. while keeping Require language (Do not allow Language Neutral).

That way your interface may be English, but you'll be able to choose any language in a drop-down to assign to that node.


Here is the module to do it:

Hierarchical Term Reference Autocomplete

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


Combine fields that has same value in views

Have you tried using the 'group by' option in views?

Under display, you can select to group by date for example.


how do I add check boxes in form created with the Registration module?

At the time of Field Creation.

Select FIELD TYPE : List (text)

Select WIDGET : Check boxes/Radio buttons & save

  Allowed values list :

  1|list1

  2|list2

  3|list3

& save field setting.

You see that radio buttons are shown.

Now in FIELD SETTINGS : Select Number of values : Unlimited & save.


Outputting front page to a different url

I would personally suggest putting breakpoints into the CSS and making the site adaptive. You would save yourself a lot of time building a separate mobile site.

Plus, especially with adaptive widths, and not fixed widths, you allow your site to display nicely on all sizes of device screen, and when a user reduces the size of their browser window on a desktop.

Alternatively, To detect a device and show a different site e.g. m.yoursite.com have a look at this answer.


Override (shorten) breadcrumbs on Views page

If you're open for contributed modules, I'd suggest that you try Path breadcrumbs. This module will allow you to set up breadcrumb definitions, depending on the path of the page. There you define all items to appear as breadcrumbs, and thus specify whether you want the last item or not, linked or not.


How can i add a depth class to UL in a menu list?

For Drupal 7.

MYTHEME_menu_link(array $variables) {
  global $_current_menu_depth;
  $element = $variables['element'];
  $_current_menu_depth = $element['#original_link']['depth'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '
' . $output . $sub_menu . "
\n";
}

function MYTHEME_menu_tree($variables) {
  global $_current_menu_depth;
  return '
' . $variables['tree'] . '
';
}

NOTE! I noticed this breaks in some cases. I had a three levels deep menu and the second level menu was marked as third.


One way you can do is make a custom module, print access info on every page, every node, every block.

menu_get_item() function return a router item which has access_arguments property for current page.

/**
 * Show access permission of current page.
 */
function yourmodule_get_page_access() {

  $router_item = menu_get_item();
  if ($router_item) {

    $access_arguments = unserialize($router_item['access_arguments']);

    $arguments = array();
    foreach ($access_arguments as $access_argument) {
      $arguments[] = $access_argument;
    }
    if ($arguments) {
      $output  = '<p>';
      $output .= t('This page needs user to have %p permission(s) to access', array(
        '%p' => implode(', ', $arguments),
      ));
      $output .= '</p>';
    }
    else {
      $output = '<p>' . t('This page needs no user permissions') . ' </p>';
    }
    return $output;
  }
}

Then you can hook_page_alter, to display the access info on top of every page.

/**
 * Implements hook_page_alter().
 *
 * Display access information on top of every page.
 */
function yourmodule_page_alter(&$page) {

  // Make a new area on top of the page for displaying access information.
  $page['content']['theverytop']['#markup'] = yourmodule_get_page_access();
  $page['content']['theverytop']['#weight'] = -10;
  $page['content']['#sorted'] = FALSE;
}

Next you can display out the block permission info like this:

/**
 * Implement hook_block_alter
 *
 * To display block permission information to the block title.
 */

function yourmodule_block_view_alter(&$data, $block) {
  $delta = $block->delta;
  $output = '';

  $rid = db_query("SELECT rid FROM {block_role} WHERE delta = :delta", array(':delta' => $delta))->fetchCol();

  if (empty($rid)) {
      $output = ' This block does not have any role permission restriction.';
  } else {
      $output = ' This block is viewable for users have role(s): ';
      foreach ($rid as $role_id) {
          $rolename = db_query("SELECT name from {role} where rid = :rid", array(':rid' => $role_id))->fetchField();
          $output .= $rolename . ' ';
      }
  }

  // append the permission info to block title for every block
  $block->title .= $output;
}

And so forth, basically the same concept, you can do the same to node, form, views.
Hope this helps.


It is true that mixing @alias and -l together does happen to work in the local case, but is not supported in sql-sync.  If this did work, you would need to use --target-uri and --source-uri to distinguish the two different -l/--uri options, but this has never been implemented.  Drush always uses the source and target alias records, and nothing else, to determine how to look up the source and target database records.

As Clive says, the best thing to do it so set up separate aliases for each site.  If you put all of your aliases in a single file, they will automatically create an alias group.

For example, I do something like this:

sitename.aliases.drushrc.php:

<?php

$aliases['live'] = array (
  'parent' => '@server.urpad',
  'root' => '/srv/www/sitename/htdocs',
  'uri' => 'http://sitename.com',
}

$aliases['dev'] = array (
  'root' => '/srv/www/sitename/htdocs',
  'uri' => 'http://sitename.com',
}

server.aliases.drushrc.php:

<?php

$aliases['urpad'] = array (
  'remote-host' => 'my.remote-server.org',
  'remote-user' => 'www-admin',
}

Using a 'server' alias file allows me to easily specify where I want to put each remote site without having to duplicate the remote host information.

Then, to use it:

drush sql-sync @sitename.live @sitename.dev


How to modify the subfields of a custom field in hook presave

As @sonfd commented you could get the field content as array:
$values = $entity->get('field_multifield')->getValue();

modify this array
$values[0]['prefix'] = '55555';

and then replace the entire field content:
$entity->set('field_multifield', $values);

Much easier though would be accessing a single property directly:
$entity->field_multifield->prefix = '55555';


In the Workflow settings of the type page you should choose Multilingual support: enabled or eabled with translation if you want to have the page in 4 different versions on their own.

If you simply choose enabled you can e.g. make as many path aliases as languages are active for one and the same page. If you choose "with translation" you can make translation nodes after creating the page. There is also a rules integration, that makes you all translation nodes automatically.

If you enable Multilingual support you will see in pathauto autmoatic section, that you can choose a path for every enabled language. The prefix you shouldn't use, because itis handled by drupal and/or modules itself. You can change the behaviour in the languages menu under site configuration.


how to download zip file through browser

You don't mention exactly what's not working, but at a guess it might be that the download works in all browsers except Internet Explorer?

IE is an annoyance when it comes to forcing downloads, you really have to go around the houses to get all versions to respect what you're trying to do.

Here's the code I use to force downloads, and it works cross browser (updated to address @MPD's comment below):

function force_file_download($path, $filename) {
  // Most of this is only necessary because of IE
  header("Cache-Control: public");
  header("Content-Type: application/octet-stream");
  header("Cache-Control: no-store, no-cache, must-revalidate");
  header("Cache-Control: post-check=0, pre-check=0");
  header("Content-Disposition: attachment; filename=\"$filename\";" );
  header("Content-Transfer-Encoding: binary");

  $fp = fopen($path, 'rb');
  fpassthru($fp);
  exit();
}

You'd use it in a page callback like this:

force_file_download($filesystem_filepath, 'file.zip');

That code works perfectly for me for any type of file, cross-browser, and if you change the exit() to drupal_exit(), it will also work great for Drupal 7 (currently it's a Drupal 6 snippet).


Pass block configuration item text field value to variable

So if this is for admin/editors only, one way to do it is to use the built-in Drupal hook_settings_form in your custom module. Here is a nice DO tutorial: https://www.drupal.org/docs/7/creating-custom-modules/creating-the-configuration-form

So in your case, this could look something like:

/**
 * Implements hook_settings_form() to configure module.
 */
function roadmap_settings_form($settings) {

  $form = array();
  $form['roadmap_url'] = array(
      '#type' => 'text_format',
      '#title' => t('Enter an alternative URL.'),
  );
  return system_settings_form($form);
}

this form will save the value as a system variable 'roadmap_url' or whatever value you enter in the form field's machine name. you'd probably need to call this from some admin page in your custom module like so:

/**
 * Implements hook_menu().
 */
function roadmap_menu() {
  return array(
    'admin/config/roadmap_OR_SOME_OTHER_PATH' => array(
      'title' => t('Roadmap settings'),
      'page callback' => 'drupal_get_form',
      'page arguments' => array('roadmap_settings_form'),
      'access arguments' => array('administer roadmap OR SOME OTHER PERMISSION'),
      'type' => MENU_LOCAL_TASK,
    ),
  );
}

Now you should be able to go to your config page, enter your URL setting and it will be saved automatically by Drupal. To access this variable, you just need to call:

$url = variable_get('roadmap_url');


Your Contextual filter should use Validator Current user ID matches argument value instead of User:


http://tools.ietf.org/html/rfc2616#section-14.21 Thanks for pointing this out.
Answer will be in here eventually - https://drupal.org/node/2161115


How can I change URL of 'Add new comment' link on teaser?

Go to the admin page for your content type

  /admin/structure/types/manage/page

and check Show reply form on the same page as comments under Comment settings.

If you look at comment_node_view() in the comment module, you can see where the comment link is added to teasers.

    if (user_access('post comments')) {
      $links['comment-add'] = array(
        'title' => t('Add new comment'),
        'href' => "comment/reply/$node->nid",
        'attributes' => array('title' => t('Add a new comment to this page.')),
        'fragment' => 'comment-form',
      );
    }

To alter the link you can use hook_node_view_alter() in your module.

function MODULE_node_view_alter(&$build) {
  $node = $build['#node'];
  if (isset($build['links']['comment']['#links']['comment-add'])) {
    // Alter the 'Add new comment' link.
    $build['links']['comment']['#links']['comment-add']['href'] = "node/$node->nid";
    // Fragment is the '#comment-form' part of the url.
    $build['links']['comment']['#links']['comment-add']['fragment'] = 'comment-form';
  }
}


Does leaving the Views UI module enabled affect performance?

Every enabled module affect performance, just for the fact they are loaded, and parsed from PHP. views_ui.module, in the branch 6.x-3.x-dev of Views, is 10355 bytes.
There are then hooks that are invoked from Drupal, even if you are not using anything from the Views UI module, such as views_ui_help(), views_ui_menu(), views_ui_theme(), or views_ui_library_alter().

Another reason to disable unused modules is avoiding possible security issues.


How do you set a default input text format per content type?

In the absence of a stable release of Better Formats module, you can create a custom module to do this for specific content types or fields.

Create a module (modulename.info and modulename.module, inside a folder 'modulename'). Example:
default_text_format.module:

<?php
/**
* Implements hook_element_info_alter().
*
* Sets the text format processor to a custom callback function.
* This code is taken from the Better Formats module.
*/
function default_text_format_element_info_alter(&$type) {
  if (isset($type['text_format']['#process'])) {
    foreach ($type['text_format']['#process'] as &$callback) {
      if ($callback === 'filter_process_format') {
        $callback = 'default_text_format_filter_process_format';
      }
    }
  }
}

/**
* Callback for MODULENAME_element_info_alter().
*/
function default_text_format_filter_process_format($element) {
  $element = filter_process_format($element);
  // Change input format to "Filtered HTML" for body fields of article nodes
  if ($element['#bundle'] == 'article' && $element['#field_name'] == 'body') {
    $element['format']['format']['#default_value'] = 'filtered_html';
  }
  return $element;
}

And default_text_format.info:

name = Default text format
description = Adapt the module code to set a default format for a content type.
package = Custom modules
core = "7.x"

Put these files in a folder 'default_text_format' in sites/all/modules/custom.

Change bundle name as appropriate for your content type. And you can substitute 'body' with your own 'field_contenttype_fieldname'. (After this comment / better_formats code.)


When a node is saved, the user is normally redirected to the page showing the node, which is not a form. In that case, hook_form_alter() doesn't help. I said the user is normally redirected to the page showing the node, as that is what Drupal does, but there could be a module that redirects the user to a different page, such as the one showing the node edit form to add a new node.

To show the popup when the node is viewed, you can use hook_node_view(), which can be used to add HTML tags to the node view page.

The example shown in the documentations shows how to add markup to the node view page.

function mymodule_node_view($node, $view_mode, $langcode) {
  $additional_markup = 'Markup to add to the page';

  $node->content['my_additional_markup'] = array(
    '#markup' => $additional_markup,
    '#weight' => 10,
  );
}

As for showing the popup right after the node has been saved, you could implement hook_form_alter() to add a form submission handler to the "Save" button; that submission handler would add a session variable that is the checked from your implementation of hook_node_view(). Its code should then be similar to the following one.

function mymodule_node_view($node, $view_mode, $langcode) {
  if (isset($_SESSION['nid']) && isset($_SESSION['timestamp']) && $_SESSION['nid'] == $node->nid && mymodule_check_timestamp($_SESSION['timestamp'])) {
    $additional_markup = 'Markup to add to the page';

    $node->content['my_additional_markup'] = array(
      '#markup' => $additional_markup,
      '#weight' => 10,
    );
  }
}

The values in $_SESSION are the ones set by the form submission handler. mymodule_check_timestamp() should return TRUE when $_SESSION['timestamp'] doesn't contain a value too past in time; this would help in the case there is a module that redirect the user to a different page, and then the user visit the node page to review the node s/he saved. For example, it could return TRUE when $_SESSION['timestamp'] is a timestamp 5 seconds earlier. It is up to you to decide how much delay should be acceptable between when the node is saved, and when the node is viewed from the same user who edited it.

You can change the weight used in hook_node_view(); that changes where in the node view page your markup is added.


Pagers of two different contents are conflicting

You can assign a different PagerID to the pager when editing the View.  This should compensate for the conflict.  By default, all pagers have an ID of 0, but if you need 2 views on the same page, then you need to manually select a different ID for one of them.


How do I import a library from Github when the module is installed

composer.json has no bearing when you enable a module in the Drupal admin. Drupal only looks at the info.yml of a module to ensure any listed dependency (module only) exists and has been met. Using drush also won't work. You need Composer for this.

You would need to require your module via composer require drupal/mymodule - at which point any dependencies listed in require would also be pulled in. For that to work, your module would need to be posted on drupal.org, with the Drupal packages repository added to your root composer.json file.

You could also add a repository endpoint pointed at GitHub, Bitbucket or any other VCS service, add a baseline composer.json file to your project and require it that way, too.

You can also do composer require googleads/googleads-php-lib:25.0.0 from your Drupal root to pull in that package, but I would go the module route (so that package is always tied with the module).


Why do uploaded files gets saved with an all-caps file extension?

Definitely not a server (nginx) issue, as the server does not do anything with the files (well, it transfers them bit by bit). Like Charlie already asked, do you use any modules?

Edit: To answer your second question, of course you can “force” lowercase extensions. But personally I wouldn’t bug your users with that, they should simply upload whatever they have. Instead simply alter the files extension before saving the file to disk/database.

hook_file_presave() seems like the correct way to do this. You would have to create a little module and have a look at the file variable that’s passed to your hook, then simply strtolower() the file extension.


Preprocess function trying to alter title

You shouldn't be using that to alter the page title, you can just use drupal_set_title();


making user profile available for anonymous user viewing

I was having this same problem and was able to solve it by going to EDIT VIEW > ACCESS (under Page Settings) > PERMISSION and changing it to VIEW COMMENTS. Then in the POEPLE > PERMISSIONS area I made sure that anonymous users were permitted to view comments.


How to search for content from the Content Management admin view?

In drupal 7 you can use the Aministration Views.

It uses the Views module and VBO to create some views to replace all the pages in administrtion area that does some kind of listing.

After the instalation you need enable the views created by this module.

For me this was the only way to get a "Title filter" for the contents in the drupal administration area.


Drupal renders a node and passes it to indexer. So whatever you see publicly that what is indexed.

but there are few options you can fix that:

to render a node for indexing this is called: $build = node_view($node, 'search_index'); view mode is search_index, so in your node template you can check what view mode it is and render it differently.
you can use display suite module and then use this display "Search result highlighting input" to configure what is indexed
after node is rendered this hook is called $extra = module_invoke_all('node_update_index', $node);  you could implement it and return extra information

hope it helps


hook_form_alter() on a view exposed filter form

This code should do it:

function MYMODULE_form_views_exposed_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $view_ids = ['YOUR_VIEW_ID'];
  $view = $form_state->getStorage('view');
  if ($form_id == 'views_exposed_form' && in_array($view['view']->id(), $view_ids)) {
    $form['field_new_used']['#attributes']['disabled'] = 'disabled';
  }
}


How to get the field template for view modes to work

Don't put too much logic into your templates. Simply add the field template suggestion by implementing hook_theme_suggestions_HOOK_alter to respect view modes from within your theme or custom module:

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME/MYMODULE_theme_suggestions_field_alter(array &$suggestions, array $variables) {

  $element = $variables['element'];
  $suggestions[] = 'field__' . $element['#entity_type'] . '__' . $element['#field_name'] . '__' . $element['#bundle'] . '__' . $element['#view_mode'];
}

Now you can add templates following this pattern: field--node--field-myfield--article--teaser.html.twig.

When using Layout Builder or Display Suite you might need to check what else you find inside $variables['element'] by printing its values with Kint (sub-module of Devel) via ksm($variables['element']) and then build the template suggestion from what you find there.


You're trying to modify a form which is already got built/processed!!

node_add function is internally calling drupal_get_form which will return the processed form, so even if you change anything it wont take any effect. i.e. Drupal will consider the things which are available when the form is being built/processed.

To overcome this you should use drupal_retrive_form instead of drupal_get_form.

The same problem is discussed here with different context, sadly the OP took part in that discussion :(


http://drupal.org/project/login_destination would seem to offer a possibility to use custom PHP snippets as conditions for destinations.

So you need to find out which theme is being used. As I cannot fathom how you are changing your theme in the first place, I cannot help you with that.


Date field select option in custom module

I can't find a link to any documentation for this at the moment, but the default value for a date field expects the date in a certain format: yyyy-mm-dd. It might sound counter-intuitive but something like this should work:

// Make up a date with the correct year
$time = mktime(0, 0, 0, 1, 1, $year);

// Format the date
$default_value = date('Y-m-d', $time);

// Set the default value
$form['release_date']['#default_value'] = $default_value;


Change weight of CSS file loaded in custom module with #attached?

You want something more like this:

$content['#attached']['css'] = array(
  array(
    'data' => path_to_theme() . '/new.css',
    'type' => 'file',
    'weight' => 1000,
  ),
);


How can I remove the "The image was resized to fit within the maximum allowed dimensions..." message without hacking core?

Disable Messages module helps you to disable any type of message in drupal.

It module has following 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.

Once you install the module you can see the configuration options at admin/config/development/disable-messages.

For your requirement just enter following text in "Messages to be disabled:" textarea.

The image was resized to fit within the maximum allowed dimensions of .*? pixels.

Note : Make sure necessary permission to be set like below.


Only admin can see bulk operations in view

You need to install the sub module in VBO called Actions Permissions.

  ACTIONS PERMISSIONS

  A module called actions_permissions is included in the package. This
  module generates a permission for each action, and VBO honors those
  permissions before showing or executing the corresponding actions.
  This is useful if you want to provide your VBO to several groups of
  users with different privileges: the same view will accommodate those
  different groups, showing to each the actions that they are permitted
  to see.

For your view make sure that you add the relationship to the flag

something like this (adjust as appropriate)

Afterwards navigate to the permissions screen, and enable Execute Flag (or unflag) a node for your roles

For your view of content you need to add the field Bulk Operations: Content (NOT bulk Operations:Flag').

And last but not least, make sure your flag permissions are set for your roles.


What is the difference between \Drupal::request()->getSession() and \Drupal::service('user.private_tempstore')?

The main difference is that session data is stored in the database table sessions and PrivateTempStore in key_value_expire. Session data is preloaded in memory, private tempstore data only when requested. Session data is for small amount of data not exceeding a few megabytes, private tempstore for bigger chunks of data you don't want to have in memory when not needed.

What you've posted is not starting a session, it gets a value. You would need to set a value first to start a session.


This behavior is correct. SimpleTest sets up a new site environment for every test case, using a table name prefix.

You probably forgot to install your module by overriding the setUp() method. Once your module is installed the query should work.


Let users download and set induvidual blog themes Drupal 7

Letting them download and put up whatever theme that they want sounds like it might be a major security issue for your site, since they could put whatever PHP that they want into the theme files and it would run. I'd suggest making a specific set of themes you have picked available and letting users choose from those. There are modules like Theme key to enable using different themes: http://drupal.org/project/themekey


2016 and I'm looking into this as well, now with regard to Drupal 8. I'm wondering about hosting the backend of our media assets locally.
The lure of using an external system is to get a more light weight cms and an easier migration path.
Part of our online core is a photo sharing platform similar to facebook's.
So I need something robust. I can't use Google+ because Google does whatever Google wants to do. I can't use Flickr because I can't be sure that it will be around in 3 years. So Smugmug is a logical candidate.

Anyway, for drupal 7 i found a limited media integration to insert smugmug assets the normal way: https://www.drupal.org/project/media_smugmug .
Smugmug also has an extensive api to program against. https://api.smugmug.com/api/v2/doc


In your case 'views_view_unformatted__test_content_view' is the theme hook in the render array. In Drupal 8 that will make it possible to use following preprocess functions to modify the variables before they get to the template:

themename_preprocess_views_view_unformatted__test_content_view()
themename_preprocess_views_view_unformatted()

There is more information about preprocess functions available here.


How do I show a link to the user registration page only to anonymous users?

According to Structure of routes

  _role: A specific Drupal role, eg. 'administrator'. You can specify multiple ones via "," for AND and "+" for OR logic. Note that, since
  the roles available may differ between sites, it's recommended to use
  permission based access restriction when possible.

so try

requirements:
  _role: anonymous


How do I override the subscription block?

There is no exact equivalent currently. To override the actual block template for that block you can use 'block--simplenewssubscription.html.twig'. You can use the input and form templates to override other elements. I would suggest enabling debugging in Twig so you can see the template overrides.


Don't Associate Orders With Drupal Users - Guest Checkout Only

It sounds like you're trying to work against some basic assumptions of Drupal Commerce, namely that users who are logged in should be associated to their data. This is true of Drupal itself - for example, an authenticated user cannot create an anonymous comment.

The simplest thing to do would be to instruct these users to log out. You can likely find a way to alter how Drupal Commerce creates new shopping cart orders such that authenticated users get anonymous orders associated to their sessions similarly to anonymous users, but I can't guarantee that the module throughout won't be checking to see if the user is currently logged in and making assumptions based on this elsewhere.


change Userlogin block on header to custom

You need just to remove the login block and create for example a new menu or use the existing service navigation where you place the links to the login form and to the reigster form. Show this menu then in the place where the login-block was. Optionaly place a link to Logout too. Drupal will recognize if the user is logged in or not.


How can I have a employee ID read-only in Drupal Profile, set by Admin?

You can use the field_permissions module to set up permissions for fields by user role and then limit access to admin. If you want to limit to one person then set up a separate role and give that role only to one person.


In a custom module, get return of hook for making it available in other hook

Yes, if you implement a hook provided by a contrib module, it is invoked by that module function.
You can declare those two variables in global scope so that they can be accessible each other in the functions.

<?php
// mymodule.module
global $foo1;
global $foo2;

function mymodule_contribmodulehook1 ($parameter1, $parameter2) {
  global $foo2;
  //$foo2 here
  $foo1 = 1;
}

function mymodule_contribmodulehook2 ($parameter1, $parameter2) {
  global $foo1;
  //$foo1 here
  $foo2 = 1;
}

If you don't want to use global scope for your variables, you can save and retrieve them alternatively in your Drupal database using variable_set() and variable_get().

function mymodule_contribmodulehook1 ($parameter1, $parameter2) {
  $foo2 = variable_get('foo2');
  $foo1 = 1;
  variable_set('foo1', $foo1);
}

function mymodule_contribmodulehook2 ($parameter1, $parameter2) {
  $foo1 = variable_get('foo1');
  $foo2 = 1;
  variable_set('foo2', $foo2);
}

Note that, for both approaches, you don't need to return each of them as long as you don't have any other purpose.


There are three RSS feeds:

Core security announcements
Third-party modules announcements
Public service announcements

Using PHP, you can parse one of those RSS feeds to get the data you need.


Drupal and Require.js not playing nice - double load of jQuery

I would try option 1. Require JS is pretty demanding in terms of getting all the dependencies right, so unless you want to debug that I'd load the Require JS version.

The place to look is: https://www.drupal.org/node/756722 where all this is explained.

Basically I think you should (for D7) define the Require JS stuff as a library using hook_library like so:

function hook_library() {
      $libraries['vertical-tabs'] = array(
        'title' => 'MY_STUFF',
        'version' => '1.0',
        'js' => array(
          'PATH/require_stuff.js' => array(),
        ),
        'css' => array(
          'PATH/bootstrap_stuff.js' => array(),
        ),
      );
      return $libraries;
    }

And on hook_init add it like so:

drupal_add_library('system', 'vertical-tabs');

And replace the core version of Jquery with hook_js_alter:

function hook_js_alter(&$javascript) {
  $javascript['misc/jquery.js']['data'] = drupal_get_path('module', 'MY_MODULE') . '/jquery.js'; // Swap out jQuery to use your version.
}

I wouldn't worry too much about sticking with the Drupal version of Jquery as it is very common to use the jquery_update module to replace it anyway.


It's always a good idea to read through the code for a class you're trying to work with.

For example, a quick look through the code yields SolrBaseQuery::getParams(), whose responsibility is to ensure accuracy for, and return, the protected $params array.


in Single Manner

    $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load(TID);
    $value = $term->FIELD_MACHINENAME->value;

Example : load title and language of term id =2

    $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load(2);
    $title = $term->name->value;
    langcode = $term->langcode->value;

And for load Multiple as you wanted

  $terms = $entityManager->getStorage('taxonomy_term')->loadMultiple($terms);
  foreach ($terms as $term) {
      var_dump($term->tid->value); //return tid of term
   var_dump($term->name->value); //return title of term
  }


Commerce field with no value, but printed

Here is a link to this issue, with a patch for commerce 1.3


How to add custom Jquery in drupal module?

There are several ways of adding JS to your module, you can check them here https://www.drupal.org/node/756722

Your attempt should work fine, just don't forget to clear the caches after editing module's .info file.

Cheers!


How can I inspect $element variable in theme function?

If dpm($element) isn't returning output at that stage, you can log the data instead (temporarily) to the watchdog log.

e.g:

watchdog('dev', '<pre>' . var_export($element, 1) .'</pre>');

You can then view it at Admin > Reports > Recent log entries


This could be achieved by creating a relationship, and using Delta to sort. Let us say that the field collection field's name in the entity is field_slides.

Create a relationship with 'Field collection item: Entity with the Slides (field_slides)'. Check the box for - Require this relationship


How to download file by clicking on icon in file module?

I guess the problem is that 'html' in $options is set to FALSE by default, thus stripping the icon html code generated by theme().

I tried modifying a bit the code above and it worked perfectly:

/**
 * Implements theme_file_link().
 */
function yourtheme_file_link($variables) {
  $file = $variables['file'];
  $icon_directory = $variables['icon_directory'];

  $url = file_create_url($file->uri);
  $icon = theme('file_icon', array('file' => $file, 'icon_directory' =>     $icon_directory));

  // Set options as per anchor format described at
  // http://microformats.org/wiki/file-format-examples
  $options = array(
    'attributes' => array(
      'type' => $file->filemime . '; length=' . $file->filesize,
    ),
  );

  // Updating 'html' to TRUE so that the html code to display the icon is     printed
  $options += array(
    'html' => TRUE,
  );

  // Use the description as the link text if available.
  if (empty($file->description)) {
    $link_text = $file->filename;
  }
  else {
    $link_text = $file->description;
    $options['attributes']['title'] = check_plain($file->filename);
  }

  return '' . l($icon, $url, $options) . ' ' .     l($link_text, $url, $options) . '';
}

Note that I added 3 lines (plus a commented line, 4) to update the value of HTML.


Whats the proper way to preprocess field collection items to add first and last class names?

You would normally do this in MYTHEME_preprocess_field_collection_item(), but field collection items don't have their own preprocess. Fortunately, they're entities, so you can use entity preprocess to create your own field collection preprocess function:

/**
 * Implements template_preprocess_entity().
 */
function MYTHEME_preprocess_entity(&$variables, $hook) {
  $function = 'MYTHEME_preprocess_' . $variables['entity_type'];
  if (function_exists($function)) {
    $function($variables, $hook);
  }
}

/**
 * Field Collection-specific implementation of template_preprocess_entity().
 */
function MYTHEME_preprocess_field_collection_item(&$variables) {
  $variables['classes_array'][] = 'your-class-here';
  // Plus whatever other preprocessing you want to do.
}


What are the alternatives for storing client side encrypted data?

Personally I would not trust any JavaScript or Flash provided by operator to safely hide my data from him. How can I know if data is really encrypted on my side, or is it just a smoke and mirrors? Probably that's the reason modules like that was never popular - they simply can't be trustworthy, so why to bother developing them if hardly anyone will trust them?

And if user is technological enough to know if data was encrypted on his side or not, he would prefer the other way. There is a way that allows user to be sure their data was encrypted on their side:

Make user install FireGPG plugin, or something analogous for his browser, to be able to encrypt any text field with his tool, that's under his exclusive control, and developed by Open Source teams not connected to you.
On Drupal side, Field Validation should stop Drupla from saving data that does not look like PGP block. Clientside Validation should stop user from posting it in the first place, but you never know for sure with client-side mechanisms.
Secure Pages should mitigate the risk of accidental access to data if user will manage to send unencrypted despite clientside validation.


Ok, you can use preprocess functions for views.

Drupal 6 - Add Javascript to a View
Programmatically set a css class of a view
Using views preprocesses to add css and js to a view


Node preview with different theme than editing

Page Preview module could be the solution.

Simply add an iframe on the node edit form with the preview of the node in the "default" theme. It's in "dev" version but works.


How to theme the $item in views-view-grid.tpl.php

If you are asking how to theme the display of a node, those templates have names like node.tpl.php, node--NID.tpl.php, node--TYPE.tpl.php, etc.  Lots of information on templates can be found here


How can I translate config entity fields?

You need a schema of the type config_entity.

See for example the one for the node type config entity:

/node/config/schema/node.schema.yml:

node.type.*:
  type: config_entity
  label: 'Content type'
  mapping:
    name:
      type: label
      label: 'Name'
    type:
      type: string
      label: 'Machine-readable name'
    description:
      type: text
      label: 'Description'
    help:
      type: text
      label: 'Explanation or submission guidelines'
    new_revision:
      type: boolean
      label: 'Whether a new revision should be created by default'
    preview_mode:
      type: integer
      label: 'Preview before submitting'
    display_submitted:
      type: boolean
      label: 'Display setting for author and date Submitted by post information'

Choose for fields you want to make translatable the types label and text. See also D8 How to create custom configurational form translatable?


Is there a reliable autosave function for nodes?

Autosave

  The Autosave module automatically saves a snapshot of your content
  type form using AJAX. If the user's browser or machine dies while
  editing a node; the edits will be presented to the user the next time
  they return to the node. The user may toggle back and forth between
  the last saved version and the version with the edits that were lost
  and select which of these they would like to continue with.

  How often a form is autosaved as well as which content types to enable
  autosave for are admin configurable.


Trying to write custom handler to extend views_handler_field_term_node_tid

You must adjust your module's weight so that it runs after views. Use hook_module_implements_alter or Modules weight

And then you can also change your code in MYMODULE.views.inc to something simpler:

function MYMODULE_views_data_alter(&$data) {
  $data['node']['term_node_tid']['field']['handler'] = 'MYMODULE_handler_field_term_node_tid';
}


The underlying problem is which module's responsibility it is to maintain that table.
All relevant info and links are in this issue: https://drupal.org/node/1387268


There is no option for this in ui.

You have to define the display mode for the form in mymodule.routing.yml:

Example from user.routing.yml

user.admin_create:
  path: '/admin/people/create'
  defaults:
    _entity_form: 'user.register'
    _title: 'Add user'
  requirements:
    _permission: 'administer users'

In the line  _entity_form: 'user.register' the form is user and the form mode is register.

Then you can access the form with the path defined here and restrict the access through roles with requirements.

Edit (place the form on any page)

If you want to place the form on any page, you need the form as a block.

You can use this module:

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

But it does not have the option for arguments like form mode.

This experimental module can do this:

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

  Interesting features that does not exists for now with the other modules : ability to choose the form mode as Drupal 8 allows to (in
  Drupal 8, you can create additional form modes).


Why don't CAS users show up in users_field_data?

For D8, CAS requires External Authentication module.

External Authentication maintains a db table called authmap.
CAS maintains a table named cas_login_data.

I suspect the data you're looking for is in one of those tables.


D6 - Trying to display variable_get()s in a block

You need to return the output of the block content as a string, not an array.

...
case 'view':
  $subject = '';
  $content = '';
  switch ($delta) {
    case 0:
      $subject = t('Subject in My Custom Block');
      $content =
        'blockvar_progress_so_far = ' . variable_get('progress_so_far', '0') . '
' .
        'blockvar_number_of_projects = ' . variable_get('number_of_projects', '0') . '
' .
        'blockvar_dollars_raised = ' . variable_get('dollars_raised', '0') . '
' .
        'blockvar_number_children_impacted = ' . variable_get('number_children_impacted', '0');

      // Return values so they can be inserted into block
      return array(
        'subject' => $subject,
        'content' => $content,
      );
    break;
  }
...

See documentation on Drupal 6's hook_block() for a more detailed example.


Creating my own Sub-Menu / Parent in the Admin/Config menu

Just thought it would be easier to show a basic example that has both parent and submenu item in the mymodule.links.menu.yml.

Right now both links goto the same place (as I had to pick a default for the parent item, since I didn't have a admin page that lists all my custom links yet ... and also since having "route_name: <nolink>" did not work for the parent menu item even though some peeps said it worked for them [Note: using Drupal 8.6.12]):

mymodule.parent:
  title: 'My MainMenu Link'
  parent: system.admin_config
  description: 'Custom main config menu item under the Admin->Configuration menu.'
  route_name: mymodule.form
  weight: 100

mymodule.parent_child:
  title: 'My Submenu Link'
  parent: mymodule.parent
  description: 'This is the sub-menu item for my custom config form.'
  route_name: mymodule.form
  weight: 101