The Allowed Formats projects allows you to control the available text formats per field, so you can limit it to plain text. Better Formats is a similar module.

You could do the same with a form alter and set #allowed_formats on the form element. Or you could remove the default comment body field and replace it with a plain text field. Although there might be some code relying on the name/existence of the default body field.


Can't get Emoijone ckeditor plugin to appear on WSYISYG editor

You need to add annotation for ckeditor plugin (more info about annotations based plugins here).

Youtube plugin is using this:

/**
 * Defines the "Youtube Button" plugin.
 *
 * @CKEditorPlugin(
 *   id = "youtube",
 *   label = @Translation("Youtube Plugin")
 * )
 */
class YoutubePlugin extends CKEditorPluginBase {

So you will need to add an annotation like this:

 /**
  * Defines the "Emojione" plugin.
  *
  * @CKEditorPlugin(
  *   id = "emojione",
  *   label = @Translation("Emojione")
  * )
  */
 class EmojionePlugin extends CKEditorPluginBase {

EDIT (thanks @kevin): clear caches after changes.


hook_node_view() hasn't really been removed, the way it's invoked has just changed. As you mentioned, it's now handled by hook_ENTITY_TYPE_view().

So you can either use:

hook_entity_view()

or

hook_node_view()

The latter would make more sense if you're targeting nodes specifically.


Which SELinux setting prevents module upload via Admin interface?

I believe I have pegged the variable in question!

setsebool httpd_can_network_connect on

This allows the web server to connect to the FTP server. So, if you have set up an FTP server and account, but still can't upload modules to Drupal via the front end, try the above command!


Figured it out.  I was using the Client ID instead of the User ID.   It's all good now :).


How to limit country list for address form drop-down?

Found solution here:
https://docs.drupalcommerce.org/commerce2/developer-guide/customers/addresses/countries-and-subdivisions
Created new module "country_limit" added event subsriber like explained there:
<?php

namespace Drupal\country_limit;

use Drupal\address\Event\AddressEvents;
use Drupal\address\Event\AvailableCountriesEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class LimitCountriesEventSubscriber implements EventSubscriberInterface {

  public static function getSubscribedEvents() {
    $events[AddressEvents::AVAILABLE_COUNTRIES][] = ['onAvailableCountries'];
    return $events;
  }

  public function onAvailableCountries(AvailableCountriesEvent $event) {
    $countries = ['AT' => 'AT', 'DE' => 'DE', 'CH' => 'CH'];
    $event->setAvailableCountries($countries);
  }

}

and registered it like:
services:
  # Name of this service.
  my_config_events_subscriber:
    # Event subscriber class that will listen for the events.
    class: '\Drupal\country_limit\LimitCountriesEventSubscriber'
    # Tagged as an event_subscriber to register this subscriber with the event_dispatch service.
    tags:
      - { name: 'event_subscriber' }

Event subsriber class is directly inside "src" dir, since I don't have other functionalities in this module.


Using the user interface, it is not possible to set the same alias pointing to different destinations for the same language.
If a module would execute code similar to the following one, it would be possible to have two records for the same alias.

$path = array(
  'alias' => 'homepage',
  'source' => 'node/1',
);
path_save($path);

$path = array(
  'alias' => 'homepage',
  'source' => 'node/2',
);
path_save($path);

drupal_lookup_path() contains the following code to retrieve the internal path associated with a path alias from the database. $path_language is the last argument passed to the function; when the function doesn't get that argument, it uses the value of $GLOBALS['language_url']->language.

    if ($path_language == LANGUAGE_NONE) {
      unset($args[':language']);
      $alias = db_query("SELECT alias FROM {url_alias} WHERE source = :source AND language = :language_none ORDER BY pid DESC", $args)->fetchField();
    }
    elseif ($path_language > LANGUAGE_NONE) {
      $alias = db_query("SELECT alias FROM {url_alias} WHERE source = :source AND language IN (:language, :language_none) ORDER BY language DESC, pid DESC", $args)->fetchField();
    }
    else {
      $alias = db_query("SELECT alias FROM {url_alias} WHERE source = :source AND language IN (:language, :language_none) ORDER BY language ASC, pid DESC", $args)->fetchField();
    }

If $path_language is equal to LANGUAGE_NONE (i.e. you are looking for the internal path associated with the language-independent alias), drupal_lookup_path('source') returns the internal path which is saved in the path_alias table with the higher pid (which normally is the latest created row).
If $path_language is not equal to LANGUAGE_NONE, the database rows are ordered to get the language-specific alias before the language-neutral, and then by pid. Also in this case, the returned internal path would be the last created one.

Suppose url_alias contains the following values.

pid   | source    | alias      | language
4     | node/1    | homepage   | und
5     | node/2    | homepage   | und
8     | node/21   | homepage   | it
9     | node/22   | homepage   | it
10    | node/31   | homepage   | xx-lolspeak
11    | node/32   | homepage   | xx-lolspeak

What I would get from that table is:

drupal_lookup_path('source', 'homepage'): node/2
It returns the last created alias that is language-independent.
drupal_lookup_path('source', 'homepage', 'es'): node/2
There isn't an alias for Spanish, and the function fallback to the language-independent alias. It gets the last created alias.
drupal_lookup_path('source', 'homepage', 'xx-lolspeak'): node/32
It returns the last created alias for Lol Speak.


How to return boolean with math expression comparison in Views

Easiest method is to either use hook views view pre render out a preprocess function.


D6 Is it possible to set node reference field and use this value in another field on the same node/add form?

These two modules are intended for that purpose and have D6 versions.  I think Dependent Fields sounds closer to what you want, but Hierarchical Select Node Reference may work almost as well.

Dependent Fields

  The Dependent Fields module (formerly AHAH Dependent Fields) allows cck based fields to specify another field as a controller field, and react to its changes on the form using AHAH/AJAX without the form re-loading.

Hierarchical Select Node Reference

  This module allows the use of Hierarchical Select form element as a widget for CCK node reference field, both in node add/edit form and in views filter.


Drush Site Install does not populate table prefix

For the problem of dropped tables, you can use --db-drop-existing-tables=FALSE.

I'm looking for an answer to the prefix problem too ...


How do I programmatically place a block?

To provide a plugin block you can build an array of settings and pass it off to \Drupal\block\Entity\Block::create() to create the Block object and save the instance.

For example if you wanted to add a Devel Execute PHP block to the Seven theme:

$values = array(
  // A unique ID for the block instance.
  'id' => 'devel_execute_php_1',
  // The plugin block id as defined in the class.
  'plugin' => 'devel_execute_php',
  // The machine name of the theme region.
  'region' => 'content',
  'settings' => array(
    'label' => 'Execute PHP',
  ),
  // The machine name of the theme.
  'theme' => 'seven',
  'visibility' => array(),
  'weight' => 100,
);
$block = \Drupal\block\Entity\Block::create($values);
$block->save();


What is the difference between a JOIN and a RELATIONSHIP in hook_views_data_alter()

From my experience, a join is always done when the query is executed. This means that you can utilise the fields on the joined tables without adding a relationship in the view. When a join is used, I don't think the views information tied to that table is pulled in. For example, you won't be able to add relationships tied to that table.

A relationship is a choice that the user can make on the view. They can choose to add the relationship (from the section on the right side of the view). When a relationship is added, the views information tied to that entity is also pulled in. For example, you will be able to add relationships linked to that table.


Scheduled rules execute a hour after they are supposed to

Cause 1:

After a rule is scheduled (using the Rules Scheduler submodule), it will only actually execute next time cron runs. Example:

schedule a rule to execute at timestamp X.
if the next time that cron runs is at Y mins after timestamp X, then the Rules execution will only happen then (= at Y mins after timestamp X).

Cause 2:

If your site is set to the correct timezone, but your users are set to a timezone that is 1 hour ahead, then that might also explain what's happening. In that case, correct the timezone accordingly.


How do I auto enable modules within an install profile

You need to add them as dependencies in the .info file. To take a segment from standard.info:

dependencies[] = block
dependencies[] = color
dependencies[] = comment
dependencies[] = contextual
dependencies[] = dashboard

To add a little reference from How to Write a Drupal 7 Installation Profile:

  The contents of the profilename.info file are as follows:

  The name, description, and core assignments are all required.
  The dependencies list includes all modules that will be enabled when this profile is installed (the ones above are the defaults from the Standard install profile).
  You can optionally include other declarations that can also appear in module .info files.

(Emphasis mine).

So enabling views would just be:

dependencies[] = views

And if you want the UI:

dependencies[] = views_ui


How to replace links and embedded image references after migrating of content

Writing a script that does a node_load(), search/replace, and then node_save() is definitely the best way to go about it, and I would argue that it is also the "proper" way to handle the situation.  If you go with this approach, you can refine and/or alter the script each pass to account for differences in the URLs.

In the past, I have

Use rewrites in .htaccess
Done search/replace on a database backup file
Put search/replace in a preprocess_page

to handle the situation, and all of these are not ideal, mainly because of slight variations in URL structure.


How to update locale after editing a .po file?

Just Import your file from config menu then translate interface import
admin/config/regional/translate/import
and then import your file


Hopefully you actually used a date field for "release date".  If so, just create a view and you normally would then in your filters add your release date field. Set it to a relative date text. Make it "greater or equal to" and insert " now" into the relative date.


To get this to work we need to add the #states functionality to every field collection after the ajax callback has taken place.

To do this add an #after_build function to the field collection item in hook_form_alter:

$form['field_witnesses'][LANGUAGE_NONE]['#after_build'][] = 'field_witnesses_after_build';

And then in the after build function loop over the elements to add the #states behavior:

function field_witnesses_after_build($form, &$form_state) {
    foreach($form as $k => $v) {
        if(isset($v['#entity_type']) && $v['#entity_type']=='field_collection_item') {

            $form[$k]['field_employee_name']['#states'] = array(
                'visible' => array(
                    ':input[name="field_witnesses[und]['.$k.'][field_person_type][und]"]' => array('value' => 'Moto Employee'),
                ),
            );

        }
    }
    return $form;
}


The Custom Search module provides easy control over many of those search options.


Translate the allowed values list of an entity access field?

As @4k4 already said in his comment, if you have the Configuration Translation module enabled, you simply go to your-site/en/admin/structure/types/manage/your-content-type/fields and select the list field you want to translate (see screenshot below).


How do I get a block configuration value in a module?

You can load the block configuration entity, and get the settings.

$block = \Drupal\block\Entity\Block::load($block_id);
if ($block) {
  $settings = $block->get('settings');
  $my_text_field = $settings['my_text_field'];
}

$block_id is the machine name you see in the block layout when you save the block.

Edit: Store module configuration

If you want to store configuration for modules don't use a block form, but use a configuration form. Reference https://www.drupal.org/docs/8/api/configuration-api/working-with-configuration-forms
(see comment from @Berdir)

Dump all blocks and their settings

$blocks = \Drupal\block\Entity\Block::loadMultiple();
foreach ($blocks as $key => $block) {
  $settings = $block->get('settings');
  var_dump([$key => $settings]);
}


Rules only with module logintoboggan. Then you will have Event: when user account is active

With custom module hook_user_login and you must check for custom fields filled only once like timestamp.


Field weight in display mode is not respected on custom entity

After debugging the Drupal\Core\Field\FormaterBase on how the fields getting rendered, it seems the weights are getting applied to each field in Drupal\Core\Entity\EntityViewBuidler, but they are not getting rendered in the order at the entity level.
So providing a theme for the entity using hook_theme and a preprocess solves this issue. Here is the code:
// mymodule.module

use Drupal\Core\Render\Element;

/**
 * Implements hook_theme().
 */
function mymodule_theme() {
  return [
    'myentity' => [
      'render element' => 'elements',
    ],
  ];
}

/**
 * Prepares variables for myentity templates.
 *
 * Default template: myentity.html.twig.
 *
 * @param array $variables
 *   An associative array containing:
 *   - elements: An associative array containing the entity
 *     information and any fields attached to the entity.
 *   - attributes: HTML attributes for the containing element.
 */
function template_preprocess_myentity(array &$variables) {
  foreach (Element::children($variables['elements']) as $key) {
    $variables['content'][$key] = $variables['elements'][$key];
  }
}

<!-- myentitty.html.twig -->
<article{{ attributes }}>
  {% if content %}
    {{- content -}}
  {% endif %}
</article>


apply condition to pages created by user roles

if(isset($node) && $node->type == 'page') {
  if($node->uid) {
    $node_author = user_load($node->uid);
    if(is_object($node_author)) {
      if(in_array("editor",$node_author->roles)) {
        // This is the condition to match the current node author belongs to editor role.
      }
    }
  }
}


Newly created node type is always disabled

Drupal base install uses this configuration to create the basic page content type. Try to modify the custom value just like the example underneath:

$type = array(
    'type' => 'page',
    'name' => st('Basic page'),
    'base' => 'node_content',
    'description' => st("Use basic pages for your static content, such as an 'About us' page."),
    'custom' => true,
    'locked' => true,
    'modified' => true,
    'disabled' => false,
);

Edit

I've just checked the code of some Drupal core modules how they manage the creation of content types within code.

The Blog module defines the content type within the HOOK_node_info (just like you did). This to notify Drupal about the new type. The HOOK_install only add fields to the content type. The module also implement the HOOK_form for the content creation form and HOOK_view for the rendering.

// blog.install
function blog_install() {
  // Ensure the blog node type is available.
  node_types_rebuild();
  $types = node_type_get_types();
  node_add_body_field($types['blog']);
}

// blog.module
function blog_node_info() {
  return array(
    'blog' => array(
      'name' => t('Blog entry'),
      'base' => 'blog',
      'description' => t('Use for multi-user blogs. Every user gets a personal blog.'),
    )
  );
}

}


Once again, the problem sat in front of the screen ;)

Like @rooby said, there was a mistake in the html returned. A missing
 tag messed up my layout. Adjusting this solved my problem. Thanks!!

But to be able to influence the layout of custom html a bit more generally, I did this:

When a module returns output without first passing it through a theme function, it ends up in page['content']['system_main']['main']['#markup'], whereas in a normal page, there would be no #markup on this level of the page array, only elements like node, pager, #block etc. So finding page['content']['system_main']['main']['#markup'] means some custom code has been returned by some custom module.

So in my theme's template.php, I implemented

function mytheme_preprocess_page(&$variables, $hook) {
    if ( $variables['page']['content']['system_main']['main']['#markup'] ){
        $variables['page']['content']['system_main']['main']['#markup'] = '
' . $variables['page']['content']['system_main']['main']['#markup'] . '
';
 }
}

Thank you guys very much! Always awesome how good the feedback in the drupal community is.


How can I theme the Views Exposed Filter Results page?

You can use the devils module to get theme help. Also there is the <?php print $classes; ?> function that i have for instance on my div  with the class container div. And there I see for example the class page-searchresults. Giving away that I can use page--searchresults.tpl.php as a template file for theming that page.


Customising Search Box in Search Results Adding OnBlur and OnFocus Attributes

If you want to add attributes to the form itself you need to do it on the $form array:

$form['#attributes']['onblur'] = "if (this.value == '') {this.value = '".$form['search-form']['#value']."';}";

I'm just guessing but I think you're expecting there to be a search-form element because that's the CSS ID of the form? That's not quite how it works with the FAPI, the elements are in a hierarchy that will eventually be rendered down to HTML. Until that rendering happens the elements have no concept of an ID/class etc., so you won't find them in the array under the ID/class.


How to skip (not ignore) some rows in migration?

Migrate doesn't work with attempts, so it always performs one migration (that you can update with the latest content).

Considering the fact you need some parent do be defined first, it might be easier to apply some sorting, so the parent is always created before the child (and you would not need several attempts). If you are migrating from a Drupal (7) site you can use the menu_links table for this. See the section about book hierarchies here: Migrating Book module nodes for a similar situation.

If you are not migrating from Drupal, but some other system you might want to look for a similar table.

As an alternative, you might be able to use the handleSourceMigration() function to see if the old parent id is already migrated (function returns NULL otherwise) and skip rows based on that, then re-run the migration. But I have never used this method and it might not work.


Round Commerce Price: in tpl.php or template.php

A better way to adjust currency formatting, using the relevant Commerce currency hooks, is with

hook_commerce_currency_info_alter

and adding your own commerce_currency_format handler

e.g:

/**
 * hook_commerce_currency_info_alter
 *
 * Add custom currency format to selected currencies
 */
function MY_MODULE_commerce_currency_info_alter(&$currencies){
  $currencies['IDR']['format_callback'] = 'MY_MODULE_commerce_currency_format';
}

/**
 * Currency format callback
 *
 * Remove decimal places from output
 * while keeping commerce_amount_to_decimal formatting the same
 *
 * See: commerce_currency_format
 */
function MY_MODULE_commerce_currency_format($amount, $currency, $object = NULL, $convert = TRUE) {

  // Format the price as a number.
  // In our case, we remove decimal places
  $price = number_format(commerce_currency_round(abs($amount), $currency), 0, $currency['decimal_separator'], $currency['thousands_separator']);

  // Establish the replacement values to format this price for its currency.
  $replacements = array(
    '@code_before' => $currency['code_placement'] == 'before' ? $currency['code'] : '',
    '@symbol_before' => $currency['symbol_placement'] == 'before' ? $currency['symbol'] : '',
    '@price' => $price,
    '@symbol_after' => $currency['symbol_placement'] == 'after' ? $currency['symbol'] : '',
    '@code_after' => $currency['code_placement'] == 'after' ? $currency['code'] : '',
    '@negative' => $amount < 0 ? '-' : '',
    '@symbol_spacer' => $currency['symbol_spacer'],
    '@code_spacer' => $currency['code_spacer'],
  );

  return trim(t('@code_before@code_spacer@negative@symbol_before@price@symbol_spacer@symbol_after@code_spacer@code_after', $replacements));
}


Auto assign organic group to a content type

I just ran into this problem with hooks. It's being saved but you won't see this in node_insert due to the caching system of nodes in Drupal. Add this before your dpm code and you'll see the results immediately.

entity_get_controller('node')->resetCache(array($node->nid));

I'm so happy I can stop someone else from banging their head on the wall like I did. Ha.


Using computed field to calculate total hours for a datetime field but to exclude all weekend hours

I would :

$duration = $start_date->difference($end_date, 'hours');
// Place this :
if($start_date->format('Y-W') != $end_date->format('Y-W')) {
  $difweeks = $start_date->difference($end_date, 'weeks');
  $duration = $duration - intval(48 * $difweeks);
}
$entity_field[0]['value'] = $duration;


Creating a related content block in Drupal 7 using OpenCalais

Open Calais will take your content and through their web service create metadata for it which the opencalais module can use to create an amazingly diverse variety of taxonomy terms that are applied to your nodes. It is a really cool service.

Once your content had the tags added by OpenCalais you could use one of the modules that provide a "Similar Content" block: http://drupal.org/node/323329 . Most of them are based on taxonomy terms. The More Like This module doesn't look like it has a D7 release but looks like it also uses taxonomy terms.

The simplest method for making a "More Like This" block might be to use Search API Solr or ApacheSolr. If you have full access to your server it is not that difficult to install. Solr's version of More Like This uses Solr's search engine to determine similar content on your site. Also a very very cool technology.


file_usage_add: custom type for my module

Yes, type just needs to be something unique within your module's types of file usage. The value of the string itself is arbitrary.

So if you have a module which stores pictures of cats and dogs, and you want to address those two different types of usage separately, you might use (contrived examples obviously):

$cat = MYMODULE_load_cat('whiskers');
file_usage_add($file, 'MYMODULE', 'cat_pictures', $cat->id);

$dog = MYMODULE_load_dog('fido');
file_usage_add($file, 'MYMODULE', 'dog_pictures', $dog->id);

But the type for those could just as easily be cat_foo and dog_foo, all that matters is that you (the module developer) know what they are, so they can be used appropriately with file_usage_delete().


I had to do the exact same thing yesterday, and I am still looking for a more Drupal 8 way to do this, but haven't found it. I ended up doing it this way:

<?php

/**
 * @file
 * This is my module.
 */

use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Implements hook_form_alter().
 */
function MODULE_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'user_form') {
    $form['actions']['submit']['#submit'][] = '_MODULE_goto';
  }
}

/**
 * Make the form go to route.id.
 */
function _MODULE_goto($form, FormStateInterface $form_state) {
  $form_state->setRedirect('route.id');
}

I am still very interested in doing it a different way, my module looked so clean without the .module file :).


How can I view what causes a page to load slow?

Yes you can figure out which function(s) spends more time in the execution by using a profiling module, then you can optimize that particular function(s)

Below are the available profiling modules in Drupal 7(AFAIK),

XHProf
Profiling

Personally I used XHProf and it helped us lot to improve the performance.

  XHProf is a hierarchical profiler for PHP. It reports function-level
  call counts and inclusive and exclusive metrics such as wall (elapsed)
  time, CPU time and memory usage. A function's profile can be broken
  down by callers or callees. The raw data collection component is
  implemented in C as a PHP Zend extension called xhprof. XHProf has a
  simple HTML based user interface (written in PHP). The browser based
  UI for viewing profiler results makes it easy to view results or to
  share results with peers. A callgraph image view is also supported.

In addition to this you can also look into Performance Logging and Monitoring module which was removed from Devel.


How to use data in a content type from another content?

I will suggest to use Entity reference module.

  Provides a field type that can reference arbitrary entities.

Also you can take a look References module.

  This project provides 'node_reference' and 'user_reference' field
  types.


If you want to create an alias using hook_url_outbound_alter(), you need to implement also hook_url_inbound_alter(), since the former is for links output from Drupal, and the latter is for links received from Drupal. The former changes the path with its alias, while the latter changes the alias with the equivalent path.

Keep in mind that:

If you are not doing conditional replacements, then it is probably less performance-heavy to use the normal Drupal path aliases
Between the arguments taken from hook_url_outbound_alter(), $path is the path as already changed by the previously executed module, while $original_path is the path before being changed from any module

Also, $options['alias'] is really a boolean, not a string, which tells url() whenever the path being passed to the function is already a path alias. In the case it is, drupal_get_path_alias() will not be called.


Remove import instance from list using Migrate Tools module

So you want to get rid of the migrations so that they don't appear in the drush ms output? Do this:

Removing imported content

Upon reading your question the second time, I thought you might even be asking "How to remove the content which is imported already?". If that is your question, then try drush migrate-rollback or drush mr for short. See documentation with drush mr --help.

Deleting the migrations

If you are using configuration management, then delete the relevant config YML files from the config sync directory and do drush cim. There should be files named migrate_plus.migration.MIGRATION_ID. It will ask for confirmation and if you say y, the relevant migrations will be deleted.
If you are not using configuration management, do drush config-list. Now, for every migration you want to delete, search for the name of the migration in the output of the config list and do a config-delete for it. Example: drush cdel migrate_plus.migration.MIGRATION_ID Consider using config management in the long run.

Deleting migration mappings

The migrate module might have created some mapping tables in the database to track your migrations. To delete these tables (I assume you know what you're doing), delete the mapping and messages tables for the migration. Example: DROP TABLE IF EXISTS migrate_map_MIGRATION_ID, migrate_messages_MIGRATION_ID. After you do this, you will never be able to do rollback.

Hope it helps.


How do I translate "Please fill out this field." on the user registration form?

This message is coming from the browser and not from Drupal, so, there's not much we can do about this, except for not using HTML5 required attributes.

I have my system in French and the message comes in French, and I don't have the French language installed in my site.

Read more about this in the Drupal core issue about "HTML5 validation is not fully accessible".

EDIT: It seems that we have a working patch that solve the problem.


Accordion display for views inside panel

You can do it by using these modules :

Panels Accordion

  Panels Accordion provides an accordion display within Panels. By using
  accordions you can fit more content into smaller areas and allow your
  users to expand each section as needed. This uses the existing jQuery
  file for the accordion effect. The layout settings allow you to choose
  the action, effect, and speed for accordions.

views Accordion

  Views Accordion provides a display style plugin for the Views module.
  It will take the results and display them as a JQuery accordion, using
  the first field as the header for the accordion rows.


How to add a notification when a relation or friends publish new content?

When it comes to Facebook type notifications, the Message module is indeed very useful. I'll give an example below of using one view's results view_with_users in another view's contextual filter my_messages_view.

For this to work, in your main messages view, you have to go into your contextual filter's settings (probably Message Author or something), then scroll to the bottom and click Allow multiple values. Instead of the usual Provide default: Current User, we will send all the friends to the view with a module.

Note: In the below example, I've sent the current user's uid to the additional view as an example, but your screenshot doesn't have that contextual filter so it's either not needed, or you may need to tweak the friends view to work programmatically.

custom_views_args.module

<?php

function custom_views_args_views_pre_view(&$view, &$display_id, &$args){
    global $user;
    // Target our Messages view
    if($view->name == 'my_messages_view') {
        // Get users from our friends view
        $friends = views_get_view_result('view_with_users', 'view_display_name', $user->uid);
        // Add each uid to array
        $friends_array = [];
            foreach($friends as $friend){
            $friends_array[] = $friend->uid;
        }
        // Add current user's uid to array as well
        $friends_array[] = $user->uid;
        // Create + separated Contextual Filter
        $messages_con_filter = implode("+", $friends_array);

        // Send the filter to the Messages view
        // $args[0] is the first filter in the list in the view
        $args[0] = $messages_con_filter;

    }
}

See this thread for more info about Facebook-style notification. There may be other useful threads but I happened to answer that one. OP's question should give you some useful pointers. My answer there is quite specific but might give you ideas on how to make messages "seen".

Pierre wrote this in the comments above.

  for each of those friends such notification can be marked as read by each friend individually

If you use a non-global Flag for "seen", then it will do the above.


How to add a checkbox to form builder component settings form?

you have to do it inside the form_id 'form_builder_field_configure'.
Example :

hook_form_alter($form,$form_state,$form_id){
`switch($form_id){
     case 'form_builder_field_configure':
     // You put your code here
     $form['check'] = array(
       '#form_builder' => array(
         'property_group' => 'validation'
       ),
       '#type' => 'checkbox',
       '#title' => t('Check'),
       '#default_value' => '',
       '#description' => t('Check this option if the user should be able
    to upload
     files.'),
      '#weight' => -1,
);
  break;
 }

}
     `

I hope it'll help you.


Multiblock module makes this possible:

  Drupal's block module is limited by the fact that a block can only
  have one instance. Each block has a 1:1 relationship with its region,
  weight, visibility (and other) settings. This means that it is
  impossible to have blocks in multiple regions or to have blocks that
  have different settings on different pages. MultiBlock module solves
  this problem by allowing you to create multiple Block Instances of
  already existing blocks.


Multi Node Add module could be very helpful for you. With this module you can add multiple nodes at once.

  This module provides a new interface for creating nodes where the users are able to select the fields what they want to use for creating the nodes.
  It is designed to create multiple nodes in one round, it's possible to add more node input rows on-the-fly.


Drupal migration api: set custom plugin as source in «process» section

Yes, it is possible to migrate fields but I don't know Metatags.There is an existing issue in Metatags for creating a migration, it may be of help. https://www.drupal.org/project/metatag/issues/2563649


Superfish menu with user id as a parameter

Checkout this module Menu token

  Menu Token module provides tokens, that could be used in title or in
  path of menu items (links). For example, if you create a menu item
  with path: "user/[current-user:uid]", the url will be changed "on fly"
  to: "user/1" (assuming you are user 1).


Have you tried this resource? http://drupal.org/node/354423 , if not, could be useful, is about a menu tab to show only with certain content type.


You're over-complicating this with the extra relationships.

Drop everything under relationships and make sure your drop your relationship references on your fields as well.

Then just add a contextual filter for Content:Author uid and you should be all set as long as that uid is correctly getting passed to the attachment. You will want to end up with something that looks more like the attached screenshot.


Theming mini panel using MYTHEME_preprocess_panels_pane

You can get at the content on a mini panel using hook_panels_pane_content_alter.

It needs to be called in a custom module (see https://www.drupal.org/developing/modules/7)


Getting fatal error in drupal when open the site

Install Context module using drush en "context".

Your site is not get /context_condition_sitewide.inc file or you may be accidently delete this module without disabling it from module list. Try reinstalling this module again.


Creating "view" of "user blogs" specific to a user

There are solution for it by using Contextual Filter in views. Follow this -

Create a new content view and limit it to the content type you want.
Uncheck "Create a page" and check "Create a block." Select the format you want.Click "Continue & edit."
Add a contextual filter for "Content: Author uid.". Do this --

Under "When the filter value is not available," select "Provide a
default value," and select "User ID from URL" from the dropdown.
Because blocks don't understand contextual filters very well, the view
won't work properly without this default value, and all posts of the
given content type will show on all user pages (not just the user's
own posts).
Under "When the filter value is available or a default is provided,"
check "Specify validation criteria" and select "Basic validation" as
the validator. Select "Hide view" from the dropdown.

Save your view.
Assuming that you created a block display, the block will now be available on the Blocks page. Go there and open it.
Set your block to display on all user pages (/user/*) in the correct region. Save the block.
Your block should now appear on all user pages, showing the content written by each user.

Let me know the result if it works fine :)


Tracking how long it takes a user to submit a node edit form?

Here is how I would do it:
/*
 * Implements hook_form_FORM_ID_alter().
 */
function mymodule_form_node_quiz_edit_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['field_duration']['widget'][0]['value']['#type'] = 'hidden'; // hide field
  $form['field_duration']['widget'][0]['value']['#default_value'] = time(); // set default value to start time
  array_unshift($form['actions']['submit']['#submit'], 'mymodule_calc_duration'); // adds a custom submit that runs before the default node submit
}

function mymodule_calc_duration(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $start_time = $form_state->getValue('field_duration')[0]['value']; // get default value
  $duration = time() - $start_time; // calculate duration
  $duration_value = [
    ['value' => $duration],
  ];
  $form_state->setValue('field_duration', $duration_value); // set duration value
}


i want to disable the cloud zoom module in drupal commerce kickstart

Cloud Zoom is a module included in the Commerce Kickstart distribution, if you want to disable it to replace it with something else, just go ahead and disable it in the drupal Modules admin page as Molot suggests.

Update: You can't just disable the module as it's part of the product dependencies in Kickstart.

So the only way you can disable its effects is in each place you see it, for example for the product page, under the Products menu, click on Variation types and then Manage display. Find the view mode, i.e. Full content, and disable/change the cloud zoom options.

More info: http://www.drupalcommerce.org/questions/7582/disable-cloud-zoom


If your preprocess doesn't affect the result of the page, and needs to execute even when the page is served from the page cache, you should move your logic to a Kernel Event subscriber, which replaces hook_boot() and hook_exit() from Drupal 7.

DrupalizeMe has an article on Event Subscribers, but the basic components are creating a class that implements EventSubscriberInterface, and then registering it as a service.

MYMODULE/EventSubscriber/MyEventSubscriber.php

class MyEventSubscriber implements EventSubscriberInterface {
  static function getSubscribedEvents() {
    $events[KernelEvents::RESPONSE][] = ['onResponse'];
    return $events;
  }
  public function onResponse(FilterResponseEvent $event) {
    $request = $event->getRequest();
    $response = $event->getResponse();

    $parameter_value = $request->query->get('parameter_name');
    $response->headers->setCookie(new Cookie('cookie_name', 'cookie_value'));
  }
}

MYMODULE/MYMODULE.services.yml

MYMODULE.my_event_subscriber:
  class: Drupal\MYMODULE\EventSubscriber\MyEventSubscriber
  arguments: []
  tags:
    - { name: event_subscriber }

The request event can modify the request before other components receive it, but cannot affect the response.  The response event cannot modify the request, but is able to alter the response after it has been composed.
If you need to do both, your service object can store some state during the request event, and then alter the response based on that state during the response event.


How do I include ? and = in a form redirection?

In Drupal 6, instead of setting `$form_state['redirect'] with a string, you set it with an array with tree items.

$form_state['redirect'] = array('some-path/search', 'keys=' . check_plain($form_state['values']['input']), '');

The last item would be a value used as anchor. As in your case you don't need it, pass an empty string.


As always, the Drupal documentation has the answer. You need to move the file to the files directory. Also you should never call a theme function directly but instead call the wrapper theme function so:

theme_image_style(...) // Don't do this ever

theme('image_style', ...) // Do it like this and make themers happy.

From the API docs:

  $variables An associative array containing:

  style_name: The name of the style to be used to alter the original image.
  path: The path of the image file relative to the Drupal files directory. This function does not work with images outside the files directory nor with remotely hosted images.
  alt: The alternative text for text-based browsers.
  title: The title text is displayed when the image is hovered in some popular browsers.
  attributes: Associative array of attributes to be placed in the img tag.


Organic Groups: how to add an invite link?

I have recently used Organic Groups Invite module to add this functionality to a site. It will give you a "OG Invite Button" block that you can place on the user view page.

Edit: Sorry the block wasnt included I had added it with a custom module here is the code:

/**
 * Implements hook_block_info().
 */
function og_invite_button_block_info() {
  $blocks['og_invite_button'] = array(
    // The name that will appear in the block list.
    'info' => t('OG Invite Button'),
    // Default setting.
    'cache' => DRUPAL_NO_CACHE,
  );
  return $blocks;
}

/**
 * Implements hook_block_view().
 *
 * Prepares the contents of the block.
 */
function og_invite_button_block_view($delta = '') {
  switch ($delta) {
    case 'og_invite_button':
      $block = array(
        'subject' => t('OG Connect Button'),
        'content' => og_invite_button_block_content()
      );
    return $block;
  }
}

function og_invite_button_block_content() {
  //Get user from profile page
  $user_viewed = arg(1);
  $user_viewed_fields = user_load($user_viewed);

  global $user;
  $output = '';

  $query = db_select('node', 'n')
  ->fields('n',array('nid'))
  ->condition('type', 'group')
  ->condition('uid', $user->uid);

  $result = $query->execute();

  foreach ($result as $row) {

    // Check if the user is already an existing member.
    $exists = db_select('og_membership', 'ogm')
      ->fields('ogm', array('id'))
      ->condition('gid', $row->nid)
      ->condition('etid', $user_viewed)
      ->execute()
      ->fetchField();
    if (empty($exists)) {
      $name = $user_viewed_fields->field_name['und']['0']['value'];
      $output .=  'nid . '/admin/people/invite-users/' . $name . '/' . $user_viewed . '">Invite To Your Group';
    }
  }
  return $output;
}

Some improvements could definitely be made like theming the link.

You will also want to add the name of the group to the button if the logged in user is the owner of more than one group.


Filter to display only modified content in Views

Unfortunately impossible to do it in the current UI.

There are 3 options AFAIK :

try the module views custom conditions
write an alter hook,
or implement a filter handler, which is definitely going to be slightly more complicated, but probably more fun :)

A repaired :) attempt to do the alter hook (with help from another answer on this great site) and the add_where_expression function :

function main_mm_views_query_alter(&$view, &$query) {
  if($view->name == 'admin_views_user') {
    $query->add_where_expression(0,'users.access < users.login');
  }
}

This is the view that comes with the module admin views. there are 2 columns - access and login, both are dates and this seems to work :) you will want to do a dpm($query) first, to see your actual query.


I know it's been over half a year so you may have already found the answer to this, but I thought I would weigh in as it is a process that I am working on myself.

For the Base DN, consider simply using DC=mydomain,DC=com.  I have not had to do this yet, so it was just a thought from their suggestion of using a higher Base DN.

I had problems authenticating until I made sure of these items:

AuthName attribute and AccountName attribute set to: sAMAccountName,
PUID set to: objectGuid
then check the box with the question "Does PUID hold a binary value?

After that, authentication went perfectly.  Good luck!


How can I enter a custom maintenance mode message for a non-English D8 site?

This function should have worked as expected. There is not some feature somewhere else or another way this should have been done. The result described is the consequence of this bug in the Drupal 8 core. As of this writing a patch has been proposed but not settled on. Such are the consequences of playing around with beta releases!

In the mean time the only way to may a D8 site behave is to hack it using one of the following methods:

Manually implement one of the patches described in that issue.
Manually override the core template file (core\modules\system\templates\maintenance-page.html.twig).
Use the Interface Translation module to access the internal localization strings. Override the default maintenance mode string for the target language.

Eventually when that issue is closed and another release cycle happens it should be fixed and providing a custom message from the Admin page will work again as expected.


U are setting $user variable inside if condition, while in if u have condition that $user->uid, so it will compute as false, and it will not go inside if condition.

You will have to write:

global $user;
if($user->uid) {
// Your code

// Edited

global $user;
$user_id = arg(1);

// $user_item = user_load($user->uid);

if($user->uid == $user_id) {
    echo 'I m connected';
    print render ($user_profile['field_mon_statut']);
}


How to unpublish or disable webform components without code for d7?

Webform itself offers no UI-based method for disabling/un-publishing components.

Unless you can find something in contrib that can help (or perhaps convince the developer of webform to add it as a feature), you'll need custom code to achieve it.

As an example you may be able to configure Webform Conditional to disable fields unconditionally, or based on a contrived condition, to simulate the effect. But it wasn't necessarily built for the purpose you need.


Problem with image styles : access denied

It is either you update your Drupal core to the latest version or you You can add the following line to your settings.php to get the images in the site working:

$conf['image_allow_insecure_derivatives'] = TRUE;


Aggregate & Compress CSS / JS Kills Metatag Fieldsets

Most likely there is a parse error in a JS and or CSS file. Check the console for any error; fix them and try again.


Styling different fields before/while rendering it using drupal_render

Yes, assuming I understand correctly that you would like the nodes presented in these tabs to be styled differently to nodes presented normally on the site then I would recommend the first thing you do is set up a separate "view mode" (ie. like "Full content" or "teaser") for this purpose. You can set set up new view mode using hook_entity_info_alter(), Entity view modes or Display Suite. For more information see this tutorial.

Once you have your new view mode in place, you should be able to replace the word "full" in your snippet with the machine name of the view mode. Then you will be able to do some themeing just by changing the formatter settings for your fields in your node type's display settings.

Their are many options for further overriding the themeing of the fields, you could for instance add the following code:

/**
 * Implements hook_preprocess_field().
 */
function MYTHEME_preprocess_field(&$vars) {
  $vars['theme_hook_suggestions'][] = 'field__' . $vars['element']['#field_name'] . '__' . $vars['element']['#bundle'] . '__' . $vars['element']['#view_mode'];
}

...to your theme. This will allow you to create a theme function called something like MYTHEME_field__FIELDNAME__NODETYPE__VIEWMODE() (replace the uppercase words with whatever's relevant in your case).  This will override the funcion theme_field() and you will be able to customise as much as you like.


Pathauto reacts on node save, which doesn't happen when you insert directly via SQL. Pass data from your external application to a custom hook_menu entry, assemble the node from $_GET-data, and run node_save($node), instead of inserting it directly.

Second option, if to enable Services, which allows you to pass data in as json, and have the nodes created that way.

I belive both ways will properly trigger Core hooks, so that pathauto will be called.


field_info_field: how to define the content type name?

What you're doing here seems correct to me, bear in mind that you can leave the bundle parameter empty and then you'll get an array of results keyed by bundle so you can evaluate if there's a problem with the machine name of the bundle you're using:

  $instances = field_info_instances('node');

You can also access admin/reports/fields and take a look to fields and content types available in your site.


I guess you have some options:

You can use Activity Stream, the imported feeds become nodes so they can be re-created using views. You have a choice to enable only the modules you need. The Facebook add-on module also has a Drupal 7 release in the issue queue.

 Activity Stream builds a lifestream, a "River of You", by aggregating all your social activities in one place. Whether it's bookmarks on Del.icio.us, posts from Twitter or your blog, edits to wikis or enjoyed music and movies, anything you create can be gathered into one easy-to-read stream. Every item becomes a full Drupal node, allowing them to be searched, promoted, commented upon, and managed just like any other piece of content within Drupal.

Alternatively, you can use the TB Social Feed, the feed items become nodes so they can also be used with views.

This module we have developed for our responsive Premium Drupal theme TB Wall. We contribute this module to the community and hope you can re-use it in your projects and development.

**What does this module do?**

This module aggregates content from social media sites. The module will retrieve public RSS feeds or request the API and creates a node for each item. Your website visitors will be able to see your sharings directly on your website and drive those visitors to your social media account. This way you might increase facebook fans, twitter followers etc.

We currently support facebook, twitter, vimeo, youtube, instagram, Flickr. Anyone feel free to contribute to this module so we can add up other social media channels.

There is also Social Feed which has a Drupal 7 release in the issue queue, but it creates a block for the feed items rather than a node for each.

So i guess the first two options are what you need


custom "register" button on a form - problem with redirection

Use below code to achieve the same functionality.

function mymodule_form_user_login_block_alter(&$form, $form_state, $form_id) {
  $form['actions']['register'] = array(
    '#markup' => l('Register', 'user/register'),
  );
}

Theme it using css to look like a button. Done !


How to insert Google Tag Manager code into pages with variable account value

you should use these two modules:

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

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

First one installs GTM on your page, second one enables passing many variables and taxonomies to be passed to dataLayer. It also has an alter function, if you'd like to add some extra data (since the module is written in a general way and i.e. extracting taxonomies from json arrays on the GTM side can be complicated).

User Id is part of default data added to dataLayer by data layermodule on each page, so you'll have it there.

Regarding your noscript part, you'd have to alter the module i think.


Depending on how the RSS links are rendered, I would suggest calling them over with a protocol-relative URL such as:

//domain.com/rss-feed....

This will force the information to be sent over based on the way the page was rendered.  If the page was rendered using https:// it will use https:// in place of '//'


print theme("links", array('links'=>$secondary_links), array('class' => 'links', 'id' => 'subnav'));


Attach JavaScript and CSS assets when render entity using Web Sockets

It was quite some work to adapt the rendering process. There is a lot of code, I will just summarise the solution. If you want more details, just write a comment.

The solution looks similar to my ideas/hypothesis in the question's description.

I created a custom render which collects all the libraries during rendering in an array. It results in an array:

return [
      'commands' ['An array with ajax commands for settings'],
      'content' => 'Rendered content(HTML)',
      'libraries' => 'all the needed assets grouped into libraries',
    ];

I had to to override the AjaxResponseAttachmentsProcessor and AssetResolver classes.

Also I implemented the hook_js_settings_build() to collect all the libraries on the page, as ajaxPageState does not contain all the dependencies.

At the front-end side it is not possible to attach all the assets by comparing ajaxPageState and the response from a Web Socket.


There was a typo in my plugin filename. :-/


Content Field Type Image not auto resizing

Verify that the images are being created by checking public://styles - (/sites/default/files/styles) by default.  If you see that the images are not being created then you might have your folder permissions set up incorrectly.  /admin/reports/status might hint at any permissions problems.


i think you are looking for tabledrag option.If so please refer  drupal_add_tabledrag


Custom permission always denying access?

The default function for the access callback is user_access(), which has the following signature:

function user_access($string, $account = NULL)

This is the function that will receive your access arguments.

It only takes one permission string at a time, so the second string you're passing in is being used as the $account object. This will cause problems in the user_access() function and is probably why it's returning FALSE all the time.

If you want to test two permissions you could provide your own access callback:

function mymodule_menu() {
  $items['reports'] = array(
    'title' => 'Reports',
    'page callback' => 'reports',
    'type' => MENU_CALLBACK,
    'access callback' => 'mymodule_reports_access'
  );
  return $items;
}

// Potentially accept an account object to make the function more re-usable
function mymodule_reports_access($account = NULL) {
  if (!$account) {
    global $user;
    $account = $user;
  }

  return user_access('access content', $account) && user_access('hr functionality', $account);
}


How to apply Image Styles to images that have been added to published nodes?

Start by checking your admin logs for one and second make sure that the new style directory permissions are correct. Image styles Troubleshooting -That's assuming that the images are being created and the folder(s)'s .htaccess is all good.

Also maybe force it by adding your specific style as argument using drush if MACHINE_NAME


This is a MySql error. MySQL is not getting fed the correct logon information. Can you logon to mysql using your drupal credentials - either by command line or PHPMyAdmin or some other method. If you can't logon it's a credentials problem. Otherwise it's likely a path problem.

In your settings.php file, make sure everything is correct. Double check it

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'MYDATABASENAME',
      'username' => 'MYUSERNAME',
      'password' => 'MYPASSWORD',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),

);


How to get escaped file description from node?

As stated in the comments to official documentation:

  It is worth noting that field_get_items() returns raw values the use of which can be a security risk. Passing the raw values through field_view_value() handles the sanitizing of the values.

Links added by me.


Fetch product data from commerce order on rules check-out completention

The solution I found:

First of all we need to create a Component which takes commerce-line-item as input,there we add some conditions to check if the item we are processing is of our desired type or not,this is how it configured :

Note that the way conditions are sorted is important.

Now after setting these conditions rules know that the item is definitely of type 'EditOption' so now all fields related to these type is accessible like below :

to create a content of type project I created another component which takes editor and 'EditOption' as inputs and the created my desired entity.(it is called in first component using data fetched from order)

the final step was to add an action of my first component in loop for each commerce-line-item of order.

here is the image :

Everything works fine now.


Modules installed with Composer placed in wrong directory

As per what Ivan Jeros said, if you add "composer/installers": "^1.2" to your "require" array, it will add a composer extention that maps to the directories you added:

"require": {
        "composer/installers": "^1.2",

Otherwise, it puts everything in /vender/drupal


The Drupal way is to add js on the go is drupal_add_js

drupal_add_js($data = NULL, $options = NULL)

Examples:

  drupal_add_js('misc/collapse.js');
  drupal_add_js('misc/collapse.js', 'file');
  drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', 'inline');
  drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });',
    array('type' => 'inline', 'scope' => 'footer', 'weight' => 5)
  );
  drupal_add_js('http://example.com/example.js', 'external');
  drupal_add_js(array('myModule' => array('key' => 'value')), 'setting');

There is a better way to add a library file drupal_add_library

Parameters

$module:
The name of the module that registered the library.

$name:
The name of the library to add.

$every_page:
Set to TRUE if this library is added to every page on the site. Only items
with the every_page flag set to TRUE can participate in aggregation.


Edit your view
Create Block View
Add Contextual Filter

Add Content:Nid

In settings choose : Content Id from URL

Enable your block in your node pages where you would like to display images


A way to generate line charts where each dataset comes from a view with specific arguments

'I' can answer that very last part of your question about charts. The views integration of the charts module is a solution for that. Here is an intro about it from the charts community pages:

  Anybody familiar with the views UI can use the charts module to create
  charts without coding PHP snippets, as one typically does when using
  the Charts API.

  So site building knowledge is sufficient to create charts using Views,
  you don't have to be like an experienced Drupal developer (who
  probably would rather want to use the Charts API instead).

To be complete: I'm the new co-maintainer of the charts module ... Working on transforming the latest (pretty old and stable) RC1 release of it in an official release of it.


I think it is not possible, because Drupal Commerce calculate the prices/taxes before the discount. I had the same issue a while ago.


Why is my Rules page redirection based on data comparison not working?

Your conclusion is wrong. You say that page redirection does not work, but what is really happening is that your conditions are configured wrong so the redirect action is never used.
For the rules_entity_is_of_bundle condition, you have:
      type: article
      bundle: article

But articles are node types, so the type: should be node. This condition will never be true because of the way you've configured it.
In general, you should debug your Rules one step at a time and use the rules_system_message action to display a message on the screen for debugging. First use just the event and the system message action to ensure the message is shown when you expect them. Then add conditions one at a time to see if the conditions evaluate as you expect them to. You can use the system message action to display the values of data like {{ node.field_test2.entity.tid.value }}, which will help you see whether the values are what you expect. After you have the conditions working the way you want, then add the redirect action.
You can also turn on Rules debug logging to see what Rules are being triggered, by what events they're being triggered, and see the result of each condition evaluation.


How to create a template for a Views row style?

In Advanced section in your view, there is a theme option in the last row. On clicking it you can get suggestions for possible template files in row style output sub heading. In this the last option is the most specific one.

Also on clicking the row style output heading you can get the code of default row style tpl which is getting called currently, which you can add in your tpl file and override it as per your requirement.


How to disable PHP files from being run in the sites/default/files directory?

By default, when you site is created a .htaccess files is put in your sites/default/files directory (or wherever your public files are) and your private directory (if defined).  See file_ensure_htaccess() and file_create_htaccess() for the details.

The first line of each should read

SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006

This is an Apache directive that resets how it handles the files in that directory, and all subdirectories.  Basically, it resets the handler to a non-existent function, which prevents files from being executed.  See SA-2006-006 - Drupal Core - Execution of arbitrary files in certain Apache configurations security advisory for more info.  I have double checked this on a few of my servers, and this does prevent PHP from being executed.

If this line is missing, then you need to figure out what happened and how it was removed.

If this not preventing execution by Apache, then you need to look at your server configuration.  It is also conceivable that PHP may be executed here from the CLI via some server exploits.


How to insert the title of the page as a class in page title block?

Seems title is a render array. You probably have to use title.value instead. But I'd recommend to simply preprocess that and leave the templates untouched.

You can implement hook_preprocess_hook and then use TitleResolver::getTitle and Html::cleanCssIdentifier to do what you want from inside your theme's *.theme file or from within a custom module's *.module file:

/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME/MYMODULE_preprocess_page_title(&$variables) {

  // This won't work properly with Twig debugging enabled.
  // $title = $variables['title'];

  // Here is a safer method to get the current title.
  $request = \Drupal::request();
  $route_match = \Drupal::routeMatch();
  $title = \Drupal::service('title_resolver')->getTitle($request, $route_match->getRouteObject());

  $css_title = \Drupal\Component\Utility\Html::cleanCssIdentifier($title);
  $variables['title_attributes']['class'][] = 'page-title';
  $variables['title_attributes']['class'][] = strtolower($css_title);
}

You can use nearly the exact same snippet to add that CSS class to the <body> tag:

/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME/MYMODULE_preprocess_html(&$variables) {

  $request = \Drupal::request();
  $route_match = \Drupal::routeMatch();
  $title = \Drupal::service('title_resolver')->getTitle($request, $route_match->getRouteObject());

  $css_title = \Drupal\Component\Utility\Html::cleanCssIdentifier($title);
  $variables['attributes']['class'][] = strtolower($css_title);
}


The error:

  Method call uses 2 parameters, but method signature uses 1

Your create() method is defined to only receive a single argument, $container. This must be a debugger in PHPStorm giving you this output, because what it is saying is that the code calling SomeController::create() is passing two arguments. So the second is getting lost. Your problem is likely stemming from that, and probably means one of two things:

The code calling the create() function is mistakenly passing a second value, or
Your create() function needs to be re-defined to catch the second argument, and do something with it.

ControllerBase::create only expects a single argument, $container, and since your function defines that, I'd guess the more likely culprit is the calling function passing an unnecessary argument (#1 above). However, if the passed variable is necessary for some reason, SomeController::create() can be redefined to catch an optional argument:

public function create(ContainerInteface $container, $additional_param1 = NULL) {
  if (is_null($additional_param1)) {
    throw new \Exception('$additional_param_1 is required');
  }

  // Continue as normal.

}


Add programmatically created field to content type form

Found out that it needed "type" for all the fields in the form_display.


Create link to users created content only

You can link to a view, that filters the content type Business and the current user.

This is a similar question for D7, I think both solutions provided there work in D8 the same way:

Filtering on node whose user ID is equal to the current user


DrupalSettings are not passing the values from block to js?

99 % sure it is the way your js file is set. as the above should work. for a test please do this:

(function ($, Drupal, drupalSettings) {
  'use strict';
  Drupal.behaviors.testStuff = {
    attach: function (context) {
        alert('yes i am attached');
        console.log(drupalSettings);
        if (drupalSettings.example) {
           console.log(drupalSettings.example);
        }
    }
  };
})(jQuery, Drupal, drupalSettings);

if you don't see that in the log then try this ...

$build = [];
$build['stuff'] = [
  '#theme' => 'block--exampleblock',
  '#value' => 'test',
];
$build['#attached']['drupalSettings']['example'] =  [
        'data' => $data,
        'color'=> $color,
];
$build['#attached']['library'][] = 'example/examplejs';
return $build;

remember to clear your cache too.


The problem was that I created a field in media bundles that didn't match with the one in the content type.
The guide that I followed was not so clear so in the media bundle I created a field_image and I was trying to reference it with content.field_reusable_image in content type, which apparently didn't work.


How to show token value in Webform confirmation

Use Webform tokens module

  Webform Tokens provides tokens for user form submissions for forms
  created with the module Webform 3.

Or upgrade to Webform4 which has this feature inbuilt.


Install Disable Field module and install. After installation go-to admin/structure/types/manage/YOUR_CONTENT_TYPE/fields and edit the desired field. In the bottom, you can see DISABLE FIELD SETTINGS open that and you can choose to disable option in DISABLE THIS FIELD ON ADD CONTENT FORM? and DISABLE THIS FIELD ON EDIT CONTENT FORM?. In that Select Disable for certain roles and choose administrator. After that save and that field will be disabled in ADD/EDIT based on your selection


Hi in Drupal 7 you can directly have the options in the views

if you are using drupal 6 you should use somthing like hook "hook_views_pre_build (&$view)"


How to alter a field within an unlimited field collection?

Since Drupal 7.8 you can leverage hook_field_widget_form_alter. You can alter any field widgets provided by field_collection before the form_alter of the main form.

function my_module_field_widget_form_alter(&$element, &$form_state, $context) {
  if ("field_my_field_collection" == $element['#bundle']) {
    if ("field_my_field_collection" == $element['#field_name']) {
      $element['#access'] = FALSE;
    }
  }
// dpm(array($element, $form_state, $context), "field_name: " . $element['#field_name'] );
}


Is the path_alias table queried for all URLs?

While @Clive's comment is in most cases correct, from a SEO perspective it can make sense to expose certain filters as links and make them searchable through Google. Path aliases are implemented in AliasPathProcessor. Since the core alias lookup system can't handle query parameters and you can alias without a lookup table by querying the entity data directly, you could add your own path processor. Inbound you have to change the path to the internal path and add the query parameter to the request, outbound vice versa (but use $options to remove the query parameters because this is for all outgoing links, don't use the request).


How to invoke a search api from drupal site for Ubuntu Unity lense?

Your site is running Drupal 6.26
http://en.ict.edu.rs/CHANGELOG.txt

The Unity Lense does not require OpenSearch. You essentially just need to Curl your search results page with a querystring and parse out the search result links.

Eg, send a Curl request with:
http://en.ict.edu.rs/search/node/example

You could show some answers easily that way for any drupal site. You could setup a custom View for searching your content as well if you wanted, or even install the Services module and make a small dedicated search api.

I'm actually running Ubuntu 12.04 here and installed the Lense stuff which looks neat -- but I'm too busy to code up a small example, sorry. Hopefully these thoughts will point you in the right direction.

EDIT: alot of the code is really there already when you start your Lense project. You just need to tear through the results from /search/node/KEYWORDS_HERE you get from the request in Python ...


Account creation emails not being sent but other emails are

I would create a clean Drupal site on Pantheon and configure just SendGrid.  Do all emails get sent as expected from the new site?  If so, it's likely that there is some custom code running on the problematic site calling hook_mail_alter or altering the normal mail handling in some other way.

You'll also find some great tips to help troubleshoot email issues in http://www.webomelette.com/drupal-modules-debug-emails


How can I send an email to Administrator when Users change their name?

yes in Rules you can achieve it

Step 1 : In Events Event add "After updating an existing user account"

Step 2  : Conditions Elements "Execute custom PHP code "

return [account-unchanged:name] != [account:name]

or add data comparison and add

Data to compare Selected data: account-unchanged:name

Operator : equals

Data value : account:name

Step 3: In action send mail

refer this for same kind of problem with role. but you have is name

How do I create a Rule "When role is removed, send email to the user"?


Not getting fieldset as a option while adding new fields in content type

There's no 'fieldset' field type as such.

If you want to wrap entity fields in fieldsets, install the Field Group module:

  Fieldgroup will, as the name implies, group fields together. All fieldable entities will have the possibility to add groups to wrap their fields together. Fieldgroup comes with default HTML wrappers like vertical tabs, horizontal tabs, accordions, fieldsets or div wrappers.


How to write a module that provides its own content-type using CCK?

If you goal it to create your own content type, but don't want to deal with the hassle of CRUD, you could use features. It's designed for doing stuff like this.

CCK doesn't actually handle creating new content types, that is part of the node module (Drupal core). If you want to add a node, as if it was done through the interface and don't want to use features you should use hook_node_info:

/**
 * Implementation of hook_node_info().
 */
function module_node_info() {
  $items = array(
    'activity' => array(
      'name' => t('Name'),
      'module' => 'node',
      'description' => t('Description.'),
      'has_title' => '1',
      'title_label' => t('Title'),
      'has_body' => '1',
      'body_label' => t('Body'),
      'min_word_count' => '0',
      'help' => '',
    ),
  );
  return $items;
}

Setting node to be the owner of the node type lets it handle CRUD etc.


How do I change the node view mode before rendering?

If you want to make sure that a content type is always rendered with a custom view mode, use the following hook in a module. (I assume the module machine name is mymodule.)

mymodule.module

/**
 * Implements hook_entity_view_mode_alter().
 */
function mymodule_entity_view_mode_alter(&$view_mode, $entity, $context) {
  if ($entity->getEntityTypeId() == 'node' && $entity->bundle() == 'my_content_type') {
    $view_mode = 'my_custom_view_mode';
  }
}


Display values in the order they are in the form field

Finally I've found the cause of the problem : the use of Selection list or Chosen as widgets for the field.

Using the Autocomplete widget, it works fine : the order of the values in the back-end is conserved in the front-end.


Adding zip archives to the Document File Type

If I understand correct and it is only an interface / layout issue, I suggest creating a view of that file with views and then put it in a block under the node and filter the block with content type and/or node conditions (or to put the block inside a paragraph layout piece).

If you mean you want the zip files to be in the also considered by Drupal as a Document file type so it would appear together with the PDF than what I suggest is to see how the module you use categorizes PDF files and then initiate this same code-level categorization to the PDF, for example, by adding the file extension PDF to the list of allowed extensions if there is one.


You have to assign the quicktab block to a particular region. Then you might be able to see the tabs


How to query entities/nodes that does not have the field "field_parent" with EntityFieldQuery?

You can't (natively) I'm afraid. An EntityFieldQuery doesn't have support for IS NULL or IS NOT NULL.

There are workarounds, however, essentially by adding a tag to the query and implementing a query alter hook, in which you add the required LEFT JOIN and IS NULL statement.

See EntityFieldQuery does not support isNull or isNotNull for a code example. I've used that code before with good results.


How do I make a horizontal user login block for the top user region?

There are many many ways to do this, there is even a screencast and a module to do this. I would personally do this from the theme layer using css, or if I was using Fusion as a base theme, I would do this from the block configuration (thanks Skinr!)

I'm adding some links that will help you out.

http://drupal.org/project/userloginbar

http://ericlondon.com/changing-user-login-block-horizontal-layout

http://www.youtube.com/watch?v=XMyOX6v-k3Y

http://www.victheme.com/blog/drupal-7-creating-horizontal-login-bar-without-module


Get argument from current URL in twig to generate a link with that argument

well if you are making a custom block then you are probably doing something like this ....

 $build = [];
 $build['#theme'] = 'your_template',
 return $build;

and then in you hook_theme().

 hook_theme() {
  return [
   'your_template' => [
     'render element' => 'children',
     'template' = 'your-templante-name',
    ],
  ];
 }

you don't need to pre prossess the block at all just make sure the block is not being cached aka add this to your block plugin.

see How to prevent a block from being cached?

public function getCacheMaxAge() {
  return 0;
}

then in your block function :

 $search_query = \Drupal::request()->get('search_api_fulltext');
 $build = [];
 $build['#theme'] = 'your_template',
 $build['#search_query'] =  $search_query,
 return $build;
....

 hook_theme() {
  return [
   'your_template' => [
     'render element' => 'children',
     'template' = 'your-templante-name',
     'variables' => [
       'search_query' => NULL,
     ],
    ],
  ];
 }

then in your twig template

{% if search_query %}
  do what you want here {{search_query}}
{% endif%}


Thoughts on customizing the user profile page?

I think the two key modules for this would be Views and Panels. That should get you most of the way but, depending on what you want to display, you may need some other modules.


Programatically initialising paragraph field in drupal 8

You should be able to rely on the auto-creating of new paragraphs, instead of assinging the ID, do not save the paragraph and assign it with 'entity' => $paragraph.

This should then actually save the paragraph when the node is saved.


How to override 'views-slideshow-pager-fields.tpl.php'?

Views Slideshow is a separate module.  This video from MustardseedMedia addresses theming for the module. I have not watched it yet, let us know if it addresses your needs.


queries with db_select don't respect integers

Drupal doesn't alter the arguments you give it (apart from expanding arrays), but because they're passed directly to PDOStatement::execute, in which

  All values are treated as PDO::PARAM_STR.

the quotes are inevitably added.

Assuming a recent-ish version of MySQL you can try disabling prepared statement emulation to let MySQL sort them out instead. In settings.php:

$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => 'drupaldb',
  'username' => 'username',
  'password' => 'secret',
  'host' => 'dbserver1',
  'pdo' => array(PDO::ATTR_EMULATE_PREPARES => FALSE),
);


Use a search bar (exposed filter) to search for different node fields

Views with exposed filters, and then a bit of custom js should do the job fine.

Basically loop over the fields that are there and use them to build a select so users can choose which field to search. The existing fields names relate to the query string key that we need to use.

Something like this should suffice:

(function($) {
  Drupal.behaviors.viewsSearchBar = {
    attach: function(context, settings) {

      // Build the HTML for the new field we are adding.
      var newField = '
';
      newField += '<input type="text" class="form-text" maxlength="128" size="30" value="" name="combined-search-text" id="combined-search-text">';
      newField += '<select id="combined-search-field">';

      // Loop over the existing widgets to add options to our new select.
      $('.views-exposed-widgets .views-exposed-widget').each(function(){

        var title = $(this).find('label').text().trim();
        var value = $(this).find('input').attr('name');

        if(title && value) {
          newField += '<option value="'+value+'">'+title+'</option>';
          // This this widget
          $(this).hide();
        }

      });

      newField += '</select>
';

      // Add our new field.
      $('.views-exposed-widgets').prepend(newField);

      // Create a submit function for the views search form.
      $('.view-filters form').submit(function(e){

        // Stop the form doing it's default action.
        e.preventDefault();

        // Build the new URL.
        var baseURL = window.location.protocol + '//' + window.location.host + window.location.pathname;
        var field = $('#combined-search-field').val();
        var text = $('#combined-search-text').val();

        // Off we go...
        window.location = baseURL + '?' + field + '=' + text;

      });

    }
  };

})(jQuery);

Further work that needs to be done:

Check if there is already a search argument in the query string and set the default value of the custom search field and select.


How to show only oldest and newest node in Drupal views?

How about creating a contextual filter in view, and take a look at the below image to select any of these creation dates?

Afterwards, filter your content type as in the following image:


Add more fields to content type dynamically

This is in core for the field types supported by the fields module.  When you add the field to the node type, just pick Unlimited  as the maximum number of values the user can enter for this field.  Every time the user adds a field, a new one ready to be filled in will appear.


Yes you can use the commerce_order_load_multiple() function and take advantage of the $conditions parameter, e.g.

$orders = commerce_order_load_multiple(array(), array('uid' => $user_id));


What is the scope of the drupal session cookie?

Better late than never?

Yes, if you are creating the cookie with a default path. It will use the current page path. So the cookie will be restricted to any path starting with the defined one (if it's /a/b then the cookie will be available for /a/b, a/b/c etc but not /a alone).

(I had a short period of hair-tearing once where I was accessing a site using it's IP address and unable to understand why the cookies weren't available ... they were hardwired to the domain.)


Custom rendering exposed filters in Views

Copy the views-exposed-form.tpl.php which is located at <drupalroot>/sites/all/modules/views/theme to your own theme folder. And it should be easier for you to style it. Here is a tutorial you can follow


Display last 3 articles in 3 columns layout in Homepage

Why not use views with a descending sort on create date and limit the number of displayed items to 3. For the layout you can define css for the .views-row class (ex. width: 33%), for the styling you can use Display Suite or use views fields display mode.


7 - Mapping multiple LDAP groups to single Drupal roles using Boolean operators

Until I can find (or someone else posts) a better way to do this, my interim solution is:

Set up LDAP group -> Drupal role provisioning as normal.
Use the Rules module to assign/revoke another role programmatically on events User has logged in, and Before saving a user account.

Example (referring to my question above):

LDAP Provisioning:

Finance_dept|finance
Managers|managers

Create roles manually:

financemanagers

Rules:

Finance_dept + Managers = FinanceManagers

Events: User has logged in, Before saving a user account
Elements: User has role(s): finance, managers
Actions: Add user role: financemanagers

Removed from either Finance or Managers

Events: User has logged in, Before saving a user account
Elements:

NOT User has role(s): finance
OR
NOT User has role(s): managers

Actions: Remove user role: financemanagers

Works for now, but it won't scale well beyond a handful of role combinations.


Is it possible to prevent a View from executing until the user has chosen filters?

I'm assuming that for suggesting an answer to your "Does anyone know some other way to do this?", it's OK to also suggest another "module" (instead of just another "way") ...

The Forena module might possibly be a valid alternative for you to consider. For more info about this module, refer to either of these links:

its Community Documentation.
its Demo site, which includes Reporting Samples and Documentation about the module (also included in a site where the module gets installed).

In this specific case, you could consider transforming your "complicated View" into appropriate Forena data blocks (SQL queries) and custom reports (and/or charts ...). And for those reports to be generated (and the SQL queries to be executed), you could consider using the various Forena features related to "Report Parameters". A few more details about these Report Parameters:

refer to this (extremely basic) demo sample that uses such report parameter.
refer to this relevant part of the documentation (related to report parameters).


I tackle this with Panels.

Instead of having a view as a page, I make a new Panel page.  Then I add two variants.  For authenticated users, the content has the view, normally configured as a separate panel-pane display.  For anonymous users, the variant just has the login block and sometimes a custom content pane that has a brief message.


How to expose the quantity of list items to an action?

You have to create a new variable BEFORE your loop.

And then select the type of variables in that list. For your example, perhaps a list of decimals?

Be sure to give it a good custom name for your loop:

Then, in your loop, you can add a new variable to an existing list:

Then, after your loop, you can access calculation results:

Note, that if you don't know explicitly which in your loop you want, then you will have to loop through your new calculation results and use a condition rule to return the one you need as (yet another) variable.


I suggest you first create a View of the image files with node id passed as Contextual Argument. Make it display the images in the order you want and then add this View as a field using Viewfield


How do you remove the search box on the search results page?

This is a fun one... The Search box is returned as part of the render array returned by search_view().

I suggest that you make a hook_menu_alter() which replaces the default callback for the search page with your own, which is basically a pass-thru to the core function, but that unsets the search form.  Something like this:

function MYMODULE_menu_alter(&$items) {
  $items['search']['page callback'] = 'MYMODULE_search_view';
}

function MYMODULE_search_view($module = NULL, $keys = '') {
  $build = search_view($module, $keys);
  unset($build['search_form']);
  return $build;
}

Don't forget to clear your cache to pick up the new hook and menu changes.

You may need to add additional paths to the hook_menu_alter() as needed (e.g., if you search users, then you may need to add entries for search/user and search/user/%menu_tail).


Suggested template file is not working for Custom Search's template

This is a known issue with the Custom Search module for Drupal 7. Of note from the issue:

  Copy custom_search/theme/custom_search-result.tpl.php to your theme
  location (e.g, sites/themes//templates/search-result.tpl.php), modify
  accordingly and then refresh your caches.

  Tested on the current stable - custom_search 7.x-1.11

The solution is to rename custom_search-result.tpl.php from the module to search-result.tpl.php in your theme.


Drupal multilingual monthly archive using views

Does the following similar question - How can I have a multilingual URL for a views result page depending on the language? help? It suggests the use of path translations and translations sets (part of i18n which I assume you already have installed and configured)?


How do I get an article's author email programmatically?

Since you are talking of authors, I take you are referring to users who posted a node. In that case, supposing you have a $node variable, you should use the following code.

use \Drupal\node\Entity\Node;
use \Drupal\user\UserInterface;

/** @var \Drupal\user\UserInterface $user */
$user = $node->getOwner();
$email = $user->getEmail();

If, instead, you are trying to get the email of the currently logged-in user, then you cannot use \Drupal::currentUser()->get('mail') because \Drupal::currentUser() returns an object implementing \Drupal\Core\Session\AccountProxyInterface, which doesn't have any get() method.

If you want the email associated with the account, you need to use the following code.

use \Drupal\Core\Session\AccountProxyInterface;

/** @var \Drupal\Core\Session\AccountProxyInterface $user */
$user = \Drupal::currentUser();
$email = $user->getEmail();

If then you would need a User object, you should use the following code.

use \Drupal\Core\Session\AccountProxyInterface;
use \Drupal\user\Entity\User;

/** @var \Drupal\user\Entity\User $user */
$user = User::load(\Drupal::currentUser()->id());


How to log user in to multiple drupal sites?

You are looking for Multisite Login module

Multisite Login allows a user to login to all sites in a multisite
configuration, even though the multisites do not share domain names.
NOTE: if you are using several sites on the same domain (ex.
politicker.com, nj.politicker.com, ny.politicker.com, etc.), then you
do not need this module. The multisite functionality in Drupal core
has the ability to share logins for sites like these without
additional modules.

also take a look at CAS module.


I'm pretty sure that just checking it against path* should work.

So rather than path/* or path/*/* just run it against path*.


Autofill fields on profile form based on previous fields

You will have to use JavaScript to dynamically copy information from those fields. Depending on the structure of your form, you could also use a form_alter() to assign data- attributes to fields, which will reduce the number of lines of JS and make maintaining easier.

Here's sample code that should explain the idea::

JS:

$('input[data-sync]').change(function() {
  // Including the selector in data-attribute of the field will allow you
  // to have both - IDs and classes out of the box. This means you can
  // change the values of multiple fields, after only one change.
  $($(this).attr('data-sync-target')).val($(this).val());
});

hook_form_alter():

/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'your-form-id':
      $form['some_field']['#attributes'] = array(
        'data-sync' => TRUE,
        // You would use this to target an element with ID.
        'data-sync-target' => '#target-element-id',
        // OR you can use this to target multiple elements with this class.
        'data-sync-target' => '.target-element-class',
      );
      // If necessary, you can add custom CSS classes to elements like so:
      $form['some_field']['#attributes']['class'][] = 'your-special-class';
      break;
  }
}


Implement hook_user_profile_preprocess() and add your template suggestion as last entry of $variables['theme_hook_suggestions']. Instead of using arg() as you are doing, use menu_get_object('user', 1).

hook_theme_registry_alter() is not good because:

Drupal caches what it gets from hook_theme_registry_alter()

  // _theme_registry_build()
  if ($cached = cache_get('theme_registry:build:modules')) {
    $cache = $cached->data;
  }

It is never invoked for each page request Drupal gets; so you could not for which user the user profile is.

Then, the Drupal way would probably be to check the user has a specific permission rather than a specific role.

if ($account = menu_get_object('user', 1) && user_access('your permission', $account)) {
  $variables['theme_hook_suggestions'][] = 'your template suggestion';
}


Build a form with multiple choice answers (multiple submit buttons) and validation

I recommend using one of these two modules and adjusting them according to your needs.

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

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

The Field Quiz module provides a simple field that can be used as a simple quiz or multiple choice questions. It provides a field with a textfield and an checkbox combined. If added to a content type the editor of the node can enter multiple answers in the textfields and determine which answers are correct.


Getting "Page Not Found" After Enabling the Devel Module Drupal 7

the theme developer module has not been touched in years and it is unsupported. You should not expect it to work at all and it is certainly plausible that it will have detrimental effects on your site.

Unfortunately I suspect that you are out of luck unless you want to dig into the code yourself and attempt to get the module into a working state that does not blow up your site.


How to set user search and filter preference on account registration

You need to use views global filter to achieve this functionality. What you set in profile2 field you will be get it globally in views too. In view you need to add only filter for that value.

Another way you can add relationship of user profile and add in contextual filer of logged in user value of interest in gender field.


When you create your views page you set the path to /sales/cars/model/%/color/%

Add contextual filters:

You need to create 2 Contextual Filters, both of them are: Content: Has taxonomy term id so repeat the process below twice.

On configuration of first contextual filter, you need to set:

  "WHEN THE FILTER VALUE IS NOT AVAILABLE" -> Provide default value ->
  Raw value from URL -> Path component

Also check "Use path alias" if the URL is an alias rather than a system path.

Now you need to validate it, on same configuration overlay screen under

  "WHEN THE FILTER VALUE IS AVAILABLE OR A DEFAULT IS PROVIDED"

tick "Specify validation criteria"

and select "Taxonomy Term" for Validator. Check the appropriate Vocabulary for each contextual filter, and finally set "Filter value type" to "Term name converted to term id" and check the checkbox "Transform dashes in URL to spaces in term name filter values".

Set "Action to take if filter value does not validate" to whatever your needs.


I haven't tried this yet, but https://drupal.org/project/google_analytics_sync might get you part of the way there.


Yep:

Commerce Abandoned Cart Notification

  This module allows you to notify your customers by email about their abandoned their cart.

It's in dev so be warned; I'm not aware of any other pre-existing solutions, but writing your own module for this would also be a pretty straightforward option if that module doesn't work for your needs.


How to print $item separately, with different content, in views-view-grid?

Anyone still looking for this, that's how I did it:

First I've created a simple view with a block to show just the fields that I needed on top (let's call it view-top), striped all default elements and classes to make it clean and easier to work (not really necessary to clean it). In OP's case would be the miniature for the gallery.

Then I've made my main view with the fields that I wanted on bottom (let's call it view-bottom). In OP's case would be the full sized images. In the header of this view I've added a "Global: Visualization area" and called my view-top.

This way I had two views, one embedded in the other, and with a bit of Drupal's behaviors I've made the click logic.


How to get the name of the current page view

views_get_page_view() returns a View object. The name should be stored in $views_page->name.


Drupal Commerce: Allow anonymous users to choose password

You should look into modules that handle this use case. See below for examples:

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

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

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

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


Add a default value for existing Image alt field

Add a node_preprocess function to your theme file. The logic would be to check if the current node has a value in the field for "image alt text", if not then set a default value, else return.

These are not the exact field names but this should get you started on what to look for in your code.

 function MYTHEME_preprocess_article(&$variables) {
      if (!field_image_alt_text->getValue().strlen() = 0 || null ) { set value to something } else {return;}
};


Seems like my copy of Drupal was having some problems after update.


When I run cron I get deleted nodes created again

Have you used drupal.org/project/feeds to import content into your site? In that case perhaps you have configured your feed to make a import every time cron runs? In that case I think you should set Minimum refresh period to none.

Also, here is a thread facing the same problem: Delete feed, ron cron, feed comes back


Changing library path with hook_library_info_alter

I pushed my patch for social icons module to add dynamic font awesome css here
https://www.drupal.org/project/social_icons/issues/2984954

This is helpful to you.

if (isset($libraries['font-awesome'])) {
     $library_key = key($libraries['font-awesome']['css']['theme']);
     $library_array = $libraries['font-awesome']['css']['theme'][$library_key];
     unset($libraries['font-awesome']['css']['theme'][$library_key]);
     $libraries['font-awesome']['css']['theme'][$font_awesome_url] = $library_array;
}


How to implement a booking system using Drupal Commerce for checkout?

You should look at the Easy Booking distribution, to check if there is anything in it similar to what you're looking for (specific to the way this distribution uses Rooms and Drupal Commerce). If you find something, it is just a matter of reusing what's appropriate in your own site, or just use that distribution (attention: it only has a beta release so far).

Here are some more details about this distribution (quotes from its project page):

  ... to set up a website, that will suit all your needs in managing your own hotel, inn or hostel online.

  It gives a set of options for visitors to make room reservations, contact hotel administration or just follow hotel’s newsletter to be aware of all special offers and discounts.
  Easy booking profile is powered by Drupal Rooms and Drupal Commerce - widely used and popular contributed decisions, which means active maintaining and timely technical support.

Note: for some other module suggestions that might possibly help, refer to my answer to the question "https://drupal.stackexchange.com/questions/173341/how-to-create-this-reservation-form-in-drupal/173467#173467".


How do i create an item list where the item has a mixture of links and text

A simpler method is to use the t() function:

$basic_items[] = \Drupal::l('Basic example', Url::fromRoute('flot_examples.basic_usage'));
$string = 'Setting various options and annotating a chart';
$options = [
  ':options_page' => Url::fromRoute('flot_examples.basic_options')->toString(),
  ':annotating_page' => Url::fromRoute('flot_examples.annotating')->toString(),
];
$basic_items[] = t($string, $options);

$output['basic'] = [
  '#title' => 'Basic Usage',
  '#theme' => 'item_list',
  '#items' => $basic_items
];


This is an easy one, I'm pretty sure you might have figured out yourself in a short while.

You see that set classes directive?

{%
  set classes = [
    'menu-item',
    item.is_expanded ? 'menu-item--expanded',
    item.is_collapsed ? 'menu-item--collapsed',
    item.in_active_trail ? 'menu-item--active-trail',
  ]
%}

This is where the magic happens and the classes array is built for all CSS classes to attach to your link item(s).

And this is also the place where you should add your additional CSS class that should be used in every link item, like so:

{%
  set classes = [
    'myCssClass',
    'menu-item',
    item.is_expanded ? 'menu-item--expanded',
    item.is_collapsed ? 'menu-item--collapsed',
    item.in_active_trail ? 'menu-item--active-trail',
  ]
%}

Leaving the rest of the template untouched (especially the {{ item.attributes.addClass(classes) }}) gives you the desired behavior.

Some further reading, that might be of interest for you: https://www.drupal.org/docs/8/theming-drupal-8/using-attributes-in-templates