What approach for Commerce products, attributes and product displays?

When thinking about how to handle products and product displays, I prefer to model it after how Commerce Kickstart handles it's data organization:

Product displays are used to organize and present products to the customer and product entities are used to store product-specific information.

  First off, I have two taxonomies. One is obviously a Product tree. A Commerce Product will have only one term reference value possible. Then I have a Usage tree (or call it Applications), which describes how and where a product can be used. A Product Display will have multiple possible term references from that tree.

Product catalog taxonomies influence how products are organized and subsequently found on your site. This would mean this information would go into the Product Display.

  Now let's say, I have a brand of nails in different sizes: 1,2,3,4. The sizes 1 thru 3 would be tagged as "Home Use" and the size #4 - only as "Construction Use". All sizes would share some fields, such as main description, PDF attachments, images. And these could be fields on the Product level.

The "Use" field is a little tougher but I think you're on the right track. Anything that is specific to the individual SKU (product images, PDFs, diagrams, descriptions, sizes, etc.) would be on the product entity. You can still provide filtering using these attributes via Faceted search, but you end up not duplicating information across multiple entities.

I'm not sure how big your product catalog is, but there are some modules you can explore to ease your data management pain:

Inline Entity Forms: With IEF, you can create and manage product SKUs within your Product Displays. It makes 1:1 product relationships much easier to manage. It can also do 1:N relationships, but sharing those across multiple products can be painful with this.
The opposite of this is Commerce Auto Display, which allows you to create a Product display from within the Product entity form.

If you want to go down this road, IEF is preferred, since it tends to want you to keep only the SKU, price, and other bare minimum fields on the product entity.


Convenience of inserting external data (products) as Drupal nodes

IMHO, you have this choices :

Use the Feeds module to import data to nodes via CSV file, and you can use the powerful Views module to list all your product, or develop a simple module that can do that.
Use can develop a module that build entities based on your tables, with this approach, you can use your database without creating nodes/terms or other stuffs, but you need to create an admin interface to manage all your tables
If you plan to sell your products online, try to use Drupal Commerce, and import with Feeds module


How do I programmatically create an entity reference in hook_entity_info()?

You can attach this field like any other:

function MY_MODULE_install() {
  // Create a field for company reference to be used by various entities
  $field = array(
    'field_name' => 'company_reference',
    'type' => 'entityreference',
    'settings' => array(
      'target_type' => 'company',
      'handler_settings' => array('target_bundles' => NULL),
    ),
    'cardinality' => 1,
    'translatable' => FALSE,
  );
  field_create_field($field);

  // Attach the company reference field to employee instance
  $instance = array(
    'field_name' => 'company_reference',
    'entity_type' => 'employee',
    'bundle' => 'employee',
    'label' => 'Company',
    'required' => false,
    'widget' => array(
      'type' => 'options_select'
    ),
    'settings' => array(
      'target_type' => 'company',
      'handler_settings' => array('target_bundles' => NULL),
    ),
    'display' => array(
      'default' => array('label' => 'inline', 'type' => 'entityreference_label'),
    ),
  );
  field_create_instance($instance);
}

Code sample taken from this more comprehensive manual.


Views insert current page node id to image link url

If you have a Contextual Filter in place for Content: Nid that is pulling in the nid from the currently viewed page, can

Add a field for your image
Choose Image for the formatter.  Configure the image style that you want.
Link image to Nothing
In Rewrite Results, check Output this field as a link
In the link path, use form?edit[field_whatisrefferaelid][und][0][value]=!1
Check Use absolute path

The !1 is the replacement pattern for the first contextual filter.  It should be listed in the list of replacement patterns in the popup you do the configuration from.

That shuld


How to add extra tab in common browsing widget in drupal commons

It uses Quick Tabs.

You can either goto admin/structure/quicktabs and edit the quicktab.

Or you can visit admin/structure/quicktabs/manage/commons_bw/edit which is the default quicktab for browsing widget directly add any block that you want.


drupal_add_js doesn't work properly in an AJAX callback. If you need to execute a JavaScript function within an AJAX callback, here's a way :

First, in your form, you have to create (you can just import it) the JavaScript function :

function my_module_form($form, &$form_state) {
// [...]
  drupal_add_js(
    'Drupal.ajax.prototype.commands.myFunction = function(ajax, response, status) {
      // Whatever you want to do.
    }',
    'inline'
  );
// [...]
  return $form;
}

Then, in your AJAX callback, you need to call this function you created :

function my_module_my_ajax_callback($form, &$form_state) {
// [...]
  $commands[] = array("command" => 'myFunction',);
// [...]
  return array('#type' => 'ajax', '#commands' => $commands);
}

Hope it helps !


Requesting REST-GET gives me 403 but works fine in DHC

Doomed, I am so stupid. Chrome had the admin cookie, FF had a simple user cookie. I forgot to permit the GET on the new endpoint in the user permissions!!!

So stupid. @Clive: Thanks a lot for your help and sorry for that waste of time.


Views Table with Taxonomy Terms for Columns and Rows

The Forena module can be used for this type of reporting. More specifically by using its facility to create a Display of a table in crosstab format.

A crosstab table is a table with a special layout. It is formatted as a grid, with:

the rows representing one or more (combinations of) facts, such as countries or regions, names of persons (or users) like employees / salespeople (or user IDs / user names), names of Models, etc.
the columns representing one or more other facts, such as periods (months of a year, years, etc), available types/flavors of something (like types of errors), etc.
the intersections of rows and columns containing the actual information (data), such as summarized information (counts of something), timestamps, etc. and which might (optionally) include a hyperlink to a drill-down report.

Below is a sample of such crosstab report (including drilldown links also, i.e. the numbers in red in it):

Refer to my comment in the Forena issue queue for more details about the above screenshot. And/or have a look at the video about How to generate crosstab reports with graphs (Forena also supports charting of those data, a typical related requirement ...).

In this specific case, if I was to create such crosstab table, for "the resultant cells having the download link" I'd create a hyperlink which would actually mention the number of manuals corresponding to the selected combination of Model Name and Model Year. And by following such link, you'd get a drilldown report with links to the actual manuals.

Disclosure: I'm a co-maintainer of this module,
I hope this does not violate the site's policy on self-promotion.


How can I get webform file upload to display a thumbnail instead of a link?

I eventually used a bit of JavaScript to replace the link with an image tag that used the path in the link for it's source.


Create a custom filter in Views related to a custom table

I would do the following to achieve this. In the custom table where you maintain log create a view handler using hook_views_data. Add the following code in your .module file

     function MODULENAME_views_api() {
       return array(
           'api' => '3.0-alpha1',
           'path' => drupal_get_path('module','MODULENAME'). '/views',
       );
    }

Then add a file with the name MODULENAME.views.inc in your module views folder and the following code.

    /**
 * Implements hook_views_data()
 *
 */
function MODULENAME_views_data() {

 $table = array(
    'custom-table-name' => array(  //  Custom table
       'table' => array(
          'group' => 'Custom Tables',      // Groupname
             'base' => array(
               'field' => 'id',  //Primary key
               'title' => '<your table name>',
            )
        ),
     //Description of id
        'id' => array(
           'title' => t(' Id'),
           'help' => t(' Id field'),
           // is mydons_custom_id field sortable TRUE
           'field' => array(
              'click sortable' => TRUE,
            ),
      //Filter handler for filtering records by mydons_custom_id
           'filter' => array(
               'handler' => 'views_handler_filter_numeric'
            ),

           'sort' => array(
              'handler' => 'views_handler_sort'
           )
         ),

         'user_id' => array(
           'title' => t('User ID'),
           'help' => t('User ID referring to User for users table'),
           'field' => array(
              'click sortable' => TRUE,
           ),
           'filter' => array(
              'handler' => 'views_handler_filter_string'
           ),

           'sort' => array(
              'handler' => 'views_handler_sort'
           ),
           'relationship' => array(
            'base' => 'users', // The name of the table to join with.
            'base field' => 'uid', // The name of the field on the joined table.
            'relationship field' => 'user_id',
            // 'field' => 'nid' -- see hook_views_data_alter(); not needed here.
            'handler' => 'views_handler_relationship',
            'label' => t('User'),
            'title' => t('Referenced USER entity'),
            'help' => t('Add USER Fields'),
          ),

        ),

         'node_id' => array(
           'title' => t('Node ID'),
           'help' => t('Node ID referring to Node'),
           'field' => array(
              'click sortable' => TRUE,
           ),
           'filter' => array(
              'handler' => 'views_handler_filter_string'
           ),

           'sort' => array(
              'handler' => 'views_handler_sort'
           ),
           'relationship' => array(
            'base' => 'node', // The name of the table to join with.
            'base field' => 'nid', // The name of the field on the joined table.
            'relationship field' => 'node_id',
            // 'field' => 'nid' -- see hook_views_data_alter(); not needed here.
            'handler' => 'views_handler_relationship',
            'label' => t('User'),
            'title' => t('Referenced USER entity'),
            'help' => t('Add USER Fields'),
          ),

        ),

      )
    );
    return $table;
}

Clear the cache and go to views page and create another view of your custom table. Add relationship to your node and users and contextual filters to show logged in users node.


Views data export remove tags from xml output

I have found the problem, i was overriding the template but with a the wrong code, i was using the alternative style template with these variables:

<?php print $header ?>
<?php print $body ?>
<?php print $footer ?>

Instead these should be used :

// Short tags act bad below in the html so we print it here.
print '<?xml version="1.0" encoding="UTF-8" ?>';
?>

<<?php print $root_node; ?>>

<?php
/**
 * @file views-view-table.tpl.php
 * Template to display a view as a table.
 *
 * - $title : The title of this group of rows.  May be empty.
 * - $rows: An array of row items. Each row is an array of content
 *   keyed by field ID.
 * - $header: an array of headers(labels) for fields.
 * - $themed_rows: a array of rows with themed fields.
 * @ingroup views_templates
 */
?>
<?php foreach ($themed_rows as $count => $row): ?>
  <<?php print $item_node; ?>>
<?php foreach ($row as $field => $content): ?>
    <<?php print $xml_tag[$field]; ?>><?php print $content; ?></<?php print $xml_tag[$field]; ?>>
<?php endforeach; ?>
  </<?php print $item_node; ?>>
<?php endforeach; ?>

</<?php print $root_node; ?>>

I'm posting so maybe it will be helpful for someone else.


Ignore UUIDs when comparing the difference between configuration exports

The use case in question here is for building features; the config/sync directory is never used to import, but it can be used to check if the result of a site install is about what we expect (and to copy wanted files or changes we wanted to keep, and missed, from a saved version).

The meaningless UUID changes in every file, however, make it impossible to find that information in all the noise.

Here is a workaround that presumes you are using Git for version control, exporting configuration and committing it, then running a site install, and re-exporting the configuration (but not yet committing it):

git diff -G '^[^u]*([^u][^i][^d][^:]).*'

will show only files with non-uuid changes. If there's a change to a uuid other than the one for the configuration as a whole (that is, indented under some other part of the configuration), that will be shown.

Super unsure about the regex in this but it's not had a false negative or positive yet.

Here's what i have in my .bashrc to make this easier to use:

# Diff that ignores config files whose only change is the UUID (ignores lines
# starting with 'uuid:' and probably other stuff but it's solid so far.)
alias gdu="git diff -G '^[^u]*([^u][^i][^d][^:]).*'"

Took me forever to come up with this workaround; hope it helps others.


Filter product displays by parent taxonomy term

With a view using Products as base_table:

Add a relationship using the taxonomy reference field you're using and do not require the relationship
Add an exposed filter `Content: Has taxonomy terms (with depth)
In the settings, set the depth to the level you want
In the exposed filter itself, you can configure whether multiple values can be selected or not.

But before all that, you need to make sure that only the child terms are selected on the products.


How to create a rule to send an email when someone creates content of selected type(s)?

I'm trying to create a rule (using the Rules module 8.x-3.x-dev) to send an email when someone creates content that is of the type Announcement or Article

To my knowledge, the current answer to this question is a no go: You can't do that yet with the most recent Drupal 8 version of the Rules module.
Refer to #d8rules status update November 2017 to get a better understanding of the current status of Rules for D8. Here are some quotes from it:

... Fago can’t dedicate time required to develop the module further. What Rules is really missing at the moment is development capacity to help finish the last milestone.

... Even if we got more funding today, fago the current principal maintainer of the Rules module wouldn’t have enough capacity to do the work himself.

One never realizes what has been done, only what remains to be done ... So start here if you wonder how to contribute.
Plan B
While waiting for Rules to become more mature, you can use the Admin Content Notification module as a temporary alternative (which does have an official D8 release already). Some details about it (from its project page):

... can be used for receive email notification when a new content of any content type will be created on your site. Although one can use rules for the same functionality but it's not good to use rules only for notification as it is a huge module, so we can use this module for small websites.

The "...Although one can use rules for the same functionality ..." part of this clearly does not apply to the D8 version of Rules (yet).


D6 + Services 3 + Appcelerator = Login help!

make your endpoint 'api'

THen your login url is, 'api/user/login' POST

And also check to make sure you have allowed application/xml as a value response format at admin/structure/services/list/api/server

Although you might need to wait for this patch to be committed
http://drupal.org/node/1232984


Looking at the errors you are reporting, it seems that you haven't downloaded the actual javascript ckeditor library.

You can do it manually, as described in http://docs.cksource.com/CKEditor_for_Drupal/Open_Source/Drupal_7/Installation.

or you can script it (update the version if needed):

wget http://download.cksource.com/CKEditor/CKEditor/CKEditor%204.5.4/ckeditor_4.5.4_standard.zip
unzip ckeditor_4.5.4_standard.zip
mv ckeditor $SITENAME/sites/all/libraries
rm ckeditor_4.5.4_standard.zip


Both <, &lt; and also &#60; works with a checkbox/radio widget. <select> doesn't allow html code for options.

In consecuence Drupal strip tags if the <select> widget is configured. This is done in _options_prepare_options().

Short story: after some tests I've found that small (< 100) works (there's a whitespace between < and 100), so it is not considered a tag.

I've done my tests with:

drush php-eval 'print strip_tags("small (< 100)") ."\n"'


The way to programatically add a product to the cart and send a user to checkout would be to use the function:

function commerce_cart_product_add_by_id**($product_id,
                        $quantity = 1, $combine = TRUE, $uid = NULL)

and

function drupal_goto**($path = '', array $options = array(),
       $http_response_code = 302)

to redirect the user to checkout.

Here is information on the functions:

commerce_cart_product_add_by_id
drupal_goto


How can I load custom module JavaScript on content type edit form?

You need to change this line:

$form['#attached']['library'][] = 'exclusive_tabs/cse_banner_header';

to:

$form['#attached']['library'][] = 'exclusive_tabs/exclusive_tabs';

As your library name is exclusive_tabs and not cse_banner_header the correct way is 'your_module/library_name' check Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module.


specify $form elements to be excluded from display?

Using unset() isn't a good solution for forms (as I think you know), as you never know what submit/validate handlers might be expecting the unset element to exist when they're processed. This can lead to unwanted errors.

There are three methods you can safely use to 'hide' a form element

Use '#type' => 'value' on the element, which will have the effect that the value for the element will still be passed through to the submit/validate functions with its #value as normal. This is my preferred method.
Use '#access' => FALSE on the element to denote it should not be outputted to the screen.
Use '#type' => 'hidden' as Bart has suggested (although use of this depends on your use case; I imagine if you're trying to hide the value of a form element you don't want to output it in the form as a hidden input).


How can I tell Drupal to add autocomplete=off to the login form

It seems there is a module for this, No Autocomplete.
As a sidenote (copied from the module's page:

  However, browsers and password managers and the like may very well not
  respect the "autocomplete=off" attribute anyway. For example, Chrome
  seems no longer to respect it and Lastpass ignores it by default.

Well, good luck with Qualys!


my module template_preprocess is not called

What you don't report in your question is the hook_theme() implementation, which is necessary for Drupal to know the theme functions a module implements. In your case, the array returned from hook_theme() should be something similar to the following (supposing that your module defines just a theme function).

  return array(
    'tocteasers' => array(
      'variables' => array('content' => 'the default value'),
      'template' => 'tocteasers',

      // Use it only if the template is not in the same directory the module is located.
      // This path should be relative to the Drupal root directory.
      'path' => 'the directory where the template file is located',
    )
  );

Notice that:

You call the theme function with theme('tocteasers', array('tocteasers' =>  "whatever")), but the template file is not using $tocteasers.
The template filename must be the same used for the theme name; in your case as the theme function is tocteasers, the reported template filename must be "tocteasers". The extension ".tpl.php" is not used, as it is automatically added by Drupal when it looks for the template file. The only allowed difference between the theme name and the template filename is that the template filename can use "-" where the theme name uses underscores. This is because the "-" character is not allowed in a theme name, which must use the same characters used in a PHP function name. (This means it cannot start with a number, for example.)
If you are altering the code of an existing, enabled module, Drupal caches the data returned from hook_theme(); the result is that you had a theme function that was not using a template file, and that has been modified to use it, Drupal will not use the template file because it still referring to the old definition. hook_theme() is called in some specific cases, such as when a module is disabled, enabled, or updated. To force Drupal to update its cached data, you should disable and re-enable the module from the administration interface.
dsm($variables) could not show anything, if it is called too late, i.e. when the messages set with drupal_set_message() (the function used from dsm()) are already rendered. For those type of debug messages it's better to use watchdog(), which saves the message in a database table. Drupal allows to see those messages in admin/reports/dblog, and defines WATCHDOG_DEBUG for this very purpose.
Both template_preprocess_tocteasers() and hook_preprocess_tocteasers() are used, the difference is that template_preprocess_tocteasers() is defined from the module implementing the theme function, and it is called before hook_preprocess_tocteasers(). The purpose of the preprocess functions is not printing anything, but altering the variables passed to the template file, or the theme function. As consequence, the following code doesn't work as expected (i.e. "hello" is not in the output of the theme function).

function template_preprocess_tocteasers(&$variables) {
  $variables['content'] = "something!!!";
  print "hello";
}


How to assign IDs to each radio button in drupal form radios?

You need to use theme_radios() hook in your template.php file, if what you get is insufficient.

Parameters
$variables: An associative array containing:

element: An associative array containing the properties of the element. Properties used: #title, #value, #options, #description, #required, #attributes, #children.

Return value
A themed HTML string representing the radio button set.

To interfere with single radio element, see theme_radio(), of course.


Accessing a Entity Refererenced field of the current node

I believe you need $currentNode->get('field_content')->referencedEntities() -this should return each of the referenced entity objects.


Add Taxonomy ID class to the body tag (D8)

The linked example gets the path. Here better use routing. Check the name of the matched route and then get a parameter which is defined in the route. Normally you use getParameter() to get the loaded entity, in this case it's getRawParameter() for the id:

mytheme.theme:

function mytheme_preprocess_html(&$variables) {
  if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical') {
    $variables['term_id'] = \Drupal::routeMatch()->getRawParameter('taxonomy_term');
  }
}

html.html.twig:

{%
  set body_classes = [
    term_id ? 'term-id-' ~ term_id,
  ]
%}
<body{{ attributes.addClass(body_classes) }}>


I would not suggest to use the batch API, simply for the fact that batch operations depend from the browser; if for any reason the browser crashes, or it loses the connection with the server, the batch operations will not terminate, or (worse) they will be hanging.
In fact, to avoid PHP timeouts, the batch operations cause the browser to ping the batch page at intervals; that is what happens, whenever JavaScript code is involved, or not (in the later case, Drupal uses the refresh meta tag).

In these cases, Drush is probably a better choice; you can create a custom module that implements specific Drush commands, or simply add a command file in the directory Drush uses for its commands.


Difference between Field and Field Instance?

A field is the basic definition of a field itself.
A field instance is an instance of that field, attached to an entity/bundle.

Fields are created with field_create_field
Field instances, with field_create_instance

To check if the field, or instance exists, use

field_info_field or
field_info_instance

When you create a field through the UI, Drupal always creates a field instance on that entity/bundle.

If you're adding an existing field, the field data is cloned and a field instance is created on the new entity/bundle.

Lastly, field settings apply globally to that field, field instance settings can vary between entity bundles.


Seeing this change record, this should work:

$items = $user->getTranslation($langcode)->get('field_company');


Cannot display a custom user field in php in Drupal 7

Some problems, and their solutions:

Never use the PHP input filter.
When you are developing code, ensure that you have proper error reporting on. This would show you that you have a problem on the $account = line.

PHP 5.3: E_ALL | E_STRICT
PHP 5.4: E_ALL.

Your general problem is not in code per se, but in not understanding how to debug code.
If you have devel installed, you can dpm() values on a line per line basis, in an attempt to nail down the problem.
If you were to do that, you would quickly notice that $account does not contain the values you expect. $user>uid is actually a mathematical operation, and will not return the users uid. What you want is $user->uid.
field_view_value() will, as the documentation suggests, return "a renderable array", it's not going to actually give you meaningful output, and since it's an array, you can't print it.

I'm guessing what you actually want is:

<?php
global $user;
$account = user_load($user->uid);
$school_cats = field_get_items('user', $account, 'field_user_school_category');
foreach ($school_cats as $school_cat) {
  print $school_cat['safe_value'];
}


Search result to show link to the page not to the pdf file

First, I can't install the Search File Attachments module at this moment, but you can read at the module's page:

  The module is based on the core search and no other module is
  required.

And I don't see any template page inside the module.

As in the search-result.tpl.php you will only have access to the $snippet variable, this is not a solution for you, because $snippet is a string, see the code inside search-result.tpl.php:

<?php if ($snippet): ?>
  <p class="search-snippet"<?php print $content_attributes; ?>><?php print $snippet; ?>

<?php endif; ?>

So your best bet should be implement the template_preprocess_search_results() in the template.php file of your theme.

See this example:

function THEME_preprocess_search_result(&$variables) {
    dpm($variables); //you need devel module to use dpm
}

Inside $variables['result'] you will have the values that you need to make your modification. See the dpm() output:

If you want modify the $snippet variable then change the value inside the function like this:

function THEME_preprocess_search_result(&$variables) {
  //searching the info that you need
  $variables['snippet'] = 'The new value';
}


Adding readonly wysiwyg field to entity form

You can try the Markup module.  Should do exactly what you're after.

  This module adds the ability for site admins to add "Markup" widgets
  to the form. These essentially let designers of cck content-types
  insert additional markup into the node/edit form to display to
  content-authors. This is the equivalent of adding additional elements
  to $form of the type '#markup'.


How to display module ouptput in a page with content

If the code for output your result is not so big than you can put the code in block and show that block on any page you want.


Yes, when you configure your view, if you edit the pager settings, there's a Pager ID that if you change it you'll get a different pagination for each view, you can sync some but others not and so on.


How do I display a form element only if the above checkbox is checked?

Use like this:

$form['count_prefix'] = [
  '#type' => 'textfield',
  '#title' => t('Count prefix'),
  '#description' => t('Set a prefix to be displayed before count number e.g. (5), [5] or <5>'),
  '#required' => FALSE,
  '#default_value' => $config['count_prefix'],
  '#states' => array(
    'visible' => array(
      ':input[name="display_count"]' => array('checked' => TRUE),
    ),
  ),
];
$form['count_suffix'] = [
  '#type' => 'textfield',
  '#title' => t('Count suffix'),
  '#description' => t('Set a suffix to be displayed after count number e.g. (5), [5] or <5>'),
  '#required' => FALSE,
  '#default_value' => $config['count_suffix'],
  '#states' => array(
    'visible' => array(
      ':input[name="display_count"]' => array('checked' => TRUE),
    ),
  ),
];


How to build a simple blog where content could be published securely to user groups?

As per your "... there could be other distributions or modules that I don't know about too." in your question: have a look at the Group module (commonly perceived as an alternative for Organic Groups).

Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. The Group module creates groups as entities, making them fully fieldable, extensible and exportable. Which also makes it integrate very well (out of the box) with commonly used modules such as Rules, Views, etc.

Some more questions you may want to look at for more details:

What are the various roles supported by the Group module?, which explains the various types of roles that can be used.
How to bulk assign existing content to a group created with the Group module?, a typical issue when adding this module to an existing site).
What are the features of the Group module versus Organic Group module?

Resources

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


Is it possible to add a default URL parameter inside a theme template_XYZ function?

Within a custom module, it is possible to use the hook_views_pre_view hook. You can alter the $args array passed as parameter, in order to add or remove arguments.


Email Customer if Order Contains a Disabled Product

You can probably rig this up via Rules to automatically send the notification when the class is disabled, but I think it would be easier and probably better to separate out the disabling of the class and the notification of users. I'm not typically a fan of automatic side effects on entity updates - just imagine what would happen if that product somehow got re-enabled and you had to disable it a second time.

I'd create a line item View using Views Bulk Operations with an exposed filter that let me choose what product SKU to use to filter the results. You can do that either based on the line item's label value (since it initializes to the product SKU) or add a relationship to the referenced product if you've altered those labels somehow. You'll also want to add a relationship to the line item's order so you can filter it by orders in a certain status.

You can then use VBO to call a custom rules component that takes the line items from the View as arguments and then sends a notification out to everyone in the list. You may need to figure out either a Views query based method or a Rules variable based method to prevent sending the notification multiple times to the same user in the event that the account purchased the product more than once.


Instantiate and load a block programmatically in twig template

I am sure there are other ways to solve this problem, but here is how I would do it.

Create your block, then go to admin/structure/block and place your block under "Disabled" list. You can then implement hook_preprocess_node in your .theme.php file.

theme file:

/**
 * Implements hook_preprocess_node()
 */

function mytheme_preprocess_node(&$variables) {
 $block = \Drupal\block\Entity\Block::load('block_id');
  if ($block) {
    $variables['my_custom_block'] = \Drupal::entityTypeManager()->getViewBuilder('block')->view($block);
  }
}

In your template twig file:

{% if my_custom_block %}
 {{ my_custom_block }}
{% endif %}

You just have to make sure that your block_id correct.


How to let users change their own profiles?

By default, users can change their own profile information, including their email address, and excluding the username. To change the username, the user must have special permissions. To change the profile informations, go to example.com/user in your website, then click the "Edit" button.


Everything you listed is super common, almost basic in Drupal projects. So you can find plenty of tutorials and introductory articles about how to do those features.

You can create the latest article blurb Block using Views module (it's in D8 core), then place the Block in a theme region and adjust its visibility to only show on the front page
You can create "Archive" page using Views (pagination is also a feature in Views)
Tag articles with the Taxonomy module (create a Vocabulary with terms inside, then add a Taxonomy reference field on Article Content type). There is a out-of-box View "Taxonomy term" that automatically creates pages for each term and lists the articles tagged with that term
Submitted by and on can also be controled through the interface by editing the Content type settings (you only need twig if you need to override the HTML output)

So get yourself some Drupal Views and Taxonomy tutorials ;)


What is wrong when Open atrium is installed with no colors and images?

This is certainly a permissions issue on your temp and possibly also files directory. Go to admin/config/media/file-system and make sure that the directory set as your temporary directory exists, is writeable to the webserver, and is specified from your server's root directory. Also make sure sites/default/files and/or sites/[yoursite]/files (if using a multisite) exists and is writeable to the webserver.


Create a node programatically and set its CCK field values

For nodereference fields you have to use "nid" instead of "value".

//123 is the nid of the node you want to reference
$node->field_application_discipline_id[0]['nid'] = 123;

The best way to discover what variable to use is to install Devel module and view the devel tab next to the view/edit tab on the node page.


Managing module library dependencies with composer

New method using drupal-scaffold for greatest flexibility

For Drupal 8.4.0 and greater using drush >9.0.0, drush make is deprecated and you should use a full-composer work flow as detailed in the drupal.org documentation links below. Those links do recommend using a composer project, but this may not work for everyone's web server setup. The following is step-by-step how to setup composer.json manually for detail explanation. The instructions regarding adding modules manually can still be done.

# Initialize composer. Stability alpha is important for custom modules that may be source managed outside of packagist or drupal.org
composer init --name myvendor/mysite --stability=alpha --license=GPLv2
composer config repositories.drupal composer https://packages.drupal.org/8
composer config discard-changes true

Then you need to add to composer.json manually the following based on your preferences because there is no way to do so automatically with composer as-is. These will configure drupal-scaffold to install your modules where you want them (as opposed to in vendor/ or a directory chosen by some other developer). Change 'webroot' to 'www' or 'public' or what your host is.

    "extra": {
        "installer-paths": {
            "webroot/core": ["type:drupal-core"],
            "webroot/modules/contrib/{$name}": ["type:drupal-module"],
            "webroot/modules/custom/{$name}": ["type:drupal-custom-module"],
            "webroot/themes/contrib/{$name}": ["type:drupal-theme"],
            "webroot/themes/custom/{$name}": ["type:drupal-custom-theme"],
            "webroot/profiles/{$name}": ["type:drupal-profile"],
            "webroot/libraries/{$name}": ["type:drupal-library"]
        },
        "patches": {}
    },
    "scripts": {
        "drupal-scaffold": "DrupalComposer\\DrupalScaffold\\Plugin::scaffold"
    }

Now you can install some dependencies. Note that composer must be able to use scripts and plugins for this to work.

composer require composer/installers:^1.4.0 drupal-composer/drupal-scaffold:^2.3.0 cweagans/composer-patches:^1.6.2

Run the drupal-scaffold script once (or on your build server as needed):

composer drupal-scaffold

Drupal core, modules, themes, etc... can be installed as per the instructions below without the drupal-merge-plugin.

composer require drupal/core:~8.5.1 drupal/views_vcards

Older method using drupal-merge-plugin or working with core directly

For Drupal 8.1.0 and greater, you can use composer to require Drupal modules directly. The documentation around Using Composer in a Drupal project and Using Composer to install Drupal packages through Drupal.org has been updated to take advantage of drupal.org's packagist. I find it works well already in a deployment scenario.

composer config repositories.drupal composer https://packages.drupal.org/8
composer require drupal/views_vcards

For development, I think that manually adding in the dependency with composer require works fine. The merge approach works too with the drupal-merge-plugin and I use this for my drush make work flow.

composer config repositories.drupal composer https://packages.drupal.org/8
composer require mile23/drupal-merge-plugin
composer update

Update 2016.06.22

I ran into an issue using drush make, which added the traditional Drupal version tags and drupal.org packagist URLs using semver. To that end, I needed to switch to using the stabler packagist at https://packagist.drupal-composer.org, which still supports the traditional Drupal version tags.

Also note that the build server or machine requires an exorbitant amount of memory to do a composer update (or require), which is necessary in all scenarios where running composer update on a similar development machine is not possible in your build process.

Update 2016.09.23

Added link to Using Composer to install Drupal packages through Drupal.org.
Added onto the development section about how I use it with drush make.

Update 2018.03.30

Noticed an up vote. This is fairly old so decided to clarify about more recent development and setting up your site directly with composer since drush make has been (sadly) deprecated for a while.


Drupal 8 problem to list taxonomy word of unpublished content in a view

An old question, but it's an issue I've been struggling with, too, so I thought I'd post an answer. Turns out there's a known issue (feature request, actually) with the taxonomy module going back to D7. You can get all the details at https://www.drupal.org/project/drupal/issues/962664.

There are patches there for 8.2, 8.3 and 8.4 that might solve your problem until the fix/feature makes into a stable release.


Moving Drupal to a new host but same domain

Few things to check.

Which version of PHP? I've seen Drupal sites break going from 5.3 to 5.4

You might want to check what the TTL of your domain is. If it's long you'll have people visiting the new site and the old one at the same time. You can set it to 5 minutes (300) which should make sure everbody moves across to the new site at roughly the same time.

Stress testing. Can the new hosting actually handle the expected load? Things like uploading images will take a lot of memory.


How can I downgrade a module with Composer?

Open your composer.json and search for the line containing drupal/commerce_pricelist
Replace the line by this one : "drupal/commerce_pricelist": "2.0-rc2",
Execute composer update drupal/commerce_pricelist

Or simply run composer require 'drupal/commerce_pricelist:2.0-rc2' as suggested @4k4 in the comments


Write all PHP errors, warnings and notices to error_log

For that, you will need to implement the hook_watchdog to make calls to the error_log() function.

You could as example one of the places where is implemented, that is the syslog_watchdog. Instead of use the openlog() and syslog() function, you will use the error_log().


View to display the comments of the curent user nodes

When you add a new view (/admin/structure/views/add), you have the possibility to select Comments.
It will list all comments.

Then you need to set a Contextual Filter and a Relation in order to get the comments of the current logged in user.


db_insert error delta "doesn't have a default"

Without knowing the circumstances, I think you might better off loading your node,  adding to the field array, then using the node save function. But if you want to stick with DB operations, you could retrieve the next highest cardinality with this query:

  $next_delta = db_select('field_data_field_room_rates','rates')
    ->fields('rates', array('delta'))
    ->condition('entity_id', $mynode->nid)
    ->condition('revision_id', $mynode->vid)
    ->orderBy('delta','DESC')
    ->range(0,1)
    ->execute()->fetchField() + 1;


I found some code within the module that was placed as a work around for issue https://www.drupal.org/node/936222. Now that it's fixed, all is well.


How to alter auto-complete exposed filter programmatically?

Here is a possible answer to this problem.
First of all, a litte visual.

To get this working you need the following:

Configure your View to display the exposed taxonomy filter as a dropdown. autcomplete will not work because you cannot have multiple entries with the same key in the generated JSON array.
Optional: Install and configure the Chosen module [https://www.drupal.org/project/chosen] to get your dropdown to render nicely and offer autocomplete options.

You will also need this JS library for Chosen to work => [https://github.com/harvesthq/chosen]

Optional: You can finally use some custom code for formatting the presentation of your list, here is a sample minimal module that adds the special arrow that you see in the screenshot.

define('YOUR_CUSTOM_TAXONOMY_AUTOCOMPLETE_PATH', 'mycustompath/1');
define('YOUR_EXPOSED_FILTER_MACHINE_NAME', 'field_tags_tid');

/**
 * Implements hook_form_alter()
 */
function se_form_alter(&$form, &$form_state, $form_id) {
  if( $form_id == 'views_exposed_form' ){
    if(isset($form[YOUR_EXPOSED_FILTER_MACHINE_NAME]) &&
    $form[YOUR_EXPOSED_FILTER_MACHINE_NAME]['#type'] == 'select'){
      $form[YOUR_EXPOSED_FILTER_MACHINE_NAME]['#options'] = _custom_update_options_for_taxonomy($form[YOUR_EXPOSED_FILTER_MACHINE_NAME]['#options']);
    }
  }
}

/**
 * Function that update select options for taxonomy filter
 *
 */
function _custom_update_options_for_taxonomy($options = array()) {
  $current_parent = '';
  foreach( $options as $i=>$option ) {
    if( is_int($i) && isset($option->option) && is_array($option->option) ) {
      $option_arr = $option->option;
      $tids = array_keys($option_arr);
      $tid = reset($tids);
      // is this a child of the previous parent
      if( strpos($option_arr[$tid], '-') === 0 && $current_parent != '') {
        $option_arr[$tid] = preg_replace('/^-/', ' ⤷ ', $option_arr[$tid]);
        $option->option = $option_arr;
      }
      // this is a parent node
      else {
        $current_parent = $option_arr[$tid];
      }
    }
  }
  return $options;
}

Hope this help some!


Display a Media Entity Image from other (referencing) node in a Twig template

To get a renderable output for Twig use EntityViewBuilder::viewMultiple()

    $variables['related_nodes'] = \Drupal::entityTypeManager()
      ->getViewBuilder('node')
      ->viewMultiple($relatednodes, $view_mode, $current_node->language()->getId());

and configure the three fields in the view mode you've specified here.


How to send mail from drupal 7 efficently and avoid 'Too many concurrent SMTP connections' error?

Have you tried using the Mandrill module? https://www.drupal.org/project/mandrill


This is difficult, because it is core functionality.
What you could do to prevent people from checking node/4, node/5 etc is blocking access when a url request has a certain structure. You'd need a custom module with an EventSubscriber.
Here is an example how to intercept such url requests and how to redirect them. In this case it is a taxonomy term view but the underlying thought is the same: https://stefvanlooveren.me/blog/redirect-taxonomy-terms-filtered-view-page
Further, you'd have to check in your html rendering that every reference to a node id is hidden. Quite some work but if it is really necessary its possible.


Files in the file_managed table with status of 0, not deleting on cron

They are deleted, but during cron tasks, and just when:

They aren't marked as permanent
They are older than DRUPAL_MAXIMUM_TEMP_FILE_AGE seconds
No module contains a reference to those files

The code that deletes those temporary files is contained in system_cron().

  // Remove temporary files that are older than DRUPAL_MAXIMUM_TEMP_FILE_AGE.
  // Use separate placeholders for the status to avoid a bug in some versions
  // of PHP. See http://drupal.org/node/352956.
  $result = db_query('SELECT fid FROM {file_managed} WHERE status <> :permanent AND timestamp < :timestamp', array(
    ':permanent' => FILE_STATUS_PERMANENT,
    ':timestamp' => REQUEST_TIME - DRUPAL_MAXIMUM_TEMP_FILE_AGE
  ));
  foreach ($result as $row) {
    if ($file = file_load($row->fid)) {
      $references = file_usage_list($file);
      if (empty($references)) {
        if (!file_delete($file)) {
          watchdog('file system', 'Could not delete temporary file "%path" during garbage collection', array('%path' => $file->uri), WATCHDOG_ERROR);
        }
      }
      else {
        watchdog('file system', 'Did not delete temporary file "%path" during garbage collection, because it is in use by the following modules: %modules.', array('%path' => $file->uri, '%modules' => implode(', ', array_keys($references))), WATCHDOG_INFO);
      }
    }
  }

If the files are not getting deleted, and you don't see any error message in the watchdog log database, then you need to check cron tasks are executed and the files are older than 6 hours. In the other cases, you should get an entry in the watchdog database table, even if that would be a generic Could not delete temporary file.


How do I show the weather block based on Geofield on a Taxonomy Term

Here's a stab at it. You'll obviously need to test as I haven't tested it at all. Basically I added in some checks to see if it was a node or a term and then tried to test the fields for either one. Let me know if it helps!

 case 'geofield':
    if (user_access('access content')) {
        // Set up the node geofield weather block.
        if (arg(0) == 'node' and is_numeric(arg(1))) {
            $node = node_load(arg(1));
        } else if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
            $term = taxonomy_term_load(arg(2));
        }

        $block['subject'] = t('Weather nearby');
        $block['content'] = '';
        $display = weather_get_display_config('default');
        $display->detailed = FALSE;
        // Get a list of all field names which are geofield fields.
        $geofield_field_names = db_select('field_config', 'fc')
            ->fields('fc', array('field_name'))
            ->condition('type', 'geofield', '=')
            ->execute()
            ->fetchCol();
        foreach ($geofield_field_names as $geofield_field_name) {
            $geofieldname = array();
            if (isset($node->$geofield_field_name)) {
                $geofieldname = $node->$geofield_field_name;
            } else if (isset($term->$geofield_field_name)) {
                $geofieldname = $term->$geofield_field_name;
            }

            if (!empty($geofieldname)) {
                // The node/term has geofield fields, determine if there's usable data.
                // First cycle through the language codes (will mostly be 'und').
                foreach ($geofieldname as $language) {
                    // Now cycle through the different locations.
                    foreach ($language as $location) {
                        if (($location['lat'] != 0) or ($location['lon'] != 0)) {
                            $place = weather_get_nearest_station($location['lat'], $location['lon']);
                            $forecasts = weather_get_weather($place->geoid, $forecast_days, $display->detailed);
                            $weather[0]['forecasts'] = $forecasts['forecasts'];
                            $weather[0]['utc_offset'] = $forecasts['utc_offset'];
                            $weather[0]['name'] = $place->displayed_name;
                            $weather[0]['geoid'] = $place->geoid;
                            $link = _weather_get_link_for_geoid($place->geoid, 'default');
                            $weather[0]['link'] = l($place->displayed_name, $link);
                            $link = _weather_get_link_for_geoid($place->geoid, 'yr.no');
                            $weather[0]['yr.no'] = $link;
                            $weather[0]['station'] = array('distance' => $place->distance, 'bearing' => $place->bearing);
                            $block['content'] = theme('weather_forecast_preprocess',
                                array('weather' => $weather, 'display' => $display));
                        }
                    }
                }
            }
            unset($geofieldname);
        }

        // Do not show block if no lat/long information has been found.
        if (empty($block['content'])) {
            return;
        }

    }


What about Drupal Commons 3 on Drupal 7?

As of today Drupal Commons on Drupal.org, Commons Distribution Projects has reached version 7.x-3.22 from the first full release on February 25, 2013


libraries_get_path() is provided by the Libraries module. That error indicates that the Libraries module is either missing or not enabled.


How to securely access the data from another Drupal instance?

The easiest way to do this would be to set up a new MySQL user on Server B that had something like: GRANT SELECT ON serverBdata TO 'serverAuser'@'serverA-IP';

Then you can write a module on server A that connects and retrieves that data.

If that's not going to work, you can look at setting up a menu hook on Server B that delivers the data in a sensible way, such as JSON, over HTTPS.

if you wanted to get really fancy, you could also encrypt the JSON.


best location for features related theming customizations

This is just my opinion...

The HTML class itself is not related to the theme, it's related to the module defining the element on which it's placed (if it is a feature specific class name as @barraponto points out in the comments).

The styling for elements with that class is the theme's responsibility.

I would suggest that your code would be more appropriate inside the feature module. If it's not, imagine what will happen if you change themes...you'll lose the class that was on that element, meaning it can no longer be targeted for styling.


How to handle caching on a Drupal 8 custom Views access plugin that checks a User's Profile's field value

A Views access plugin implements CacheableDependencyInterface. So you probably need to set a tag and a context for the current user in these methods:

  /**
   * {@inheritdoc}
   */
  public function getCacheMaxAge() {
    return Cache::PERMANENT;
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheContexts() {
    return ['user'];
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheTags() {
    return ['user:' . \Drupal::currentUser()->id()];
  }


Client-side validation module, fields required only if certain values in other fields are set

You can always create a custom rule for Client Side Validation, check clientside_validation.api.js for instructions, but you'll need some coding experience, otherwise feel free to open a feature request and we'll see what we can do.


Entity Form to insert data into Custom Entities

this sounds like something Views Bulk Operations or Rules could do, eg you make a "url link" (with Rules Link module) to call an action to add a doctor to an event. You could make more than 1 link, and ever link could have a custom ?number_of_doctors=N value on it to update the Entity with N number of blank doctor entries.


How do I trigger Infinite Scroll with FancyBox in Drupal 7

ugh... sounds like you'll need custom work. But try the Image Lazy Loader Module

  This is a small helper module which will automatically lazyload all images for sites with multiple images, which will make the site load faster.

  All images will only load when it's visible to the browser window.


how do i get the groups which i have joined

There is a view that comes with OG 7.x-1.x (I'm using 7.x-1.4) that displays all of the groups subscribed to. If you have views running, you could  simply append /user-groups to your url and you should see it. After that, you can go into the view and modify it to meet your specific needs (e.g., make a block or whatever).


Pass values to twig file from #theme options

You need to add it to your $build render object. Here's a piece of sample code, in this case from a Block plugin with a form on it, similar to yours:
...
in my BlockPlugin
..

public function build() {
    // getConfiguration returns the values from the form I have and save to a config object.
    $source = $this->getConfiguration()['source'];
    $access_token = $this->getConfiguration()['access_token'];

    $build = [
      '#theme' => 'my_fancy_search_widget',
      '#source_data' => $source,
      '#access_token' => $access_token,
    ];
    return $build;
  }

...
in my .module file:
...

/**
 * Implements hook_theme().
 */
function my_module_theme($existing, $type, $theme, $path) {
  return [
  'my_fancy_search_widget' => [
      'template' => 'main-search',
      'variables' => [
        'source_data' => NULL,
        'access_token' => NULL,
      ],
  ];
}

in my twig template I can print these vars with {{ source_data }} and {{ access_token }}


You can use the Facebook OAuth (FBOAuth) module for this. Here is a quote about it (from the module's project page):

... provides authentication services and an API to perform actions against Facebook. This module allows users to login to Drupal through the service commonly known as "Facebook Connect". This module is built with simplicity and flexibility in mind, it provides login services (and does it well), and an API for performing any other actions you may want to write yourself to query against Facebook's APIs.
Features:

One-click login through Facebook.
Automatic import of user e-mail and profile information during initial login.
Integration with Profile module to map Facebook data to Profile fields. (Drupal 6)
Integration with Field module to map Facebook data to fields on users. (Drupal 7)
A flexible and direct API for modules to get authenticated and query Facebook's APIs (plus extensive documentation).
Extensive permission settings for Facebook data retrieval.
The ability to de-authenticate or unlink a Facebook account from a Drupal account.
Does not require any external libraries or downloads.


Share Unpublished nodes through a link that needs a user authentication

Access unpublished

  Easy to use module grants access to view unpublished content to anyone
  who has a unique URL and appropriate permissions. Visitor can be
  anonymous or authenticated user with the user role.

  When administrator or users with enabled privileges visit (or save)
  unpublished node, can see link for direct view that unpublished
  content. Unique URL link is displayed as Drupal message or in node
  content.

  Administrator can enable view an unpublished node for any roles with
  "View unpublished contents" permission. If it is set for anonymous
  users, anyone who know the link with hash key, can view the
  unpublished node. View only, not edit.

  Default URL parameter is "hash" and can be changed on configuration
  page for more security or customization.

  Module is useful for proofreaders, content checkers etc. Webmaster
  does not need to create user accounts and can keep the website safer.
  Each node has its own unique hash key (like Google Docs).


Adding stylesheets for an internal page only

The path is incorrect; it should be as in the following code.

if ($path == 'about/advantages') {
  drupal_add_css(drupal_get_path('theme', 'ninesixty') . "/styles/framework/page-about.css");
}


How to add a universal form submit handler to ALL forms?

You can use hook_form_alter(&$form, &$form_state, $form_id) without traditional if inside. Then it'll work on all forms.

Problems start when submit handlers are attached not to form, but to buttons. If you have to take care about that, you will need to scan recursively form tree, find all elements with ['#submit'] set and attach your handler to them. to do this, write recursive* function. Drupal mixes properties with children elements, so to avoid scanning properties, use element_children(&$elements, $sort = FALSE).

*Of course you can make it iterative, too, should be faster, but recursion is more intuitive approach.


Limit the number of registrations by field

You can disable specific dates in date popup by implementing some custom code as per shown in jQuery UI DatePicker: Disable Specified Days. To work with jQuery in Drupal you can check the date popup alter example here.

OR you can try Work Calendar Module with Date Restrictions Module (both are in dev and not suggested to use on Production unless working without any error).


Rules are very important and most common using thing in Drupal. We can create custom rules programmatically using the hook_rules_action_info. There is a useful hook hook_rules_action_info() provided by rules api to create custom rules programmatically. Using this We can use our custom functions to perform the actions that we require.

Following is a sample of the hook_rules_action_info implementation

function sample_custom_rules_action_info() {
  return array(
    'sample_custom_action' => array(
      'label' => t('Custom Rule Action'),
      'parameter' => array(
        'param1' => array(
          'type' => 'int',
          'label' => t('Sample Label'),
        ),
        'param2' => array(
          'type' => 'commerce_order',
          'label' => t('Sample Label2'),
        ),
      ),
      'configurable' => FALSE,
      'group' => t('sample Custom module action'),
      'callbacks' => array(
        'execute' => 'sample_custom_action',
      ),
    ),
  );

Label for the rule action appears in the Rules interface.
Parameter that needs to be passed to the custom action function
A group for this element, used for grouping the actions in the
interface.
callbacks are array of custom functions that to be used for this
action's functioning.

This function has more parameters, but the above are most required ones to create a custom action.

Video tutorial

Creating a Rules Action


Convenient way to copy & paste links to uploaded file attachments when editing Drupal 7 content?

IMCE will let users browse to it and insert links to the files inside a text area if that's what you're going for. You could also programmatically alter the form and provide a copy to clipboard link next to the file in the listing.


50 Variations of a Node with Access Restrictions Based on User Login

There seems to be good handful of permission access type modules restricting users to a specific node.

I tried taxonomy access and taxonomy access lite and they dont do what I need as they limit access to a taxonomy to roles only and not doable for specific users. A work around would have been create a bunch of roles. But I have 50 different users that need 50 different access rights to certain pages.

I also tried https://www.drupal.org/project/permissions_by_term but that was a bit wonky as this didn't restrict via the access restriction table. So items still showed in the menu even though they didn't have access to it. Upon clicking on the menu, they do indeed not have access to it, but I wanted all node references to this restricted node removed from the page.

I finalized on the Flexi Access module: https://www.drupal.org/project/flexiaccess

This gives the ability to restrict specific users to a certain node page, but does not restrict by taxonomy terms or by role.

It will add a new flexi access tab on your content pages.


How can I limit a list of node tokens to only a particular node type?

I'll just answer this as a "No".  Token Tweaks is what I needed to use to prevent long page loads (30 seconds at times...)


How can I set a default value for the country in an addressfield?

Finally figured it out. The idea is to emulate the code in addressfield_field_widget_form(). Here's the recipe:

 /**
  * Implements hook_form_FORMID_alter() for `commerce_checkout_form_checkout`.
  */
 function mymodule_form_commerce_checkout_form_checkout_alter(&$form, &$form_state) {
    // Get the addressfield element we're modifying.
    // Adapted from addressfield.module/addressfield_field_widget_form()
    $element =& $form['customer_profile_shipping']['commerce_customer_address'][LANGUAGE_NONE][0];
    $element_key = $element['element_key']['#value'];
    $field = $form_state['field']['commerce_customer_address'][LANGUAGE_NONE]['field'];
    $instance = $form_state['field']['commerce_customer_address'][LANGUAGE_NONE]['instance'];
    $delta = $element['#delta'];
    $settings = $instance['widget']['settings'];
    $langcode = $element['#language'];
    $items = array($delta => $element['#address']);

    // Get the default address used to build the widget form elements, looking
    // first in the form state, then in the stored value for the field, and then
    // in the default values of the instance.
    $address = array();

    if (!empty($form_state['addressfield'][$element_key])) {
      // Use the value from the form_state if available.
      $address = $form_state['addressfield'][$element_key];
    }
    elseif (!empty($items[$delta]['country'])) {
      // Else use the saved value for the field.
      $address = $items[$delta];
    }
    else {
      // Otherwise use the instance default.
      $address = (array) $instance['default_value'][0];
    }

    // Merge in default values to provide a value for every expected array key.
    $countries = _addressfield_country_options_list($field, $instance);
    $address += addressfield_default_values($countries);

    // Set our default country.
    // THAT'S THE PAYLOAD!
    if ($address['country'] != $my_default_country) {
      $address['country'] = $my_default_country;
      $address['administrative_area'] = '';
    }

    // Add the form elements for the standard widget, which includes a country
    // select list at the top that reloads the available address elements when the
    // country is changed.
    if ($instance['widget']['type'] == 'addressfield_standard') {
      // Generate the address form.
      $context = array(
        'mode' => 'form',
        'field' => $field,
        'instance' => $instance,
        'langcode' => $langcode,
        'delta' => $delta,
      );
      $element = array_merge($element, addressfield_generate($address, $settings['format_handlers'], $context));

      // Mark the form element as required if necessary.
      $element['#required'] = $delta == 0 && $instance['required'];
    }
  }


Do not create new nodes, only update existing

First you need to ensure that each created node has a unique id associated with it that Feeds can use to identify it (eg as an existing node that needs updating).

You can set one (or more) of the fields to be unique in the node processor mapping section (admin/structure/feeds//mapping):

My example takes the generic 'Item GUID', I would suggest that you might instead map SKU to GUID and then set that to unique (make sure to click both update and save).

You then change the node processor settings to Update/Replace:


CCK field. how to use dynamic names to call CCK fields? (like: $node->$cckname)

You use curly braces {} to delimit the variable inside your reference, as

for($i = 0; $i >= 20; $i++) {
  $cckname = 'field_photos_' . $i; //$cckname is changing the image field name, then...
  echo "<img src='/" . $node->{$cckname}[0]['filepath'] . "'";
}

This syntax is used in many places in Drupal core, see for example hook_field_prepare_translation.


How to display the total number of article/page on a term views?

You could achieve this by creating view attachment or block which will calculate the total number of nodes per term. Do not add access rule for this case. This can be then called in the header of the Taxonomy Term View using Global:View where you can select the newly created view and its display.


Table Sorting on "Content Indexed" View type

As indicated in the edit, the "Content Indexed" view type comes from the module Search API. After digging around I was able to find the page

admin/config/search/search_api

Which houses a bunch of search indexing. For me, I was able to go into the "Content Index" and find a list of fields, with options for how they are indexed. At the top of this page there is the help text:

  The datatype of a field determines how it can be used for searching and filtering. Fields indexed with type "Fulltext" and multi-valued fields (marked with 1) cannot be used for sorting.

I noted some the fields I was trying to sort on were listed ether as full texted, or did not have an option set for indexing at all. Setting these fields to something other than "Fulltext" allowed them to become sortable in the view.


Is it possible to assign permission to fields?

Yeah,
You can make use of Field Permissions

  Features

  Enable field permissions on any entity, not just nodes.
  Role-based field permissions allowing different viewing patterned
  based on what access the user has. Author-level permissions
  allow viewing and editing of fields based on who the entity owner
  is. Permissions for each field are not enabled by default.
  Instead, administrators can enable these permissions explicitly for
  the fields where this feature is needed. Field permissions overview


views slideshow: display multiple items but scroll only one item at the time

I'd suggest using the owl carousel module from Git hub for responsive slide shows.  It has lots of options to define how many slides based on breakpoints, support for mobile touch events, number of slides per next, and more.

We've been using it since 8.0 without a problem.  Note that despite the Readme, the author has released it under GLPv2.  See issue #4.

There is a cleaned up pull of this project as well.  I have not used this but it may be a slightly better alternative.

Just install the module as a manual module or you can add the git hub repo as a repository in your composer.json and install it via composer.  Once enabled, change your view format to Owl Carousel and then use the settings to define things.


You could migrate DB data with the Migrate module (though it's not very light module and has an individual learning curve, so if you are not a programmer, or not yet, it might be better for you to find a Drupal programmer that will help you run it). Otherwise, if the site is small (i.e has only several or about fifteen pages) I would suggest of building it from the start... In most cases it shouldn't take much time..

Blessings,


Exclude a not-hidden field in the content

The field shouldn't be removed from the $node object...if it is then I'd check what custom/contrib modules you have installed that might be causing this to happen. It's not supposed to.

A sure-fire way to make sure all fields are attached to the object is to re-load it:

$node = node_load($node->nid, NULL, TRUE);

That will re-load the $node fresh from the database, with all fields attached. You do take a performance hit doing this. However, Drupal core will never have removed the field from the $node object in the first place, so if you've got some other theme/module that's doing this you'll either have to find/repair/remove it, or use a more a extreme method like the one above.


How can I pass user real name as a contextual filter in views

If the real name is stored in one field in your user, you can set up a relationship with the user and then point to that in the contextual filter, eg, here I just created a "real name" text field in the user and then did this:

and then for nice looking urls, did this in the filter:

so I can go to

www.example.com/by-real-name/this-real-name

or

www.example.com/by-real-name/that-real-name

It's really up to you re: case transformation, but two real caveats:  you have to make sure real names are unique AND it gets really squirrelly if and when special characters are in the real name field.


It seems that drupal can't process your files due to not writeable file system paths.
Go to admin/config/media/file-system and specify public and temporary directories.
After that clear all cache here admin/config/development/performance.


drupal_set_message showing twice when called from hook_init

It's likely that the first message you see is the left-over result of a previous AJAX call, and the second message is the one you're intending to see.

To test that, open a different browser and browse to the page in question. First time round you should see the message once; when you refresh the page, and on subsequent requests, you should see it twice.

It happens because hook_init() is also invoked for AJAX requests, but the messages added to the session are never printed-then-cleared - so there's an extra copy of the same message in the next normal page load.

For most (all?) modern browser/server combinations you can use something like this to detect whether or not the request is from an AJAX source, and react accordingly:

function is_ajax_request() {
  return !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}


Error embedding drupal views to twig template

That's an error you would get if the twig_tweak module is not enabled, are you sure you have enabled it? If you have multiple clones of your site, make sure you're on the right one.


It looks like a bug, see http://drupal.org/node/633916

It's optional to path the pid to path_set_alias() so it should work without passing it.


theming user profile with "User Field Privacy" - but no "Privacy" available

update/solved: I did solve my problem now with very basic measurements: for each field I wanted to have a 'privat option' for, I added an extra checkbox field ("public/private"). This setup just works fine no need to have "User Field Privacy" installed – at least for me. Hope this might help somebody some day.


Correct SQL Statement for Joining Taxonomy Terms

If you want to show Locations a Course is offered. Or Courses at a Location I would recommend using the Views Field module, or perhaps Context to show a View on the content type page.

Views field allows you send parameters to the embedded field view from the source Node. So you should be able to get the related content(s) you want to show by passing the necessary filter parameter criteria you want to the View -- usually as a contextual filter.

For example for a Landing Page Content Type (eg, First Aid) you add a field that is a View. Call the view like locations for course. Then make a View that outputs Location taxonomy term names based on a contextual filters. The contextual filter will be:

the taxonomy term name of the course(s) in your taxonomy of Courses.

Then output the taxonomy Location term names for results of the set course name contextual filter. Overwrite the linkpath as needed.


Fix a constant width for first sidebar and second sidebar

My guess, before your css editing, the index block filled that white space, right?

you changed the width of the sidebar's content, rather than the sidebar itself (which is a region, not a block)

i don't know of the zero point theme, but look for an outer class, like .sidebar, or .sidebar-first, and set the with of that.

i looked into that particular theme.

revert all the css editing and go to the theme settings, under "layout setting -> sidebars layout" try using the 'fixed' options instead than the 'variable'.


Managing display of articles promoted to front page

Go to yoursite/admin/config/system/site-information
Change the Number of posts on front page to 3 or whatever you want.

Please note your allow to display up to 30 post, however if you want to show more then 30 than i suggest to use View module, to create page of your article list


I can't see anything direct, loading the node type entity itself is an option though:

$bundle_label = \Drupal::entityTypeManager()
  ->getStorage('node_type')
  ->load($node->bundle())
  ->label();

Or as Berdir pointed out in the comments, there's a quicker way through the entity reference field:

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


How to keep the same vertical tab open on AJAX call?

We can save in $form_state html id current vertical tab.
Only, be sure, do not forget to set custom ids your tabs


Module that adds &nbsp after one letter words

Traditional Drupal way is to use Text Filters. Here you have introduction text - it's for Drupal 6, but nothing important changed since then. Examples for Developers contains example filter. Use regex replace or other method from stackoverflow to make actual replacement:

preg_replace('/(?<=\b[a-z]) /i', '&nbsp;', $s);

All the rest you can copy-paste from Examples.


How to pass negative values to config-set

The (ugly) work-around is:

echo '-1' | drush cset block.block.myblock_name weight - -y

You don't need to specify that format is string as that is the default.

This seems to be a general problem with Drush commands; values starting with a dash is interpreted as arguments. See bug report for similar issue with vset - https://github.com/drush-ops/drush/issues/378


Action links available options / caching

The following example implements an action link in Drupal 8 with the requirement of user-specific caching. This should allow you to hide/display the action link for the different users on your page. Providing different titles for different users should also work.

mymodule.links.action.yml:

entity.mymodule.add_form:
  class: Drupal\mymodule\Plugin\Menu\LocalAction\UserAction
  route_name: entity.mymodule.add_form
  title: 'Link to Add Form'
  appears_on:
    - entity.mymodule.collection

mymodule/src/Plugin/Menu/LocalAction/UserAction.php:

<?php

namespace Drupal\randomintro\Plugin\Menu\LocalAction;

use Drupal\Core\Menu\LocalActionDefault;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Routing\RouteProviderInterface;
use Drupal\Core\Routing\RouteMatchInterface;

/**
 * Defines a test local action plugin class.
 */
class UserAction extends LocalActionDefault {

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, RouteProviderInterface $route_provider, AccountInterface $current_user) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $route_provider);

    $this->currentUser = $current_user;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('router.route_provider'),
      $container->get('current_user')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheContexts() {
    return parent::getCacheContexts() + ['user'];
  }

  /**
   * {@inheritdoc}
   */
  public function getRouteParameters(RouteMatchInterface $route_match) {
    // If the user is not Anonymous.
    if (!$this->currentUser->isAnonymous()) {
      // Getting the uid.
      $uid = $this->currentUser->id();
      // Adding the link.
      return ['user' => $uid];
    }
    return [];
  }

}


So what I ended up doing was to create a module that reads from a json file, and adds the translation. (Import controller + drush command)

a) Load up the custom menu items by menu name:

$main_menu_items = \Drupal::entityTypeManager()->getStorage('menu_link_content')->loadByProperties(array('menu_name' => $menu_name));

b) Go through your menu items, foreach of them check if your menu link title matches one in your json/po file/config.

c) Check if you already have a translation on that menu item, then remove the old translation or skip.

if ($menu_item->hasTranslation('fr')) {

d) Finally add the translation that exists in your file.

  $menu_item_fr = $menu_item->addTranslation('fr');
  $menu_item_fr->title = $translation_json[$menu_name][$link_title];
  $menu_item_fr->description = '';
  $menu_item_fr->save();

This is essentially what my json looked like:

{"menu_name": {"english_link_title":"french_link_title"}}

Do hope this helps someone else, or someone can think up a better answer.


Filter by taxonymy ID with multiple field in contextual filter

On the views edit page:

Under Advanced: Create a relation to the field that holds the refrence to the taxonomy id ("Taxonomy term referenced from field_your_field_name_that_holds_the_reference")
Under Advanced: Create a contextual filter for the Term ID and select the previous made relation as relationship. As final step click on "more" on the same page beneith, and select allow multiple.

Now you just add multiple taxonomy id's as  1+2+3 (for OR) or 1,2,3 (for AND).
And if you want to select on multiple fields:
Repeat the process to add more fields and then you can do:
/1+2+3/877,454,453/345,345,345
Each slash represents the contextual filter field
1+2+3 is contextual filter one
877,454,453 is contextual filter two
Etc.


How to add web app icon png to root document folder?

place an icon file in PNG format in the root document folder called apple-touch-icon.png

Literally that - put a file called apple-touch-icon.png in your web root. Drupal doesn't affect static files, it won't interfere.


"Drupal root not found. Pass --root or a @siteAlias in order to see Drupal-specific commands"

A missing composer.json file was the solution for me.


Updating a taxonomy term, with extra fields - taxonomy_term_update does not exist

try

    $terms = taxonomy_term_load($tid);
    // echo "<pre>";
    // print_r($terms);
    // die();
    //dsm($terms);
    $terms->extra_field_1[LANGUAGE_NONE][0][$column_name] = 23;
    taxonomy_term_save($terms);

Use print_r or dsm(devel module if installed) and check the "$column_name".

After print the $terms you able to get "$column_name" replacement. Update that and save.


How can I add a Dismiss Button to a Webform Modal Conformation?

Here is how I got it working:
(function($) {
  Drupal.behaviors.hideModal = {
    attach: function(context, settings) {
        $('body', context).on('click', '#button-close-modal', function(e){
            $('.webform-confirmation-modal--content', context).dialog('close');
        });
    }
  };
})(jQuery);


Sorting options in an entity reference Select list within a form

To enable this functionality in Drupal 8,

Add a view for your entity type.
Create an Entity Reference view display with a field and sort option (See comment from @saramm1 above).
Edit the Field Settings for the entity reference field and change the "Reference Type" to use a view.


What you need is to create an installation profile.

Follow the instructions on drupal.

How to write a D8 profile

Move the files from the config/sync folder to config/install folder. Be sure to delete core.extension.yml and remove all UUIDs.

Optionally, you can try this project:project config_installer


Make sure to put in the "Host" of the MySQL database under "Advanced Configuration" as db and not the default localhost.


Field twig template : override HTML output

You only need the twig content between <ul> ... </ul>. The variables you set  are not used anywhere. And you don't need to extend the field template from the base theme to override it. Only if you want to replace twig blocks.

field--field-fichier-joint.html.twig

{%
  set classes = [
    'class1',
    'class2',
  ]
%}

<ul{{ attributes.addClass(classes) }}>
  {% for item in items %}
      {% set zebra = cycle(['odd', 'even'], loop.index0) %}
      <li{{ item.attributes.addClass(zebra) }}">{{ item.content }}</li>
  {% endfor %}
</ul>

If you still get an WSOD enable error reporting to see in which file and line number the error occurs.


Paths to images are messed up in Vagrant

you should add your site name to the base url in .htaccess file and uncomment the base url code.


In a message about a new comment, how to tell if the comment needs approval or not?

There is a great tutorial on Rules with a similar use case.


How can I bypass the login screen during checkout in Commerce 2?

I was able to solve this problem by editing the Default checkout flow at /admin/commerce/config/checkout-flows, where I could simply disable the Login or continue as guest step.


Permissions for seeing translated custom menu link items

Make sure your menu link translations are actually published, there's a checkbox in the edit form. I think there are some bugs there that this isn't set properly when doing it from a node edit form.


Force views to write exposed form block info to {block} table during install profile

Doing a views_get_view() cannot actually load the view. From what I can tell, it appears that install profiles do not have access to views provided by hook_default_views.


How do I debug/kint Simple XML Sitemap link array?

As Clive said, you will need to make sure that both the devel and kint modules are enabled.  (NOTE: D8's Devel 4.0 now includes the kint module but requires 'composer require kint-php/kint' to be done to make it work) Then you can add your hook and just do a ksm($links); statement.
Make sure to clear cache so the hook will be found.  Then doing a regenerate of the sitemap(s) in the gui will product the kint output that you can examine for the structure.
Also, not totally sure, but I think this hook has to be in a module and will not work in the .theme file.
FYI - Here's a code snippet from a working hook that does what you want, including removing untranslated nodes.
/**
 * Implements hook_simple_sitemap_links_alter().
 */
function my_module_simple_sitemap_links_alter(&$links, $variant) {
  foreach($links as $key => $link) {
    // Filter out any node/### URLs
    if ( preg_match("!(/[a-z-]*)?/node/\d?!", $link['url']) ) {
      unset( $links[$key] );
      continue;
    }
}


Got the answer for you! Check out the core tabledrag.js lines 862, 869, 1150, 1160. These are all functions that you can overwrite to react to tabledrag events! Here's a code example I wrote for you:

Drupal.tableDrag.prototype.row.prototype.onSwap = function (swappedRow) {
      (function ($) { // Important as this allows $ for jQuery.
        alert('React to tabledrag!');
        return NULL;
      }(jQuery));
    }


Display Suite Token Fields in Custom Block Types

Does it work when you don't limit?

And just to be double sure.... you have got to Structure > Block Layout > Types > (actual type) > Manage Display.  And once there, in the bottom area where it says "Layout for basic in default", you selected a "Select a layout" of something other than "-None-".  Because the fields won't show until you select a Display Suite layout.


Where is the entity in code field? [Display suite module]

SOLVED!

I needed to enable 'Display Suite Format' module.
If enable it give me a new text format 'Display Suite code' which give an $entity variable inside a code field!


View watchdog logs at Administer >> Logs >> Recent log entries. (admin/logs/watchdog)

More details in this post Drupal.org: Watchdog: monitor your site


For fieldsets I think you have to include the parent as well.

Try changing

form_set_error('phone', 'Ditt nummer v....
to

form_set_error('contact][phone', 'Ditt nummer v....

You can read more here: http://drupal.org/node/678816


Based on Ashlars's comment.

A minipanel, provided by Panels, is for anyone not used to Panels, essentially a block, that supports internal layouts. You can use a mini-panel to wrap several different blocks (and many other things, views, nodes, etc) into a single "block".

Unfortunately, I must admit that documentation is scarce on this topic. I will refer you to this other question: looking for a good mini panels tutorial.


What you have done is to create a menu task on the route entity.node.canonical with the title of Import JSON from file which links to the route entity.node.import_form.

The error you are getting is because the route entity.node.import_form (the link of the task) doesn't exist. You have to either depend/enable the module that provides this route or create the route yourself.


I don't know that that's possible as described, but you could do something like this:

create a content type with only one field, accessible to the staff member
add an entity reference to the content type housed in the view

  Provides a field type that can reference arbitrary entities

create a relationship to the staff member content type

This would allow the Staff member to change the value in the content to which they have access, which would affect the View, but not directly have admin access to the View or the Admin sections of the Views UI


Can the reaction of "Cron Maintenance" in the Rules modules pull data from nodes?

Previous Attempt: Have a node become stickied when a comment is
  posted. Then unsticky the node after a certain amount of time. If a
  node is not stickied, send an email. This worked for one evaluation
  time rather than having evaluation over the life of the node.

Activate the Rules Scheduler module (comes with Rules)

Sorry, I missed a step. For your If and Else Statement Add Action of Schedule Component Evaluation and select your component. So you basically re-schedule your component evaluation. Thus, you get continuous evaluation.

Result:


How would I add a section header sub-image based on path in Drupal?

The simplest solution that Drupal provides.
You can create 2 blocks with images. Than set visability on different pages.
This is it.


How do I filter the "admin/content" page through it's url?

By default this is not possible.
Easiest I can see would be to create a view - if you have views module installed - that has the same path which will override the default Drupal content screen.

Then you can either create argument for the content type as part of url and/or expose filters and since the filters are being passed via get parameter, you will be able to construct an url to point to the filter selection.

Which is almost what administration views module does. You might want to extend these views with arguments, filters, etc...

Other option would be to create custom functionality that would "hook" into the default functionality.


How To Show Node Comment Count in node.tpl?

You can use $comment_count in node.tpl.php.

  $type: Node type, i.e. story, page, blog, etc.
  $comment_count: Number of comments attached to the node.


Search API + Apache SOLR - No highlighted excerpts returned for stemmed terms

I'm guessing that you, like me, had the "Highlight" filter enabled, which you shouldn't actually do for Solr. I found this nugget of info here:

https://www.drupal.org/node/2358065#comment-9319765

Though Solr returns the excerpt, that processor removes it if there's not an exact match.


Create such sub-theme folder manually. The folder name you'd use for it will be the machine name of your subtheme.

For more details, refer to:

"Creating a sub-theme" (= Community documentation that applies to any sub-theme).
"Sub-theming" (= documentation about sub-theming specific to Drupal's Bootstrap theme).

If you prefer to look at a great (I think) example of a (contributed) Bootstrap sub-theme, then have a look at the Bootstrap Business theme.


Ajax callback change "checked" radio button

You would need to show more code (the form definition), I would recommend you to try:

unset($form['input'][$item]);

Right prior to calling:

$form[$item]['#default_value'] = $entry->$item;

Relative links: https://www.drupal.org/node/1082818#comment-5335080


Answered in comments, but just moving the answer here for posterity's sake.

The theme was loading the .js file, but the permissions were restricted, so the server was returning a 403 error. Changing the permissions fixed the issue.


User role referencing when they might not exist

Lets say there is a module in drupal which just does what you are asking for, how would you like it? :P

I found this module recently. TextNodeReference

What this module does is

It creates a new widget for the references. Once the widget is enabled,
If the referencing node exists then it will store a reference to that node in the table.
If the node doesn't exist already on the system, then it will store it as text. But when the node with the same title is created, it will auto-reference it to the node.

Caveat : When that node doesn't exist, make sure that you are entering that right title(for the author or venue), and then use the same title when creating the actual node for that entry(author or venue).

You can thank me later, but do thank Boobaa who wrote this module.


How do I integrate a custom filter inside a view

I found a solution for above. I can add a field in the filter criteria selecting the URI. And expose that filter to the user with a grouped filter. In the grouped filter I can define my own keys and parameters with an operator. That worked pretty well.


How to dynamically create Drupal 7 tables based on form API input values?

As I read the output of the error message, I suppose the values you are trying to parse do not contain the type of the database field.

Did you check your PHP error log as well? There might be PHP warnings, stating that $arr[1] is not set.

Verify your parsed values and make sure they contain the type information.

An additional note: I do not know your special use case. But creating a new table on each template might easily bloat your database structure. Maybe you find a better solution to store your information within one dedicated table, using your template ID as identifier and serialized arrays holding the information?


Custom Theme - Add page specific meta tags / title to pages

You can attach the tag to the page's render array via hook_page_attachments_alter().

An example from the related change record:

function MYTHEME_page_attachments_alter(array &$page) {
    $viewport = array(
        '#type' => 'html_tag',
        '#tag' => 'meta',
        '#attributes' => array(
            'name' => 'viewport',
            'content' => 'width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no',
        ),
    );
    $page['#attached']['html_head'][] = [$viewport, 'viewport'];
}


Problem with aggregated CSS/JS on flush cache

https://drupal.org/project/advagg might be the solution you're looking for.

If you want to flush both caches this will help https://drupal.org/project/expire


How to show the slide dots using the Slick Carousel module?

You need to enable the slick module and the slick ui module, after that go to Configuration -> Media -> Slick Carousel (admin/config/media/slick).

From there you can edit the default profile for slick carousel or create a custom one. There you can enable or disable dots and of course various other options.


Display a block based on current select option

Don't try to add the fields in a form alter hook. Do this in the field UI of the user entity /admin/config/people/accounts/fields. To change the visibility of fields dependending on the content of another field use

Conditional Fields

or the Form #states API directly, see How can I hide or show fields using states with hook form alter.

EDIT: The form #states api did the trick.


How to display field collection fields in tabs on add another item button?

I have found the solution.

I used multiple value widget module. It does exactly the same.


To translate custom block text you need to do the following:

Download the Internationalisation module (i18n)
Enable String translation module (i18n_string)
Go to Configuration > Regional & Language > Multilingual Settings >
Strings (admin/config/regional/i18n/strings)
Enable Full HTML in Translatable text formats
Save


Caching results from an API via drupal_http_request

You could use the Drupal's cache API to store the response doing something like:

if (!cache_get('my_module_cache')) {
  $data = drupal_http_request($url, $options); // Add the param for the request to web service
  cache_set('my_module_cache', $data, 'cache',  REQUEST_TIME  + (3600 * 24 * 30 * 6)); // Stores in cache table and expires after 6 months
  return($data);
} else {
  $return = cache_get('my_module_cache');
  return($return->data);
}

Depending on how many times you need to get that cached value on same execution, you could also use drupal_static().

On the example that I provided above, the expire policy is only based on time (6 months), in your case, you will need to analyse carefully the expire policy you are going to implement to expire/renew the cached value.

Lullabot has a great article about Drupal cache: A beginner's guide to caching data


how do I get the user ID other than the one for the current logged in user?

Assuming that you're viewing a page at a path like /user/42, then you can use the RouteMatch class. Your example is close, but you need to change the parameter passed to the getParameter() method. The parameter in this case is named 'user' not 'node'. You can determine the parameter name from the route definition. Not all routes have parameters, but when they do, they are specific to the route in question.

In this case the route (entity.user.canonical) is defined by \Drupal\user\Entity\UserRouteProvider::getRoutes. And the 'user' parameter is the UID of the user entity in question. Given that, you can use RouteMatch to get the ID in one of two ways.

Load the $user object specified by the user parameter. Which is probably more common. I'm guessing if you're trying to get the UID it's so you can load the user object. With this method parameters are processed by the parameter conversion system, which does operations such as converting entity ID parameters to fully-loaded entities

$user = \Drupal::routeMatch()->getParameter('user');
$uid = $user->id();

Or access the parameter value directly:

$uid = \Drupal::routeMatch()->getRawParameter('user');

This change record provides a bit more information https://www.drupal.org/node/2295317


Commerce product options on product basis

Drupal Commerce generally conceives of attributes as those things about a product that a customer might specify on the Add to Cart form to drill down to a particular SKU, i.e. a particular variation in a group of products. From this perspective, you wouldn't have the ability to randomly add options to a product for selection on the Add to Cart form; you'd define attributes as fields on your product type and create a unique product for each potential variation.

You can use line item fields and expose them to the Add to Cart form, allowing the customer to enrich the line item with additional information required for fulfilling the product that do not affect the SKU. There are videos showing both of these different features in our video library:

http://www.drupalcommerce.org/videos

Finally, I met Joshua Needham at BADCamp, and I believe he intends to put some time into the Commerce Product Options module. This was a suite of modules initially developed by hunziker and then left on its own for a year or two. If Joshua is able to get commit access, I'd expect to see some work in there that allowed for product by product configurable bundles of options that are exposed through the line item form. I'd pull up a link for that but drupal.org is down atm. : )


Exposing a type of field operation (flag lists) for search index view

Those flag list operations come from a Views handler; they're applied only to the node entity type in flag_lists_views_data_alter.

The Indexed node isn't a node entity, it's something specific to the search API module (added in search_api_views_views_data). It only contains fields that are indexed, plus any extra stuff search API or contrib modules add on.

I haven't tried it, but you may be able to include the nid in the index, and add a relationship in the View to Content. That would, in theory, give you access to everything that Views knows about for a node.

Failing that, you'll probably have to implement your own Views handler, implement hook_views_data_alter, and find the table whose field handler you need to override (it'll be search_api_index_MACHINE_NAME). The class in includes/flag_lists_handler_field_ops.inc would probably be a good template to start from.


Have you tried the http://drupal.org/project/file_force Module ?
Some details from the module's project page:

File Force Download can be used to force the user's web browser to download the file to disk instead of displaying it in the browser window.
Web browsers today are pre-configured to render various types of media directly, such as text files, various image, video and audio formats, PDF documents, and Flash movies. While it is still possible to save such files afterwards by right-clicking on them and selecting "Save As..", it is sometimes desirable to just offer the file for download in the first place. File Force Download solves this issue by supplying a file with certain HTTP headers which instruct the web browser to download the file to the user's disk instead of displaying it in a browser window.

It should be a good starting point for inspiration for your own module.