How to make user as an exposed filter option in filter criteria of a normal view?

You may install this module Total Control module. After installing this module goto this link yourdomain.com/admin/structure/views/view/control_users/edit

This view provides the functionality you want.

To see it working you visit the page through this link yourdomain.com/admin/dashboard/users

EDIT I have export the view and pasted it below in-case you just need a reference and don't want to install that module.

$view = new view();
$view->name = 'control_users';
$view->description = 'Total Control over user accounts: Contains a panel pane and a page to control user accounts.';
$view->tag = 'total_control';
$view->base_table = 'users';
$view->human_name = '';
$view->core = 0;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Defaults */
$handler = $view->new_display('default', 'Defaults', 'default');
$handler->display->display_options['title'] = 'User Accounts';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['access']['perm'] = 'have total control';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['query_comment'] = FALSE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['exposed_form']['options']['submit_button'] = 'Filter';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '35';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['pager']['options']['id'] = '0';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'name' => 'name',
  'mail' => 'mail',
  'rid' => 'rid',
  'status' => 'status',
  'created' => 'created',
  'login' => 'login',
  'delete_node' => 'delete_node',
  'edit_node' => 'edit_node',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'name' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'mail' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'rid' => array(
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'status' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'created' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'login' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'delete_node' => array(
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'edit_node' => array(
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Field: Bulk operations: User */
$handler->display->display_options['fields']['views_bulk_operations']['id'] = 'views_bulk_operations';
$handler->display->display_options['fields']['views_bulk_operations']['table'] = 'users';
$handler->display->display_options['fields']['views_bulk_operations']['field'] = 'views_bulk_operations';
$handler->display->display_options['fields']['views_bulk_operations']['label'] = '';
$handler->display->display_options['fields']['views_bulk_operations']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['display_type'] = '0';
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['enable_select_all_pages'] = 1;
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['force_single'] = 0;
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['entity_load_capacity'] = '10';
$handler->display->display_options['fields']['views_bulk_operations']['vbo_operations'] = array(
  'action::user_block_user_action' => array(
    'selected' => 1,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::views_bulk_operations_delete_item' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::views_bulk_operations_script_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::views_bulk_operations_modify_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
    'settings' => array(
      'show_all_tokens' => 1,
      'display_values' => array(
        '_all_' => '_all_',
      ),
    ),
  ),
  'action::views_bulk_operations_user_roles_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::views_bulk_operations_argument_selector_action' => array(
    'selected' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
    'settings' => array(
      'url' => '',
    ),
  ),
  'action::system_send_email_action' => array(
    'selected' => 1,
    'postpone_processing' => 0,
    'skip_confirmation' => 1,
    'override_label' => 0,
    'label' => '',
  ),
);
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
/* Field: User: E-mail */
$handler->display->display_options['fields']['mail']['id'] = 'mail';
$handler->display->display_options['fields']['mail']['table'] = 'users';
$handler->display->display_options['fields']['mail']['field'] = 'mail';
/* Field: User: Roles */
$handler->display->display_options['fields']['rid']['id'] = 'rid';
$handler->display->display_options['fields']['rid']['table'] = 'users_roles';
$handler->display->display_options['fields']['rid']['field'] = 'rid';
/* Field: User: Created date */
$handler->display->display_options['fields']['created']['id'] = 'created';
$handler->display->display_options['fields']['created']['table'] = 'users';
$handler->display->display_options['fields']['created']['field'] = 'created';
$handler->display->display_options['fields']['created']['label'] = 'Created';
$handler->display->display_options['fields']['created']['date_format'] = 'custom';
$handler->display->display_options['fields']['created']['custom_date_format'] = 'm/d/Y';
/* Field: User: Last login */
$handler->display->display_options['fields']['login']['id'] = 'login';
$handler->display->display_options['fields']['login']['table'] = 'users';
$handler->display->display_options['fields']['login']['field'] = 'login';
$handler->display->display_options['fields']['login']['date_format'] = 'custom';
$handler->display->display_options['fields']['login']['custom_date_format'] = 'j/d g:ia';
/* Field: User: Edit link */
$handler->display->display_options['fields']['edit_node']['id'] = 'edit_node';
$handler->display->display_options['fields']['edit_node']['table'] = 'users';
$handler->display->display_options['fields']['edit_node']['field'] = 'edit_node';
$handler->display->display_options['fields']['edit_node']['label'] = 'Edit';
$handler->display->display_options['fields']['edit_node']['text'] = 'edit';
/* Sort criterion: User: Created date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'users';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: User: Name */
$handler->display->display_options['filters']['uid']['id'] = 'uid';
$handler->display->display_options['filters']['uid']['table'] = 'users';
$handler->display->display_options['filters']['uid']['field'] = 'uid';
$handler->display->display_options['filters']['uid']['operator'] = 'not in';
$handler->display->display_options['filters']['uid']['value'] = array(
  0 => 0,
);
$handler->display->display_options['filters']['uid']['expose']['label'] = 'User: Name';
$handler->display->display_options['filters']['uid']['expose']['operator'] = 'uid_op';
$handler->display->display_options['filters']['uid']['expose']['identifier'] = 'uid';
/* Filter criterion: User: Roles */
$handler->display->display_options['filters']['rid']['id'] = 'rid';
$handler->display->display_options['filters']['rid']['table'] = 'users_roles';
$handler->display->display_options['filters']['rid']['field'] = 'rid';
$handler->display->display_options['filters']['rid']['exposed'] = TRUE;
$handler->display->display_options['filters']['rid']['expose']['operator_id'] = 'rid_op';
$handler->display->display_options['filters']['rid']['expose']['label'] = 'Roles';
$handler->display->display_options['filters']['rid']['expose']['operator'] = 'rid_op';
$handler->display->display_options['filters']['rid']['expose']['identifier'] = 'rid';
/* Filter criterion: User: Name */
$handler->display->display_options['filters']['uid_1']['id'] = 'uid_1';
$handler->display->display_options['filters']['uid_1']['table'] = 'users';
$handler->display->display_options['filters']['uid_1']['field'] = 'uid';
$handler->display->display_options['filters']['uid_1']['value'] = '';
$handler->display->display_options['filters']['uid_1']['exposed'] = TRUE;
$handler->display->display_options['filters']['uid_1']['expose']['operator_id'] = 'uid_1_op';
$handler->display->display_options['filters']['uid_1']['expose']['label'] = 'Username';
$handler->display->display_options['filters']['uid_1']['expose']['operator'] = 'uid_1_op';
$handler->display->display_options['filters']['uid_1']['expose']['identifier'] = 'name';
/* Filter criterion: User: E-mail */
$handler->display->display_options['filters']['mail']['id'] = 'mail';
$handler->display->display_options['filters']['mail']['table'] = 'users';
$handler->display->display_options['filters']['mail']['field'] = 'mail';
$handler->display->display_options['filters']['mail']['operator'] = 'contains';
$handler->display->display_options['filters']['mail']['exposed'] = TRUE;
$handler->display->display_options['filters']['mail']['expose']['operator_id'] = 'mail_op';
$handler->display->display_options['filters']['mail']['expose']['label'] = 'E-mail';
$handler->display->display_options['filters']['mail']['expose']['operator'] = 'mail_op';
$handler->display->display_options['filters']['mail']['expose']['identifier'] = 'mail';

/* Display: User Admin */
$handler = $view->new_display('page', 'User Admin', 'page_1');
$handler->display->display_options['defaults']['hide_admin_links'] = FALSE;
$handler->display->display_options['path'] = 'admin/dashboard/users';
$handler->display->display_options['menu']['type'] = 'tab';
$handler->display->display_options['menu']['title'] = 'User Accounts';
$handler->display->display_options['menu']['weight'] = '-14';


Your best bet is to either

use the #autocomplete_path and tweak the behavior by overriding the JavaScript (prototyping)
Don't use the ajax framework, but create this with custom JavaScript.

The AJAX framework can do a lot of things for you, and works very great for most things, but there are some cases like this one, where it doesn't work as intended. The problem is that you will get too many ajax requests at once if you do one for every keyup event, which most likely will mess things up if you could actually do it. This is why you need an autocomplete functionality which usually caches the results for improved performance.


You can embed a different View under "No results behaviour"

e.g a View that lists all venues.


Create a related content block which sorts the nodes of related content by how many tags they share?

You can do this with Aggregation, but you have to be careful about some details.

The first thing to do is to create a block listing your desired content, with contextual filters that will restrict the results to only nodes that are tagged with the same terms.

A very popular method of doing that is through Has taxonomy term ID contextual filter set to Provide default value of Taxonomy term ID from URL (with other options appropriately set).

I haven't been able to achieve the Sorting through Aggregation that way. Perhaps someone will come along and shed some light on this, whether and how it can be done.

I have been able to do it with a different strategy, the one that is usually necessary when dealing with Entity references in general. It relies on Relationships to introduce sibling nodes, and ID as contextual filters. Here are the steps to create it:

List nodes tagged with the same Taxonomy terms

Create a View of type Content, Filter it as usual to Content types, the taxonomy field not empty etc. Show fields Title and the field containing your terms, show Multiple values in the same row although that won't matter later, format as Table simply for readability, you can change it later.
Add a Relationship (search for your field name) Taxonomy term referenced from field_yourtags.
Add another Relationship Content using field_yourtags,
it will be set by default to use the Relationship from the previous step
Add a Contextual filter ID (from Content Category) and set it to use the second Relationship (the one from the previous step, it will actually be the only choice next to "Do not use a Relationship") with other options:
When the filter value is NOT available:
Provide default value
Content ID from URL
When the filter value IS available or a default is provided
Specify validation criteria (optional)
Content
[your appropriate types]
Add another Contextual filter ID  but this time Do not use a Relationship:
When the filter value is NOT available:
Provide default value
Content ID from URL
More: Exclude

This will exclude the node you're currently viewing from the list.

If you want to check the output in Views Preview at this point enter the same node ID both times, for example to see what the block would output on node 14 enter 14/14.

Don't worry about the multiplicates, we'll turn them to the best use with Aggregation ;) They are listed the number of times that the tags match between them and the current node!

Aggregate results according to common terms count
Turn Aggregation on (Use aggregation option in the third column set to Aggregate), don't worry about the red message in Preview. All fields and filters now have Aggregation settings. You only need to change the one on your taxonomy field:
Click on Aggregation settings for the "Content: Yourtags" field and change it to Count DISTINCT. Notice how your tags are now replaced by numbers indicating how many common terms those nodes have with the current node!
Now we just have to sort the View using this data: Add a Sort criteria:
Content: Yourtags
Do not use a Relationship
Sort descending
Aggregation settings: Count DISTINCT

Now you can Place your block in a Region and check the count on nodes.

Additional perk of this approach is that it won't list anything if the current node isn't tagged with any terms, while with the "Has taxonomy term ID" method you get all results.


Creating a menu structure based on Content Types Alias

I have never seen a module that does that, but you could try Import HTML. More details from the module's project page:

Import an old existing, static HTML site structure into the Drupal CMS as structured nodes!
Allows an admin to define a source directory of an existing traditional static HTML website, and import (as much as possible) the content and structure into a drupal site.
Source files will be stripped of exisiting chrome and navigation elements before being inserted as nodes.

As alternative, I would use the https://www.drupal.org/project/menu_editor module to quickly build out the menu structure of the already imported content.


Usernames in git commit messages on Drupal.org

The usernames are the usernames for the Drupal.org accounts, not the git usernames.

The reason is simple: Everybody can provide a patch, even the users who don't have a git account. As far as I recall, everybody can have read access user to a Drupal.org git repository. You can create a patch that solves an issue; once the issue has been resolved, or the feature request implemented, the git commit will report the usernames of those who contributed with a patch.

The other reason for using the Drupal.org usernames is that not every users see somebody else's git username, and it is more practical to use what is visible in the issue where the patch is being discussed.


There's Simplytest.me, but that's really for testing existing module to see if you like them (e.g. never used Panels before, select Panels from the list and hit Launch Sandbox to give it a go).

You could set up a test site with Devel and hit devel/php.  However this isn't really any different from running a local sandbox site and doing the same thing.

Apart from that, I've not seen anything like what you're looking for.  Sorry :(


Core JavaScript is not included in all pages

Drupal 8 adds little to no javascript by default, and thankfully doesn't force jQuery on us any more :)

You need to declare your dependencies explicitly:

default:
 version: 1.x
 css:
  theme:
   css/bootstrap.css: {}
   css/style.css: {}
   css/font-awesome.min.css: {}
   css/animate.min.css: {}
 js:
    js/galip.js: {}
 dependencies:
    - core/jquery
    - core/jquery.once
    - etc...


As you mentioned, you already have textfield with 255 character length and also contains data. If you want reduce length of this field then you need to make sure that there is no data within this field having more than 100 character length. Because if this field contains any data more than 100 character length then you can't alter it in this way. My suggestion to you is first take backup of this table and empty this table. Then you would be able to change its length and then you can import this table data. If there is any data more than 100 character either it will stored in truncated way or give you any warnings for this. One thing you need to remember you need to do this offline, this question is specific to database and take care of every piece of data. There is possibility you might need to make some changes manually, so should take data base backup first.


Assign the same vocab to both content types.
Install the Tagging module
Now the fields should have auto suggest for the fields, as the user types


Use the Services-3.x node resource to create a new *unpublished* node

Try setting the 'status' field to TRUE or FALSE instead of 0 or 1.


What's the difference between 'commerce-line-item-unchanged' and 'commerce-line-item'

Commerce line items are Drupal Entities (enhanced a bit by the Entity module) and, like other entities, the "entityname-unchanged" is present in some rules just so you can see what the entity was like before it got changed.

There isn't a specific use case intended for it but there are cases where being able to see the original state of an entity would be good.  Specific to a commerce line item, maybe you'd want to reset the line item's quantity to its old value if they chose some crazy number like 10000.


Well, i found a best way to do a one page menu , using link attributes for add exceptions to the any menu item, and i used jquery one page nav than with a simple reference to the menu, works perfectly.


How do I debug with Xdebug in Visual Studio Code?

InvalidPathException is an exception related to the vlucas/phpdotenv composer package so this issue isn't related to the Lando & VS Code codebases; it's an issue with your Drupal code base.

You can confirm phpdotenv is a Drupal dependency by looking at your composer.json file and looking at the require section.

The issue is the package dependency isn't finding the /app/.env file in your Lando environment. Confirm that the .env exists in your Lando project root (the same dir as your .lando.yml file).


What is the proper URL to get flag service?

I had to implement this for DrupalGap/jDrupal:

https://github.com/dontmcyn/flag/blob/master/flag.js#L282

Essentially you make a POST to ?q=rest/flag/countall.json and send along the following data:

var data = {
  flag_name: 'my_flag_name',
  entity_id: 123
}

You may have to JSON.stringify(data) before sending it. And you are right, pass along an X-CSRF-Token header in the POST call, the value of the token can be retrieved here: ?q=services/session/token


How many products can Drupal Commerce handle?

Interesting question. The major limiting factor for any Drupal Installation is server resources. If you have unlimited budget, it's safe to say you can have unlimited everything. There are upper limits to the architecture, but it's probably a limitation of database structure, that can be avoided by using a different kind of database.

For Drupal Commerce, the biggest limiting factor in Drupal 7 is usually not number of products (one of the companies I've worked with in the past did some tests with millions of products, and it worked just fine), but it is number and frequency of orders. A really busy ecommerce site is dealing with thousands of orders per hour.

I've personally seen tuned Commerce installations that can handle that kind of traffic at peak times and not crash. It takes a very dedicated team to scale any resource like Drupal Commerce to such heights.


How to replace text about [node:url] within a Rules Action?

I would transform your existing rule into 2 separated rules like so:

Create a Rules Component that only performs a Rules Action which is to send an eMail, similar to what you already have in your current Rules Action. But replace the node:title and the node:url by corresponding parameters to execute this Rules Component.
Replace the Rules Action of the rule you already have by the execution of your newly created Rules Component, in which you pass as parameter values:

the title of the node
the appropriate string that matches your domain.com/newsroom/press-release/[path-to-content]

With that, you don't need any PHP, so no str_replace() either.


How can I add cache context to custom menu link?

As @4k4 says you don't need the derivates class in this case you need to do something like this example:

.links.menu.yml file:

client_account_links:
  class: Drupal\my_module\Plugin\Menu\UserProfile
  menu_name: account
  title: 'Edit Your Profile'
  route_name:  entity.user.edit_form

The class:

<?php

namespace Drupal\my_module\Plugin\Menu;

use Drupal\Core\Menu\MenuLinkDefault;
use Drupal\Core\Menu\StaticMenuLinkOverridesInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Session\AccountInterface;

/**
 * Represents a menu link for a user profile edition.
 */
class UserProfile extends MenuLinkDefault {

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

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

    $this->currentUser = $current_user;
  }

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

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

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

}


Is it possible to make the output of a taxonomy reference field with multiple values grammatical?

I did this in D6 using a CCK field formatter and using the Multiple Group Values.

What you want to do is inform Drupal essentially of a new radio option for "Display Type" that formats the output how you want for the collection of elements.

Again my solution is for D6, but you basically make a field formatter in D7 as well ...

# expose the formatter to ckk using a hook
function MYMODULE_field_formatter_info() {
  return array(
    'compressed_days_formatter' => array(
      'label' => t('Compressed Days'),
      'field types' => array('date', 'datestamp', 'datetime'),
      'description' => t('Displays a listing of days in a month with commas'),
      'multiple values' => CONTENT_HANDLE_MODULE,
    ),
  );
}

# define our theme function
# this turns array('2011-12-03', '2011-12-04', '2011-12-05')
# into say "december 03,04,05 2011".
# and stradles months / years OK by outputting multiple lines.
function theme_formatter_compressed_days_formatter($elements) {
  $output = array();
  foreach (element_children($elements) as $k) {
    $day = $elements[$k]['#item']['value'];
    $ts = strtotime($day);
    $Y = date('Y', $ts);
    $M = date('M', $ts);
    $d = date('d', $ts);
    $dates[$Y][$M][]=$d;
  }
  foreach ($dates as $year => $months) {
    foreach ($months as $month => $days) {
      $output []= $month.' '.implode(', ',$days).', '.$year;
    }
  }
  return implode('<br>',$output);
}

So I haven't done this in D7 (yet) ... but the approach would be the same. You'd just implode most of your elements with commas, and then the last item you tack on your 'and' as-needed.

A hacky-er way to do this is probably with an alter hook in views_pre_render() that examines each result and looks for the last comma and replaces it with an "and". That would work but its more cryptic and sloppy ... I think you really want a formatter here.


How to remove duplicate view results from multiple blocks on same page in Drupal 8

Try Views Exclude Previous, check screenshots bellow


1) Add new custom views filter handler that extends views_handler_filter_in_operator

class MY_MODULE_own_company_filter_handler extends views_handler_filter_in_operator {

  public function get_value_options() {
    $options = parent::get_value_options();
    $options['own'] = 'Own Company';
    $this->value_options = $options;

    return $this->value_options;
  }

  /**
   * Replaces "Own Company" value with real value.
   * Do query alter here or in query() function.
   */
  function pre_query() {
    parent::pre_query();

    // Check if "Own Company" was chosen.
    if (!empty($this->value['own'])) {

      // Unset "Own Company" 'own' value.
      unset($this->value['own']);

      // Get current "Own Company" value the way you like.
      $company_id = 100500; // Example value.

      // Set current "Own Company" value.
      $this->value[$company_id] = $company_id;
    }
  }

}

2) Implement hook_views_data_alter() and add custom handler to all entityreference field filters

/**
 * Implements hook_views_data_alter().
 */
function MY_MODULE_views_data_alter(&$data) {
  // Loop all field filters.
  foreach ($data as $data_key => $data_field) {
    if (strpos($data_key, 'field_data_') !== FALSE) {

      // Get field name
      $field_name = str_replace('field_data_', '', $data_key);

      // Check if field filter is entity reference
      if (isset($data_field[$field_name . '_target_id']['filter']['handler'])) {
        if ($data_field[$field_name . '_target_id']['filter']['handler'] == 'views_handler_filter_in_operator') {

          // Name of custom handler class
          $custom = 'MY_MODULE_own_company_filter_handler';
          // Add custom handler
          $data[$data_key][$field_name . '_target_id']['filter']['handler'] = $custom;

        }
      }
    }
  }
}


How do I fetch the values of an entity's field?

In Drupal 7, you would use the EntityFieldQuery class. In Drupal 8, there is an equivalent service.

$query = \Drupal::entityQuery('node')
    ->condition('status', 1)
    ->condition('changed', REQUEST_TIME, '<')
    ->condition('title', 'cat', 'CONTAINS')
    ->condition('field_tags.entity.name', 'cats');

$nids = $query->execute();

In your case, instead of field_tag.entity.name, you need body.body_value. See EntityFieldQuery has been rewritten.
If you just need to get all the node IDs, remove all the condition() lines, and then use entity_load_multiple('node', $nids) to load the full node objects.

In this way, your code is not making assumptions about the tables used to contain the node data. Plus, it can be easily extended to filter the nodes basing on some criteria (node properties, content of fields...).


You have two ways of doing this, one is to use HTML/CSS to position the language switcher block in the menu, probably a little harder to do with a variable length menu unless you right align it.

Two would be to add the language switcher to the menu, you can use something like http://www.liquidcms.ca/how-to-language-switcher-menu-item to do that.


I don't find something similar to drush field-create in Drush 9

drush field-create has not been ported to Drush 9.

You can install Drupal console and use drupal generate:plugin:field instead.


How to delete nodes without taking a lot of time?

Usually I use 2 approach from the command line. If you call a page from the browser to accomplish the task this will use more time and resources.

1. You can create your own module named drush_delete

Inside the drush_delete.drush.inc file put this code:

<?php
/**
 * @file
 * The Drush Delete drush commands.
 */

/**
* Implements hook_drush_command().
*/
function drush_delete_drush_command() {
  $items['node-delete'] = array(
    'description' => dt("Delete nodes."),
    'aliases' => array('nd'),
    'arguments' => array(
      'nids' => dt('The nids of the nodes to delete'),
    ),
    'examples' => array(
      'drush node-delete 1' => dt('Delete the node with nid = 1.'),
      'drush node-delete 1 2 3' => dt('Delete the nodes with nid = 1, 2 and 3.'),

    ),
  );
  return $items;
}

/**
 * Callback for the node-delete command
 */
function drush_drush_delete_node_delete() {
  $nids = func_get_args();
  $nids = array_filter($nids, 'is_numeric');
  $nids = array_map('intval', $nids);
  $nids = array_unique($nids);
  $nids = array_values($nids);
  $cant = count($nids);

  if ($cant > 0) {
    node_delete_multiple($nids);

    drush_print(dt("Deleted nodes:"));
    drush_print(implode(' ', $nids));
  }
  else {
    drush_set_error('DRUSH_ERROR_CODE', dt("You must enter at least one nid"));
  }
}

Install the module, run drush cc drush to clear the drush cache and use the command like this:

To delete a node use:

drush node-delete 1
drush nd 1

To delete multiple nodes use:

drush node-delete 1 2 3
drush nd 1 2 3

EDIT: I just remeber that I have a collection of drush commands in github at https://github.com/adrian-cid/drush_commands.

2. You can use the Drush Entity module

Deleting node with nid 1 and 2

drush entity-delete node 1 2

Deleting all the nodes:

drush entity-delete node

Deleting all the articles nodes:

drush entity-delete node --bundles=article


This is not directly an answer, but it is also too long for a comment :)

When I migrated something that wasn't actually paragraphs into paragraphs, I just wrote a custom process plugin that created paragraphs on the fly, then I didn't have to bother about trying to figure out some kind of mapping/made up ID's. What you're doing definitely seems like a bad idea, as 1010 could either be delta 10 from node 10 or delta 0 from node 101.

Put two classes I used for that into a gist: https://gist.github.com/Berdir/8a650a29a670fe283589f8946354086c.

It is both a bit hacky and a fairly complicated as I needed to support importing multiple translations for separate nodes in 6.x to a single node with a single paragraph with translations in 8.x.

Also created a to-do for me to write a blog post about this. ;)


Injected javascript in google DFP module drupal 7

you can take a look at these functions (_dfp_js_global_settings and _dfp_js_slot_definition) that are used to inject inline javascript in the page, I believe that javascript loads the ads remotely and inject them in their spots


How can create custom twig template for particular page

Twig Debugging
It’s great that we have the ability to override our template files,
but we are still left with the question of how we are to know which
template file needs to be overridden in any particular case. After
all, template files are nested one inside the other—which one contains
the markup that we want to change?
This brings us to the killer feature of Drupal 8 theming—Twig
debugging. Getting started is very easy. Inside of the sites/default
folder is a file named service.yml. Inside that file you will find a
setting for Twig debug. This setting will be set to false by default.
Simply change it to true as shown in the image below:

As usual, clear your cache after making this change. When we return to
our page and inspect the markup we will find debugging information
added in the form of code comments. Here’s an example of what our home
page markup will look like when inspected in DevTools:

You can see the debug info provides the path to the new template file
we have created. This information is repeated for other template files
found on the page, providing a fast and easy way of finding the file
you need to override or edit.
Important: Do not edit template files in core! Copy the file to your
theme and edit that version instead.
Also included are file name suggestions for overriding the currently
active templates. If you’ve ever had to track down the correct
template file to override in Drupal 7, then you know what a huge
improvement this is.
Author: John Hannah
Source and more great twig info: Drupal 8 Theming Fundamentals, Part 2

Note: In the 2nd pic, the x shows you the current twig template that is being used. In this example it's page--front.html.twig
To answer your Q, enable twig debug and go to your page and with your browser inspect element. The debug will suggest you all the template names you can use for that page.
PS: Don't forget to turn off twig debug before your site goes live.


I figured out the reason it wasn't working. It's a conflict with the Update Manager module. If that module is installed, Localization Update looks for the newest possible version as returned by that module, instead of looking for the installed version on the system. Because of this, it was looking for 7.24, which doesn't have any translations attached to it as of yet.


User Stats is a good basic plugin that provides this functionality within Views and Rules. Install the plugin, then add a field or filter to your views results.


Indeed it is.

Steps you will need to do:

Create a custom module
Implement hook_menu()
Define the route 'latest-projects', and make the menu callback a function
In the custom menu callback function do SQL or whatever to find the latest project (maybe use EnityFieldQuery in Drupal 7)
Use drupal_goto() to then redirect the user to the latest project node

Note in the above solution, a redirect is used to send the user to the project node, but if needed you can also simply render the node on the page as another idea.


How to override a function inside of a Trait?

For those that may run across this. I could not find a way to override (don't think it's possible). I did eventually settle on modifying the line of the file myself, running a git diff, and adding my own patch to my composer.json. In this way, I can run updates and use composer correctly. It's not a patch others will need, but how it was solved might help others.


Drupal Commerce Product Pricing Rules disapear

It sounds like for some reason the event is getting removed or changed to something other than "Calculating the price of a product." However, without seeing a screenshot of your Rules list, there's no way to tell. Look at the list and see what the event is getting set to.

If you use the product pricing rule add link from the product pricing interface, it should be altering the form to pre-select the proper event and hide the select list. Perhaps you have some other code on the site that undoes that selection or otherwise invalidates it.


How to manage video content including chapter markers and CC

Here's the solution I'm working on:

new Content Type: Video.

This content type has file fields for each file, two video type, up to 10 closed caption files, and chapter markers.

Then I add a node--video.tpl.php
Within the node template I'm then doing this:

 $mp4 = ltrim ($node->field_mp4_video[und][0][uri], 'public:/');
 $webm = ltrim ($node->field_webm_video[und][0][uri], 'public:/');
 $vtt = ltrim ($node->field_chapter_markers[und][0][uri], 'public:/');
 $encc = ltrim($node ->field_closed_captions[und][0][uri], 'public:/');
 $escc = ltrim($node ->field_closed_captions[und][1][uri], 'public:/');

ltrim trims the public:/ from the front of the string and printing that inside the video element:

<video width="100%" height="100%" style="width:100%; height=100%;" id="player2" controls="controls" >
  <source src="../sites/default/files/<?php print $mp4 ?>" type="video/mp4">
  <source src="../sites/default/files/<?php print $webm ?>" type="video/webm">
  <track kind="subtitles" src="../sites/default/files/<?php print $encc ?>"  srclang="en" />
  <track kind="subtitles" src="../sites/default/files/<?php print $escc ?>"  srclang="es" />
  <track kind="chapters" src="../sites/default/files/<?php print $vtt ?>"  />

Unsupported in this browser.

</video>

The un-solved issue is if there's more than the English and Spanish closed-captions. Certainly solvable, but probably outside of the scope of the project as currently budgeted.

Also, Drupal is throwing an error Notice: Use of undefined constant.... I'll tackle that in a separate question.


You could try an alternative Theme key module rather then using mobile switch module to check for the mobile device.
It provides flexibility for changing the theme not only based on the type of device but also can theme different parts of site based on different conditions.
You can check for a detailed video tutorial by Mustardseed to check this features.


How to theme video_embed_field per node type

Twig naming pattern for the field per content type is

field--field-name--content-type.html.twig

Read more on Twig naming convention here.

update

Media entity seems to be following custom template suggestions, that unfortunately are not documented anywhere. See function media_entity_theme_suggestions_media() here for template suggestions patterns. It does not include per content type template suggestion, but you can try overriding it in a custom module.


The problem is that you have a minimum lifetime of 1 day set. This means cache_clear_all() will not remove entries with a lifetime of less than a day. Try setting this to 1 hour, or something more acceptable for your site (eg, how long between new content or edited content, and when an anonymous user needs to see the content).


Webform Radio buttons are not getting "radio-checked" class when clicked on

After a bit more digging, it appears it's my memory that has failed me. This functionality is provided by Javascript.
So I'm placing my solution here in case anyone would like to make their select options look like buttons.

You have my CSS above.  Next you need to add a javascript folder & file in your sites> all >themes > [theme_name] directory.

I've placed a new folder and file in the above path :  js > webform_tweaks.js

Inside the webform_tweaks.js file, place this code:

(function($) {
  // DOM ready
  $(function(){
    // add a radio-checked additional CSS class to the parent label
    $(".webform-client-form .form-radios input").click(function(){
      $(this.parentNode.parentNode.parentNode).find('.form-item .control-label').removeClass('radio-checked');
      $(this.parentNode).addClass('radio-checked');
    });
  });
})(jQuery);

You need to reference this javascript file in your [theme_name].info file (found in the root of your sites> all >themes > [theme_name] directory.)

Open that file and add:

scripts[] = js/webform_tweaks.js

You will also need to flush your CSS & Javascript caches before you see the change.

Hopefully, now you should be able to click on your "pretend" button and apply a style to it using this new "radio-checked" class and make the button looked clicked by adding a background colour or something to it.


new domain url for multi sites linked to sub domain drupal install

So finally figured this all out.

If like me you are weird and want to use a Sub-domain for your main drupal install and then create multi-sites from that you can just add your virtual hosts to the custom conf file or wherever you keep that.

I found that to do away with .htaccess in favour of the /etc/httpd/conf.d/custom.conf file as well as httpd.conf on linux vps.

BUT if you want to add a new domain directing to same IP it will obviously keep searching for doc root,so even if you add the Drupal folder direction in virtual host it will just go there and not install at your actual URL.

So you need to create a symlink in this case and then add that directive to your virtual host. so it would be something like /var/www/html/drupal/nameofmysite.com  which would be a symlink to the actual folder in sites folder of subdomain.


Drupal has a wealth of community documentation related to this:

Patch guide
Applying patches
Applying patches manually

However, for your first problem. Drush is pretty much version independant. If you have the latest version of drush it will work with drupal 7, 8 and most likely 6.

Finally, the issue you linked also mention that it's been fixed in the latest version of drush as well.


I think that you might need to add some jQuery to your theme.

Here is a way to do it.

jQuery(document).ready(function(){
    jQuery("#id-of-my-custom-block h3:first").trigger('click');
});


combining two taxonomy fields into one exposed filter dropdown

You can follow this using below step:

Go to Administration -> Structure -> Views
Edit your existing view or create new new.
Add Filter for taxonomy for 'home' and 'away'
Click on "Rearrange" filter icon in Filter section
Click on "Create new filter group" and move filter "Home taxonomy" and "Away taxonomy" in new filter group.
Select Operator as "Or" in new filter group and save the form.


I'd like to regard content types as a template to create entity objects (much like classes in object oriented programming) rather then as a means to create pages.

I do not see a reason for each project to have its own taxonomy term. If there is a 1:1 mapping between terms and projects, you are effectively creating redundancy. This might be done at a later stage to facilitate using specific modules that rely on the taxonomy module.

Nodes of the content type "media" can be linked to nodes of the "Project" content type by adding a "node reference" field to the "Media" content type. In Drupal 6, the "Node reference" module is part of the Content Construction Kit; in Drupal 7, it has been moved into the References module.

You can use the Prepopulate module to create URLs that show the "Media" creation form with the "node reference" field for "Project" already populated. This URL can be linked to using hook_link() (in Drupal 6) or hook_node_view() (in Drupal 7) to create media from the project page.

The list of associated media can be shown on the project page using the Viewfield module. Alternatively, the project page can be overridden using the Panels module. A second alternative is to add the output of the view to the project node using hook_nodeapi(&$node, $op='view') (in Drupal 6) or hook_node_view() (in Drupal 7).


How to create a new table in drupal without uninstall/installing the custom module

The proper way to do this is to simply implement hook_update_N() and manually add the table that you've added to hook_schema():

/**
 * Add the foo table.
 */
function MYMODULE_update_7100() {
  $table_name = 'table_name';
  $schema = drupal_get_schema_unprocessed('MYMODULE', $table_name);
  db_create_table($table_name, $schema);

  return $table_name . ' table created.';
}

That goes in your module's .install file along with the schema hook, and you'll need to run drush updb (or run through the UI at /update.php) for the changes to take effect.


When you need to find the child items present in a form, you need to use element_children(), as Drupal functions like filter_process_format() do.

The reason is simple: In a Drupal form array, as well as in a render array, not all the keys are child items; those keys with a name that starts with # are properties. Consider, for example, the form returned from forum_form_forum(); if you loop through it with the following code, you would add values where you should not.

foreach($form as $key => $value) {
  $form[$key]['#attributes']['class'][] = 'vr-paragraphs';
}

In fact, $form['#submit'] is not a child item, nor is $form['#theme']. In particular, when your code will be executed for the last key, you would get a PHP error. $form['#theme'] is a string, and $form['#theme']['#attributes'] would select a character of that string, supposing that '#attributes' would be evaluated as the integer 0; even in that case, $form['#theme']['#attributes']['class'][] would not be a valid PHP construct.

The correct code would be the following one.

foreach(element_children($form) as $key) {
  $form[$key]['#attributes']['class'][] = 'vr-paragraphs';
}


Get URLs of taxonomies terms in Link field

Nodes and taxonomies both use fields but they're stored slightly differently.  You will need to recreate your field for the taxonomy you wish to apply it to, it won't show up in Use existing field.


reCaptcha does not display on modal window(colorbox) webform

Fixed the issue, there was a patch on issue's forum on the Module page.
71 @ https://www.drupal.org/node/2493183


Is it possible to patch a non-dev version of a module?

There would be a few differences from the process described on that documentation page.

In Step 1, when creating the topic branch, specify the commit from
which to create the branch. You can do this by appending a commit
ID, a tag name, or an existing branch name to your git branch
command. Tag name should work, because Drupal project releases are
tagged with the project version number. So if you wanted to patch
off of the 7.x-1.5 version of a module, instead of this:

  git branch [issue-number]-[short-description]

You would do this:

  git branch [issue-number]-[short-description] 7.x-1.5

You would skip Step 4 and 5, since those steps are for making apply
to the most recent dev version.
In Step 6, when using the git diff command to create your patch
file, you now want to diff against the commit that represents the
unmodified version. Again, we can use the tag/version name.

  git diff 7.x-1.5 > [project_name]-[short-description]-[issue-number]-[comment-number].patch


How to use Drupal.ajax() to update #content div on  click?

dont know it can be achievable using drupal.ajax , but created a module for drupal 6 using jquery load and Drupal.attachBehaviors with which you can load any page to any div. Now ported to 7 also :)  this is the module (currently under review process)


It would be helpful to know what version of drupal you are using.

Modifying html.tpl.php to add Javascript like this is really a bad choice as it is a very brittle way of coding something.

Jquery in Drupal 7 is loaded using the noConflict mechanism. This avoids javascript namespace collisions:

  Many JavaScript libraries use $ as a function or variable name, just
  as jQuery does. In jQuery's case, $ is just an alias for jQuery, so
  all functionality is available without using $. If we need to use
  another JavaScript library alongside jQuery, we can return control of
  $ back to the other library with a call to $.noConflict():

If you wanted to use code like you've written you would write:

You're better off adding a scripts[] entry into your theme_name.info file and placing such code in its own javascript file in your theme directory. Drupal will load it into the HTML  for you and aggregate your javascript files for you if you have aggregation turned on.

# In YOURTHEME.info
scripts[]= js/example.js

/* Example /sites/all/themes/YOURTHEME/js/example.js */
jQuery(document).ready(function($) {
  $('nav ul.primary-menu').append('

');
});


How do I let users cancel their account with JWT / JSON:API?

This method uses the JSON:API Resources module.
It assumes:

Upon cancellation, blocking the user is OK.  (Admins will manually delete the accounts completely later.)
Logged-in users will simply make a GET request to www.example.com/jsonapi/MYMODULE/cancelaccount to cancel their accounts (the app will provide an "Are you sure?" dialog and so forth).

There is probably a better way to do this but I am sharing my solution here because a Google search didn't reveal anything on this topic.
What to do
First, create a custom module.
Then, in MYMODULE.routing.yml:
MYMODULE.user_cancel:
  path: '/%jsonapi%/MYMODULE/cancelaccount'
  defaults:
    _jsonapi_resource: Drupal\MYMODULE\Resource\MYMODULEUserCancel
  requirements:
    # Give all authenticated users permission.
    _permission: 'view own commerce_order'
  options:
    no_cache: 'TRUE

Next, in MYMODULE/src/Resource/MYMODULEUserCancel.php:
<?php

namespace Drupal\MYMODULE\Resource;

use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Logger\LoggerChannelFactory;
use Drupal\Core\Session\AccountInterface;
use Drupal\jsonapi\JsonApiResource\LinkCollection;
use Drupal\jsonapi\JsonApiResource\ResourceObject;
use Drupal\jsonapi\JsonApiResource\ResourceObjectData;
use Drupal\jsonapi\ResourceResponse;
use Drupal\jsonapi\ResourceType\ResourceType;
use Drupal\jsonapi\ResourceType\ResourceTypeAttribute;
use Drupal\jsonapi_resources\Resource\EntityQueryResourceBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Route;

/**
 * Processes a request for a collection containing a user's article nodes.
 *
 * @internal
 */
class MYMODULEUserCancel extends EntityQueryResourceBase implements ContainerInjectionInterface {

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

  /**
   * Logger factory.
   *
   * @var \Drupal\Core\Logger\LoggerChannelFactory
   */
  protected $loggerFactory;

  /**
   * Constructs a new EntityResourceBase object.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *   The current user.
   * @param \Drupal\Core\Logger\LoggerChannelFactory $logger_factory
   *   The Watchdog logger.
   */
  public function __construct(AccountInterface $account, LoggerChannelFactory $logger_factory) {
    $this->currentUser = $account;
    $this->loggerFactory = $logger_factory->get('MYMODULE');
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('current_user'),
      $container->get('logger.factory'),
    );
  }

  /**
   * Process the resource request.
   *
   * Code example:
   * https://git.drupalcode.org/project/jsonapi_resources/tree/9.x-1.x/tests/modules/jsonapi_resources_test/src/Resource.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The request.
   * @param \Drupal\jsonapi\ResourceType\ResourceType[] $resource_types
   *   The route resource types.
   *
   * @return \Drupal\jsonapi\ResourceResponse
   *   The response.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  public function process(Request $request, array $resource_types): ResourceResponse {
    $uid = $this->currentUser->id();
    // Make sure that we do not try to cancel user 1 or anonymous.
    if ($uid !== 1 && $uid !== 0) {
      $user_storage = $this->entityTypeManager->getStorage('user');
      $current_user = $user_storage->load($uid);
      // See: https://drupal.stackexchange.com/a/204422.
      // Send the user the "account blocked" confirmation email.
      _user_mail_notify('status_blocked', $current_user);
      $current_user->set('status', FALSE);
      $current_user->save();
      $this->loggerFactory->notice("User account for UID @uid cancelled by JSON:API.", [
        '@uid' => $current_user->id(),
      ]);
    }

    // Some data to return with JSON:API.
    $custom_field_data = [
      'cancelled' => TRUE,
    ];

    $links = new LinkCollection([]);
    $resource_type = reset($resource_types);
    // To disable caching, set metadata.
    $cacheability = new CacheableMetadata();
    $cacheability->setCacheMaxAge(1);
    $primary_data = new ResourceObject(
      $cacheability,
      $resource_type,
      $current_user->uuid(),
      NULL,
      $custom_field_data,
      $links
    );
    $top_level_data = new ResourceObjectData([$primary_data], 2);
    $response = $this->createJsonapiResponse($top_level_data, $request, 201, []);
    $response->addCacheableDependency($cacheability);

    return $response;
  }

  /**
   * {@inheritdoc}
   */
  public function getRouteResourceTypes(Route $route, string $route_name): array {
    $fields = [
      'drupalUid' => new ResourceTypeAttribute('drupalUid'),
      'status' => new ResourceTypeAttribute('status'),
    ];
    $resource_type = new ResourceType('current_user', 'current_user', NULL, FALSE, TRUE, TRUE, FALSE, $fields);
    // @todo Add role entities as a relatable resource type.
    $resource_type->setRelatableResourceTypes([]);
    return [$resource_type];
  }

}


Drupal 7 Multiple Display Types Different Options?

With the Panels module, you can build pages using views blocks.
When you select a block you are looking for to include, you can alter on the fly the paging mecanism.
So for the first one : only 1 row, and for the second one : all rows ...

Alternatively setting the paging parameter for a specific block is done into a popin in the Views backoffice. On left top corner of this popin you have a select box which allow you to select "This block (override)". Doing this, will setup different parameters for only this block. All parameters in views can be setup like this : global or override.


Language Block customization: I need to display either English link or the other language link (not both)

Usually the current language link gets an "active" class. You can use CSS to hide all other links and display only the active link.

This can also be done by overriding theme template files or functions.


Add line item quantity in block-commerce-cart-cart "title"

Here's a quick way using hook_block_view_alter():

function MYMODULE_block_view_alter(&$data, $block) {
  if ($block->module == 'commerce_cart' && $block->delta == 'cart') {
    global $user;
    if ($order = commerce_cart_order_load($user->uid)) {
      // Count the number of product line items on the order.
      $wrapper = entity_metadata_wrapper('commerce_order', $order);
      $quantity = commerce_line_items_quantity($wrapper->commerce_line_items, commerce_product_line_item_types());

      // If there are more than 0 product line items on the order...
      if ($quantity > 0) {
        // Use the dynamic menu item title.
        $data['subject'] = format_plural($quantity, 'Shopping cart (1 item)', 'Shopping cart (@count items)');
      }
    }

  }
}

The above borrows code from commerce_cart_menu_item_title() to get the cart quantity, so if that's the string you want to output you can just call that function directly and not bother with re-implementing the code, in which case it would be as simple as:

function MYMODULE_block_view_alter(&$data, $block) {
  if ($block->module == 'commerce_cart' && $block->delta == 'cart') {
    $data['subject'] = commerce_cart_menu_item_title();
  }
}

The default return from commerce_cart_menu_item_title() will be at least 'Shopping Cart' (if the cart is empty) so this method should be pretty bulletproof.

Make sure you set the title of the block as an empty string on the block admin page (so the altered subject is used instead of a custom title) and that should work fine, e.g.:


How to use tags for filtering images to be displayed using views?

I can almost guarantee that this question has been asked before, but still ...

If you did a standard Drupal 7 install, then you should already have a Tags taxonomy. Add that taxonomy to your content type.

In the view, you could do a couple of things.

Create more than one variation of the view. In each variation, filter the view to only contain the tag that you want.

OR

Use a Contextual Filter to grab the specific term from the URL. That way, you will have as many different views as taxonomy terms. This is more complicated, but it will help you learn a lot, and it is almost always the better way to do this sort of thing.


There is a check box on field edit page of user account which enable "Display on user registration form.". This one might work for you.


Drupal 7, Default value php snippet missing?

This functionality is not part of the Field UI in Drupal 7.  You'll need to install the CCK module.


What to choose Content Type or Drupal Commerce or Ubercart

Just go (start with) what you call "Plain content types".

For the "rating" requirements, have a look at my answer to "What are recommended modules or processes which support rating based comments or reviews?".

Should you ever want to expand that to a (rather basic) e-shop and/or add a shopping cart, you can always use the modules as I suggested in my answer to "How to create a simple shopping cart without Drupal Commerce or Ubercart?".

Next question?


I think you can accomplish this with the field permissions module. You can then specify that users without permission cannot view the field.

Secondly, create a new user role for the people who can see the field. When a user makes a request to see the field, you can set the field permission to view the field by assigning the new role to that user.


Errors when trying to send e-mail when using Ubercart

So after much searching I came across this post:

http://shutterfreak.net/blogs/olivier-biot/2010-06-24/configuring-smtp-server-sending-mail-drupal

Apparently issues with the default SMTP are quite common. This post explains how to install and configure "SMTP Authentication Support module" and PHPmailer to basically override the default.

Worked great for me.


Is it possible to add or somehow relate a checkfiled to taxonomies?

To change the tag selection for a taxonomy field from autocomplete to check boxes go to the content type or product type and change the widget in the tab Manage form display:


How to create a rule for changing a user field to a random string?

There is a (sandbox) module for it, which is the Rules Random module. Here is a quote about it (from the linked page):

  A simple rule action to generate either a random string or integer. Can define the length of the random result. For random strings, can also choose to include numbers and lowercase letters.

Either you just use that module, or you look at its source code to understand what it takes to include this logic in your own (custom) module.

With that, all that's needed is to create a custom rule like so:

Rules Event: use whatever event that fits your requirements (eg: After saving a new account).
Rules Condition: "Entity has field", related to your some_var field. That will make this field available for subsequent processing in Rules Conditions and/or - Actions.
Rules Action: Use the action provided by this module, to set a value for your some_var field.


The Views PHP module would work for this.


Services REST API and special characters

It looks as though your PHP install might be configured with the deprecated Magic Quotes

  When on, all ' (single-quote), " (double quote), \ (backslash) and
  NULL characters are escaped with a backslash automatically.

More info: Disabling Magic Quotes


Adding an existing node as a translation

You can do this in code by reading the field values from the three translated nodes and add them as translation to the english node:

$node_en->addTranslation($langcode1, $node1->toArray());
$node_en->addTranslation($langcode2, $node2->toArray());
$node_en->addTranslation($langcode3, $node3->toArray());
$node_en->save();

This is for demonstration only, you can loop through the languages and get the langcode from the node.

The problem is that at the moment the translated nodes and the english node have no connection in the database. If you have some data in the nodes that do match, you can do a entity query and loop through the results.


Where do I add HTML content into a block?

I think you first want to define the fields of a block content type. You'll find this at this url:

www.mysite.com/admin/structure/block/block-content/types

In the admin UI this is not so easy to find like the node content type at the top  level of the admin structure. The block content types are two or three levels deeper in the block layout. To access above link make sure you have the Custom Block module enabled.


Drupal Commerce product in-cart status info in Views

I am not aware of any modules, that will provide the functionality that you described out of the box, but the snippets below will probably get you moving in the right direction.

You'd write a function that gets all product IDs that are in the cart.

/**
 * Return the product_id values for all products in the cart
 *
 * @return
 *  An array of product ids
 */
function CUSTOMMODULE_get_products_in_cart() {
  $cart_product_ids = &drupal_static(__FUNCTION__);

  if (!isset($cart_product_ids)) {
    global $user;
    $cart_product_ids = array();
    $order = commerce_cart_order_load($user->uid);
    if ($order) {
      $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
      foreach ($order_wrapper->commerce_line_items as $delta => $line_item_wrapper) {
                if ($line_item_wrapper->type->value() == 'product') {
                    $product_wrapper = $line_item_wrapper->commerce_product;
                    $cart_product_ids[] = $product_wrapper->product_id->value();
                }
      }
    }
        $unique_cart_product_ids = array_unique($cart_product_ids);
  }

  return $cart_product_ids;
}

For adding a class to the views row according to the quantity in the cart you'd implement hook_views_pre_render() and implement your logic there

/**
 * Implements hook_views_pre_render().
 */
function CUSTOMMODULE_views_pre_render(&$view) {
  if ($view->name == 'your_view_name') {
        // get product_ids in cart
        $cart_product_ids = CUSTOMMODULE_get_products_in_cart();
        if (in_array($product->product_id, $cart_product_ids)) {
            // check how many times product_id is in the present in the array
            // do other stuff - apply class, etc.
        }
  }
}

Also, you'd probably want to change the "Add to Cart" button text to something custom if the product is already in the cart

function CUSTOMMODULE_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state) {
  $cart_product_ids = CUSTOMMODULE_get_products_in_cart();
    if (in_array($product->product_id, $unique_cart_product_ids)) {
        // Product is already in cart
        // Change "Add to Cart" button text
        $form['submit']['#value'] = t('Add one more'); // your custom text and maybe a quantity of that product that is already in cart...
    }
}

I think using hook_views_pre_render() is the right way to go about this, but if there is more efficient or easier way I'd like for others to pitch in with ideas.

Hope this helps.


How to use Rules to flag a node on behalf of ALL users who had previously flagged it with a different flag?

You need to flag on behalf of the user that the loop is operating with each iteration. Either that or add a numerical variable that you increment each loop and fetch that index from the list of users for the behalf of which to flag


What does the message "hook_flag_access: ignore" mean, and how do I turn it off?

Sounds like you need to disable the flagaccesstest module.

The problem is, in flagaccesstest.info the module declares

hidden = TRUE

So, it doesn't show up in Drupal module admin.

You could probably still disable it with Drush

drush dis flagaccesstest

or even (last resort) SQL:

UPDATE system SET status = 0 WHERE name = 'flagaccesstest';

Alternatively, in flagaccesstest you could comment out

;hidden = TRUE

and then disable the module from Drupal module admin UI.


menu_get_active_trail returns page not found

First, you have to make sure that the active menu is actually set. In Drupal 6, we did this like this: http://echodittolabs.org/blog/2010/04/drupal-fails-set-active-menu-trail-causing-context-fail.

Next, clear the cache, and then refresh the page. Yes, dpm() has a lag or something. If you see the right data, great.

My data was actually being cached as page not found, when actually it had set the correct data. Don't know why.

So, your debug info may show "Page not found" when, what is being rendered would be correct. The way you see if this is the case is by clearing the cache and refreshing.

This is for Drupal 6, but the principles likely hold for Drupal 7. Unfortunately, I doubt anybody rewrote the crufty old menu system. Too much AJAX and glitz.


How can i pass JavaScript variables back to PHP Controller in Drupal 8

You're right, you'll need to create a php controller for this task.

This involves a number of steps

In your custom module you'll need to add your controller in /yourmodules/src/Plugin/rest/resource

In this example I created one called HelloRest.php

<?php

namespace Drupal\my_module\Plugin\rest\resource;

use Drupal\Driver\Exception\Exception;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
/**
 * Provides a resource for accepting rest calls
 *
 * @RestResource(
 *   id = "hello_rest",
 *   label = @Translation("Hello Rest Handler"),
 *   uri_paths = {
 *     "canonical" = "/hello/{name}",
 *     "https://www.drupal.org/link-relations/create" = "/hello"
 *   }
 * )
 */

class HelloRest extends ResourceBase {
    /**
     * Responds to GET requests.
     *
     * Returns a watchdog log entry for the specified ID.
     *
     * @param int $id
     *   The ID of the watchdog log entry.
     *
     * @return \Drupal\rest\ResourceResponse
     *   The response.
     */

    public function get($name = '') {
        $response = ['message' => 'Hello '.$name];
        return new ResourceResponse($response);
    }
}

Then I enabled the route using the REST UI module here https://www.drupal.org/project/restui to do so. There is probably another way to enable the route but I'm not sure how. Also you want to make sure every role you need has permissions to access the rest call. In my case I wanted everyone that visited the site to have access so I had to make sure that anonymous users had access to that route.

Now that you have that created all you have to do is perform an ajax call to it to get your response back.

jQuery.ajax({url: location.protocol + "//" + location.host + "/hello/"+name+ '?_format=json", success: function(result){
        console.log(result.message);
}}


The solution in following post worked for me
http://www.derreklemar.net/tutorial/drupal-autocomplete-overriding-default-select-event-behavior


You may be experiencing a Krumo side effect:

https://drupal.org/node/1855468

The problem is that PHP handles references to array elements in a risky way, see this article: PHP: References To Array Elements Are Risky

I haven't read the post deeply, and can't assure you have this problem, but you may try the workaround to see if it works: use Krumo NG.

Another way is to use dd to dump your traces to a file, see functions documentation: https://api.drupal.org/api/devel/devel.module/function/dd/7


Change field input type on node edit form

Try this in a custom module...

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MODULE_NAME_form_YOUR_FORM_ID_alter(&$form, &$form_state) {

  // Replace the next 5 lines with your logic to set the array of values
  $options = array(
    1 => 'Red',
    2 => 'Blue',
    3 => 'Green',
  );

  $form['FORM_ELEMENT_ID']['#type'] = 'select';
  $form['FORM_ELEMENT_ID']['#options'] = $options;
}

Replace MODULE_NAME, YOUR_FORM_ID and FORM_ELEMENT_ID with your module name, form id and form element key respectively.


How can I findout where a custom variable is being created?

$styles is set in the $variables array during template_process_html. It is a result of calling drupal_get_css, and you can add to, remove, or change the order of this array by implementing drupal_add_css, adding a css file to your theme info file, or using hook_css_alter. The reason you do not see it in your theme's template.php is because it is a higher level function that Drupal does, the page is assembled using a majority of the application, core and contrib modules informing or responding to requests.

https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_get_css/7.x

As you can see, drupal_get_css allows for altering, which is where you would implement hook_css_alter to adjust anything in the array of CSS files before they are added to the page.

See: hook_css_alter

The same applies for the $scripts variable. You can add javascript with drupal_add_js, library hooks, or by adding it to your theme info file.

For example, if you want to change every JS file in drupal to load in the footer, instead of the head, you can do this with hook_js_alter:

/**
 * Implements hook_js_alter().
 * @param $items
 */
function mytheme_js_alter(&$items) {
  foreach ($items as $key => $script) {
    $items[$key]['scope'] = 'footer';
  }
}

Lets say on certain node types, you also want to remove scripts from loading to the page because they are not necessary for the page to function:

/**
 * Implements hook_js_alter().
 * @param $items
 */
function mytheme_js_alter(&$items) {
  foreach ($items as $key => $script) {
    $items[$key]['scope'] = 'footer';
  }

  if ($node = menu_get_object('node')) {
    if ($node->type == 'campaign') {
      // unset all the JS we won't need to reduce page weight
      unset($items['sites/all/themes/mytheme/js/jquery.waypoints.min.js']);
      unset($items['sites/all/themes/mytheme/js/jquery.fitvids.js']);
      unset($items['sites/all/themes/mytheme/js/isotope.min.js']);
      unset($items['sites/all/themes/mytheme/js/imagesloaded.min.js']);
      unset($items['sites/all/libraries/ckeditor/plugins/codesnippet/lib/highlight/highlight.pack.js']);
      unset($items['sites/all/modules/contrib/wysiwyg_codesnippet/wysiwyg_codesnippet.js']);
      unset($items['sites/all/modules/contrib/addthis/addthis.js']);
      unset($items['http://s7.addthis.com/js/300/addthis_widget.js']);
    }

    // we only need addthis to load on an article
    if ($node->type != 'article') {
      unset($items['sites/all/modules/contrib/addthis/addthis.js']);
      unset($items['http://s7.addthis.com/js/300/addthis_widget.js']);
    }
  }
}

See hook_js_alter


Then dont exclude special price from display and customize that field. There's an option @ No results behavior, where you need to check Hide if empty.

THEN, all you need to do is to style the two fields where they're both present.

That's the simplest way. There is another way, where you exclude both from display and add another field at the end "Global text area", where you can play with the tokens and rewrites.


My guess is that a label can't be an anchor (because of XSS).
You may want to use theme_preprocess_field or theme_preprocess_node to wrap the label with an anchor.


I slightly changed the way I handled this after following the excellent tutorial
Creating a Simple AJAX Interface with Views

All is up and working now.


A few things you can try:

Make sure that when you are editing or creating new content that the "Text Format" selection box at the bottom of the WYSIWYG editor shows the same profile that you edited. On my site an advanced user can be allowed to choose from Filtered or Full HTML, and by default the Filtered HTML profile is loaded (thus they wouldn't immediately see changes to the "Full HTML" profile).
You can try clearing your cache if you haven't already.
I understood your question as not seeing the new options in the Toolbar, but if your issue is that you are not seeing something like bolded or larger font upon saving, it may be that you need to create an exception to a specific HTML tag in your "Advanced Content Filter" and/or the "Cleanup and Output" settings under your CKEditor profile options (/admin/config/content/ckeditor/ in Drupal 7).


How to get different languages of the site to appear in that language's Google search results

The i18n module, which can be used for various localization tasks, includes a redirect submodule specifically for SEO.  If you read the i18n documentation and set up your site carefully, you can create a site in which the English versions show up in English Google search, and the German version in German Google search.

One way to speed this process up is to use the XML Sitemap module and create a sitemap for each language; this will help Google learn which pages of your site belong to which language (although Google certainly doesn't need this, and can determine it automatically; it will just take longer to index your site).


You should test this module on the live site, but not on the localhost. If you are testing on localhost, Google Docs Viewer will not be able to access in the PDF document and can't show it, but you can download it from local server.


VBO doesn't search, it only gives you the interface to select items in the Views results and perform actions on them.

To construct the search you want you can use ordinary Views with the Combine fields filter filter, here's one video tutorial: Search across Fields in Views using Combine Fields Filter in Drupal 8, or use Search API for something more advanced.

Once you have the search working you can add the VBO field if you need to do some actions on the found items.


I've used Feeds JSONPath Parser module to parse a JSON feed and insert the objects as a specific content type (e.g. blog posts).

It works well but I'm unsure about your search results, you might just have to set the template to link to each of the content nodes by getting the node based on a specific field that you know will be unique for all of your nodes? e.g. title?

If you don't want to actually store the parsed data as content, and just want to display them as a page, then you'll need to use the hook_menu() function. I've linked to API 6 as you noted you were using D6.


Is there any performance issues in using Omega theme with Context, Delta and Panels modules?

it depends on your site and server configuration. if you get alot of anonymous traffic that doesnt require users to login, you should be fine as the cache would handle alot of that load. Also be sure to turn on js / css aggregation. I've built many sites with those modules combined and they run fine. But if your all about performance, you can just do everything by hand and write your own templates/css and not use the bloated ones they have, but you'll be spending alot of time. in that effect you'll have total control over what gets outputted to the user.


Drush and web front end reporting strange updates?

This was reported over at drupal.org - https://www.drupal.org/node/2729789

It is now fixed.


How to reduce options for units of measurement to just miles and km for proximity search

Another approach is simply using CSS.

The select list is built like this:

<select>
  <option value="6371">Kilometres</option>
  <option value="6371000">Metres</option>
  <option value="3959">Miles</option>
  <option value="6975175">Yards</option>
  <option value="20925525">Feet</option>
  <option value="3444">Nautical Miles</option>
</select>

You could hide the undesired values with the following style (in this case only "kilometres" and "miles" remain):

option[value="6371000"],
option[value="6975175"],
option[value="20925525"],
option[value="3444"]{
  display: none;
}

If you're only using one value, it may look a bit silly to have a select box of it. You could disguise it as regular text though. Make sure the font is identical to the rest, remove the border, set a width to the container of the select list and hide everything seeping out of it, whilst making the select list a tad longer (thus the dropdown arrow gets hidden by the overflow):

.form-item-field-geofield-distance-unit{
    width: 90px;
    overflow: hidden;
}

select{
    width: 120px;
    border: 0;
    cursor: text;
}

Alternatively (Bootstrap 3):

.form-item-field-geofield-distance-unit select{
    border: 0 !important;
    box-shadow: none;
    cursor: text;
    -moz-appearance: none;
    -webkit-appearance: none;
    appearance: none;
}

Adjust the margins or paddings if necessary…


Passing Settings from Drupal Module to Javascript: Uncaught TypeError: Cannot read property

For future readers who will have the same problem.

My call for retrieving Drupal settings variables was made in the declaration part of the JavaScript:

var my_locs = Drupal.settings.my_module.my_locs;

I supposed this would be correct, since the Drupal settings object is already created, and since Javascript allows, like Java, the creation of new objects at declaration time.
But for some reason it didn't work.

I solved leaving the declaration

var my_locs;

and passing the object inside an initialize() method.

function initialize() {
    my_locs = Drupal.settings.my_module.my_locs;
    [...]

I hope it can be useful, since I lost lot of time on this.


On the publishing end, you'd need to categorize the data by site (e.g. use term references). Then expose that data as JSON using the built-in Views module. Allow that view to filter by site, to allow the subsites to select the content it wants to import.

On the consuming end:

There used to be the Feeds module that allowed a Drupal site to fetch data from a source and load that data onto content types on the site. But that module is still in development.
Alternatively, you could build a migration that is triggered in a hook_cron(). Migrate is already in core, I recommend also installing Migrate Plus and Migrate Tools for additional utilities.

In both cases, they would hit the main site at the url that Views is exposing, filter by the site term they want, and consume the JSON it returns.


Services 3 File upload, create/return image styles

the image created with the style when you request a page displaying that image_style So you have to call it in code.

The default generation method only creates images when they are requested by a user's browser.

image_style_url  Returns the URL for an image derivative given a style and image path

code sample :

// $file object from file_load($fid)
image_style_url('style name', $file->uri)


How to show separate values in Views from multi-value field

Adjust these settings in your view for the image field:


How to add a Google Maps containing GeoRss Feeds on a page - don't know exactly what module to use

Try to use GMap module. This module solve your issue.

How to use ?

If your issues not solved then try to use any of these modules :

Simple Google Maps
Google Maps Location

For GeoRSS try to use below module :

GeoRSS
Google Maps Tools


Authentication error when deploying site's content

My guess would be that on this step:

  For Endpoint URL, enter
  'http://your-destination-site.example.com/services/rest'. Click
  'Finish'. Note that it appears that any path other than
  '/services/rest' on either origin or destination generates a Request
  response error: -1002 missing schema.

Your entering the incorrect url. Make sure you are using clean url's. If not, make sure to include the "?q=" part for the path.


Show certain slides only on specific urls on views slideshow

Would you be better off having two separate views for the two URLs? If you do need this done in a single view, you will need to write custom module that adds filters to the view. Try using contrib module called views_arg_context


Blocks created twice for a single page load

$blocks = $page['revel_card_dashboard'];

This line of code grabbed the blocks that had already been created by drupal's original passthrough.


How do I add a class to a specific input type?

Template files are available by default for each input type.

Copy the input.html.twig file and rename it input--textfield.html.twig
Put it in the folder of the theme
Clear the cache and the new template will be used for all text-field form fields
You can add <input{{ attributes.addClass('input') }}/>{{ children }} in that file

If you want a more customized input field, you implement hook_theme_suggestions_HOOK().

function YOUR_THEME_NAME_theme_suggestions_input_alter(array &$suggestions, array $variables) {
  // To see available variables use kint().
  kint($variables);
  if ($variables['element']['#type'] == 'textfield' && $variables['element']['#name'] == field__--------- ) {
    $suggestions[] = 'input__customized';
  }
}


Remove "No front page content has been created yet"

There are many possible solutions for this problem, but here are a few of the more straightforward ones:

Edit the Frontpage view at /admin/structure/views/view/frontpage as follows:

This View form allows you to adjust the out-of-the-box front page. In the NO RESULTS BEHAVIOR section, click on the Global: Unfiltered text item. This will open a dialog box to edit that setting. From here you can see that this is where the undesirable message is coming from. Click on the Remove link beside the bottom buttons to remove that message. Depending on the desired front page behavior, you may also want to remove one or both of the other items listed under NO RESULTS BEHAVIOR.

Once you've removed the unwanted items, be sure to click the Save button on the View form to make those changes permanent. You can then browse to the front page and see the results. (You might need to Clear all caches at /admin/config/development/performance to see the change)

Or, create a custom front page:

Create new content of type Basic Page. Give it the title you want your front page to have. For the body, you can leave it blank, or put whatever static content you want to always appear on the front page. After saving and publishing this new content, write down the "/node/some-number" part of the URL.

You can now set this new node as the front page at /admin/config/system/site-information by changing the Default front page setting to the /node/some-number you wrote down earlier. Save the settings and things should be all set.

To do it programmatically, you might add this code to your custom theme or module

use Drupal\Views\ViewExecutable;

// Implements hook_views_pre_render().
function MY_THEME_OR_MODULE_NAME_views_pre_render(ViewExecutable $view) {
  if($view->id() == 'frontpage' && $view->current_display == 'page_1') {
    // Use some or all of the following 3 lines to remove specific
    // 'no results' behaviors
    unset($view->empty['area_text_custom']);
    unset($view->empty['node_listing_empty']);
    unset($view->empty['title']);
  }
}

or you could use $view->empty = []; instead of the 3 separate unset()'s to remove all "no results" behaviors from the frontpage view. Note that this code assumes you haven't changed the view's name or display name from the defaults. If this is not so, the if() statement will require some tweaking.


Define HTML element classes with pattern fields

yaml_field_name.field_drupal_machine_name[0]['#markup'] gave me the selection. problem solved.


Where do I put a custom function for multiple themes

You can put it in a module, or set up your themes so that they are sub themes of a main theme.


What's the best way to get the email of the author of a referenced node

With Rules:

Create a new Rule that reacts on event After saving new content.
Add a condition Content is of type to the rule and select the note content type in the content types section.
Add an action Fetch entity by id to the rule.

As entity type, select Node.
In the Identifier section, press button Switch to data selection (unless you already see an input field labeled Data selector).
From the Data selectors section, find the selector that references the ticket that is associated to the note. Copy that value into the Data selector input field.
In the Fetched entity section, set the variable label to "Referenced ticket" and the variable name to "referenced_ticket"
Save the action.

Add an action Send mail to the rule. You can now use referenced-ticket:author:mail as data selector for the recipient.


Fix the namespaces:

delete:
namespace Drupal\Core\Block\BlockBase;

add:
namespace Drupal\MY_COOL_MODULE\Plugin\Block;
use Drupal\Core\Block\BlockBase;


How to change a filter handler of the view?

I always take the following approach: Copy the existing views_data code via php:

// Copy the existing definition.
$data['table']['field_special'] = $data['table']['field'];
// Force the real field, so views still consider it as a different field in SQL.
$data['table']['field_special']['real field'] = 'field';
// Set a special handler.
$data['table']['field_special']['field']['handler'] = 'foo_handler_field_...';

This allows you to easy reuse the custom handler if needed, but at the same time not conflict with existing views.

In contrast to the approach of berliner (which certainly works) this does not add any runtime code execution, which adds potential bugs. This approach just uses basically configuration.


How to calculate the sum of 2 fields in a content type and display the result in a 3rd one when the node is saved?

Computed Field is a good solution. You can achieve a similar results without an additional module (provided you already have a custom module).

If you need to store the result when the node is saved, you can implement hook_node_presave() to set the value of the third fields just before the node data is saved to the database.

MODULE_node_presave($node) {
  $value = 0;
  $price_items = field_get_items('node', $node, 'field_price');
  if ($price_items) {
    $value += $price_items[0]['value'];
  }
  $vat_items = field_get_tems('node', $node, 'field_vat');
  if ($vat_items) {
    $value += $vat_items[0]['value'];
  }
  $node->field_value[LANGUAGE_NONE] = array(array('value' => $value));
}

Because the value is always calculated and simple, there is really no need to store it in the database. If your are already using the Entity API module and its entity metadata wrappers, this is easily doable with a hook_entity_property_info() implementation.


Twig template not rendering new field variable

@4k4, thanks for sharing the link. I was able to retrieve the value
this way: content.field_hide_header_title[0]

content.field_myfield[0] still gets the rendered output, now of the first field item. It's not a good idea to use it for programming, because the output can be formatted in different ways and is translatable. You don't want to adjust the code anytime this is changing.
For programming if/else code better use the block content object.
content['#block_content'].field_myfield.value
This is a similar question for a node field: Boolean field inside node twig renders ok but does not work in if statement


Variable_get question default value in form

The #default_value for a 'checkboxes' element must be an array rather than a single value (so you can have multiple default values selected).

All that code does is provide the default value wrapped in an array, so that it conforms to what the 'checkboxes' element type is expecting.


How do I access the Node Access User Reference configuration?

I found a clue in the README.txt which I'd previously missed

  Create a field to reference users in a content type using the Field UI.  The field's
  configuration page will contain the settings for Node access user reference.

I edited the User Reference field I'd created, and on the Edit tab was a collapsed heading for Node access user reference that I'd previously missed.  Clicking the heading revealed the configuration form.


Primary links background not visible by non-admins

Did you use the correct classes? E.g. when you use the .logged-in class in your CSS, the style will not be used when not logged in.


Ok, I find an answer. In my case the proper theme suggestion was html--node--edit.tpl.php I used theme debug mode to find it.

Also, to make page--node--edit.tpl.php works I need to delete my page--contenttype.tpl.php file. To customize my content type page I just used simple check in page.tpl.php if($node->type == 'book'):

<!-- THEME DEBUG -->
<!-- CALL: theme('html') -->
<!-- FILE NAME SUGGESTIONS:
   * html--node--edit.tpl.php
   * html--node--209.tpl.php
   * html--node--%.tpl.php
   * html--node.tpl.php
   x html.tpl.php
-->


How to restore form values from $form_state['values']?

Use Form default value:

'#default_value' => variable_get('sitename_textfield', ''),

If you use system_settings_form() you don't need to manually save your variables using a custom form submit function. Note: The variable must have the same name as the form item.

Function details: https://api.drupal.org/api/drupal/modules!system!system.module/function/system_settings_form/7

/**
 * Creates/returns a form to configure the variables.
 *
 * @param array $form
 * @param array $form_state
 * @return array
 */
function sitename_custom_form($form, &$form_state) {
  $form['sitename_textfield'] = array(
    '#type' => 'textfield',
    '#title' => t('Custom Textfield'),
    '#default_value' => variable_get('sitename_textfield', ''),
  );

  // Use system_settings_form() to automate saving configuration variables.
  return system_settings_form($form);
}


How can I upload and read an unmanaged file?

Maybe have a look at the CSVimportForm.php in xurizaemon/csvimport sample module. I wrote the D8 version. There an unmanaged uploaded CSV file gets read line by line. This happens in a batch process to prevent a timeout when you process a CSV with let's say a million lines.
The file gets uploaded to the temp dir and will be added to the files table as a temporary file. We make a copy of the file to the public files dir and let the garbage collector delete the original upload. You need to put the file somewhere on the server to read it in PHP. You don't have access to the browser in PHP. You then can delete the file when you are done.


Contextual filter has no results when using entity translation of non default language

not sure if I had the exact problem, but I solved my views / ET woes by adding 'entity translation' relationship. then you can filter by 'entity translation: language' and then select to user the user's current language. hopefully this helps!


How to install a module which includes a different version of Symfony?

So, I think if CiviCRM were installed into Drupal 8 via composer (ie. composer require civicrm/civicrm-core in the Drupal root) and CiviCRM's use of Symfony was compatible with Symfony 2.8 or 3.x (ie. not using deprecated functionality), this could work.

This would get everything installed in Drupal's vendor directory, rather than having two, and it'd mean that CiviCRM would use the Symfony version in Drupal 8. But if CiviCRM was compatible with later Symfony versions (even if it bundled an older version for Drupal 6 & 7 and other CMS's) it should be fine.

I think?

UPDATED: Yes, it works - I tried it. :-) I originally posted the below in the CiviCRM issue queue (CRM-17652), but re-posting here for completeness.

The big idea:

Since composer is pretty new to a lot of people, I'm going to attempt to go step by step, from some high-level composer stuff all the way to one way it could be done in CiviCRM:

Composer allows applications to require the libraries it needs (and libraries, of course, can require other libraries).
Libraries have a composer.json file which says what other libraries it needs and what versions it's compatible with (but not necessarily a specific single version - usually a range of versions, like ^2.4.3 which says a minimum of 2.4.3 and up to (but not including) 3.0.0)
Applications have a composer.json which similarly describes needed libraries and compatibility with a range of versions, but the range is really to help with updating. An application will also have a composer.lock which is a specific set of individual versions
Libraries can also have a composer.lock for their own testing or distribution (like building the release tarball with the dependencies bundled), but this is ignored when an application requires the given library (see https://getcomposer.org/doc/02-libraries.md#lock-file)
When an application wants to require a new library, composer finds an intersection of version compatibility between all the things the application requires (including all the libraries already installed and their dependencies) and the new library, possibly doing some updates to make everything line up (or erroring out if it can't find a compatible mix of versions)
In this case, CiviCRM is a library, and a particular Drupal 8 site is the application (Drupal core itself is a library)
CiviCRM could say it "requires" Symfony ^2.5 in its composer.json which means it is compatible with versions 2.5.0 up to (but not including) 3.0.0
When a Drupal 8 site wants to use CiviCRM, the site admin uses composer require civicrm/civicrm-core to require the CiviCRM library and all it's dependencies. If CiviCRM is compatible with Symfony 2.8 (like used in Drupal 8.3.x) everything will install and work fine, using the single Symfony 2.8 from Drupal. All the dependencies end up in Drupal's vendor directory.
However, CiviCRM could keep Symfony 2.5 in its composer.lock, which means the tests would use that, and the tarballs for Drupal 6 & 7 and other CMS's would bundle Symfony 2.5

The proposal:

Update the composer.json of CiviCRM so it can be used as a library by composer-based CMS's like Drupal 8 (but probably others could move that way in the future - composer is getting quite popular)
Make sure CiviCRM core is compatible with Symfony 2.8 and 3.0 (used by Drupal 8.3.x and 8.4.x respectively) but keep the "officially supported" version (currently Symfony 2.5) in the composer.lock for testing and the tarball for distribution. Being compatible with multiple Symfony versions may not be as hard as it sounds - there's a number of libraries out there compatible with both Symfony 2.8 and 3.0. It may just be a matter of avoiding deprecated methods/classes/features! The composer.json will need to be updated to reflect this
Use composer to install the CiviCRM library on Drupal 8 rather than copying into the libraries directory. This is becoming the normal way of installing 3rd party PHP libraries in Drupal 8 (this is used extensively by Drupal Commerce, for example)

For composer-based CMS's, I really think this is The Right Way. While this issue is currently affecting Symfony and Drupal, as the PHP community starts using more and more 3rd party libraries via composer, this could very well affect other CMS's with other version conflicts.

Some working code to test:

So, as promised, I actually got this to work to a limited degree :-) I'm totally coming at this from a Drupal/Composer/Symfony perspective -- I don't have a ton of CiviCRM experience, so there's probably some better ways to do my process below. I welcome any advice!

Download and install Drupal 8.3.5 (or the latest dev of Drupal 8.4.x!)
Go into the root directory in the shell and run these commands to install CiviCRM via composer: https://gist.github.com/dsnopek/56311dbea347874e75180883efabb620
If you use Apache, remove the vendor/.htacess file. This is a security measure from Drupal, which prevents resources like CSS/JS being loaded. This will need some collaboration with the Drupal project to figure out a proper solution because removing this file altogether is a bad idea on production. See: vendor/.htaccess blocking CSS/JS assets from composer libraries.
Go into the /modules directory and do git clone https://github.com/dsnopek/civicrm-drupal.git --branch composer-library
Go to the "Extend" page (/admin/modules) and install the CiviCRM module
Clear drupal cache via Drush (drush cr)
Log out and log back in again per CRM-19878
CiviCRM works! :-)

After all of this, CiviCRM is using Symfony 2.8 from Drupal and the dependencies in Drupal's vendor directory, and isn't loading anything from it's own vendor directory. Huzzah!

I tested enabling the "Telephone" module which failed before these changes (see my steps to reproduce), but works fine with them. :-)


Documentation of Drupal Content Types and Views

admin/reports/fields - Field list with node type relationships.
admin/reports/fields/views-fields - Used in views.

You need Field UI module enabled.


Broken file derivatives when creating an article

Change the ownership of file folder to www-data:www-data and give permission to 755 in recursive way.


How do I obtain the result summary from within a form on the view page?

However, the result summary for the view would appear to need to go in
  the middle of the form.

  Since this is on a View page, is there a way to get the current View
  and fetch its result summary within a hook_form_alter()?

Don't complicate your Drupal life, and just KISS.

I assume you already added the Result Summary to your View's header. So just:

style.css

.view-id-[your-id] .view-header {

  position: absolute;
  top: 70px;

}


It is not well explained in the documentation, but structure_sync works by generating a new configuration item with all the exported content. It does not generate new files by itself.

Later, when you export the configuration, the new config item appears.