How can I disable a user that should still be visible on the site?

Using a custom module, you could change the permission to see user profiles. For example, the following code could be used for Drupal 7.

function mymodule_permission() {
  return array(
    'access blocked user profiles' => array(
      'title' => t('View user profiles of blocked users'),
    ),
  );
}

function mymodule_menu_alter(&$items) {
  if (isset($items['user/%user'])) {
    $items['user/%user']['access callback'] = 'mymodule_view_access';
  }
}

function mymodule_view_access($account) {
  $uid = is_object($account) ? $account->uid : (int) $account;

  // Never allow access to view the anonymous user account.
  if ($uid) {
    // Admins can view all, users can view own profiles at all times.
    if ($GLOBALS['user']->uid == $uid || user_access('administer users')) {
      return TRUE;
    }
    elseif (user_access('access user profiles')) {
      // At this point, load the complete account object.
      if (!is_object($account)) {
        $account = user_load($uid);
      }
      if (is_object($account)) {
        // If the account is blocked, show the profile to users with the right
        // permission.
        return ($account->status ? TRUE : user_access('access blocked user profiles'));
      }
    }
  }
  return FALSE;
}

Give the new permission to anonymous users, and they will be able to see the user profile of blocked users.

This is probably easier than changing password and email, and it's easier to revert if you block by mistake a current employee: Just unblock the account.

The code I shown works for a direct access to the user profile, and for modules that only verify the user has the access user profile permission to show the link to a user profile. This is what Drupal does, for example in template_preprocess_username().

  $variables['profile_access'] = user_access('access user profiles');
  $variables['link_attributes'] = array();
  // Populate link path and attributes if appropriate.
  if ($variables['uid'] && $variables['profile_access']) {
    // We are linking to a local user.
    $variables['link_attributes'] = array('title' => t('View user profile.'));
    $variables['link_path'] = 'user/' . $variables['uid'];
  }
  elseif (!empty($account->homepage)) {
    // Like the 'class' attribute, the 'rel' attribute can hold a
    // space-separated set of values, so initialize it as an array to make it
    // easier for other preprocess functions to append to it.
    $variables['link_attributes'] = array('rel' => array('nofollow'));
    $variables['link_path'] = $account->homepage;
    $variables['homepage'] = $account->homepage;
  }

Any module using theme('username') (for which template_preprocess_username is a preprocess function) to show the user name will print the link to the user profile, even if the shown user account is blocked, if the currently logged-in user has the access user profile permission.

If there are modules that check the user account is blocked before showing a link to the user profile, then this method will not work.

In this case, the alternative I would adopt is the following:

Don't block the user accounts for those ex employees
Add a flag to the user accounts that says if an account can be used to log in
Using an extra validation handler for the login form, return an error if one of those accounts is used to log in

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_login' || $form_id == 'user_login_block') {
    $form['#validate'][] = 'mymodule_user_login_validate';
  }
  elseif ($form_id == 'user_register_form') {
    $form['account']['can_login'] = array(
      '#type' => 'checkbox',
      '#title' => t('The user account can be used to log in'),
      // The form is for registering a new user; there is nothing to load from the database.
      '#default_value' => TRUE,
      // See user_register_form() which set the following value to TRUE if
      // the currently logged-in user administer users.
      '#access' => $form['administer_users']['#value'],
    );
    $form['#submit'][] = 'mymodule_register_submit';
  }
  elseif ($form_id == 'user_profile_form') {
    if ($form['#user_category'] == 'account') {
      $form['account']['can_login'] = array(
        '#type' => 'checkbox',
        '#title' => t('The user account can be used to log in'),
        '#default_value' => mymodule_load_flag($form['#user']->uid),
        '#access' => user_access('administer users'),
      );
      $form['#submit'][] = 'mymodule_profile_submit';
    }
  }
}

function mymodule_user_login_validate($form, &$form_state) {
  if (!empty($form_state['uid'])) {
    // The user trying to login is not limited by flood control;
    // user_login_authenticate_validate() found a user with the username and password entered in the login form.
    if (!mymodule_load_flag($form_state['uid'])) {
      form_set_error('name', t('The username %name cannot be used to login.', array('%name' => $form_state['values']['name'])));
    }
  }
}

function mymodule_register_submit($form, &$form_state) {
  if ($form_state['values']['administer_users']) {
    // The user submitting the form can administer users.
    // user_register_submit() sets $form_state['values']['uid']; save it in
    // a database table the module creates when installed.
    mymodule_save_flag($form_state['values']['uid'], $form_state['values']['can_login']);
  }
}

function mymodule_profile_submit($form, &$form_state) {
  if (user_access('administer users') && $form['#user_category'] == 'account') {
    // user_profile_submit() sets $form_state['values']['uid']; save it in
    // a database table the module creates when installed.
    mymodule_save_flag($form_state['values']['uid'], $form_state['values']['can_login']);
  }
}


How do I redirect after saving the user account with $user->save()?

I suppose you want to remain on your site when redirecting.
I don't recommend hardcoded URL's anywhere else but in route.yml files.
Call the right service and don't forget to use dependency injection in your services and don't use a trait or directly call it from the container.

  private function redirect(string $route) {
    $path = $this->container->get('url_generator')->getPathFromRoute($route);
    return new RedirectResponse($path);
  }


Unable calculate date field using strtotime

I got it. It should be:

// Extract the first field item
$date_items = field_get_items('node', $node, 'field_date_start_rent');
$date_item = array_shift($date_items);
$integer_items = field_get_items('node', $node, 'field_subscription_period');
$integer_item = array_shift($integer_items);

// Get the field value
$start_rent = $date_item['value'];
$period = $integer_item['value'];

// Update the other field
$node->field_cubagan[$node->language][0]['value'] = date('Y-m-d h:i:s', strtotime("+$period year",strtotime($start_rent)));

// Save the node
node_save($node);


I it been a long time that you created that content type ?

It is on a production website already ?

Are you working on a fresh Drupal 7 installation ?

You could delete and recreate that content type if there is no serious impact on your site or your data.

If you do that, then your can check if the situation happens again. Sometimes there are particular manipulations while working that are responsible for those situations (and you can find out if you did something in a certain way the first time).

But remember : to me this operation depends on the 3 questions that I've asked on top of this text.

Does it help a bit ?


How can I access this site as the administrator?

I think default is substituted for the site name in your drush result, try http://example.com/user/reset/1 which would be the standard password reset page for a user with a uid of 1 (the admin user).

If that doesn't work the default theme is set by the theme_default variable...you can edit the variable table in the database manually and set the value column for that variable to whatever theme you want.


The Mini Panels sub-module of Panels allows you to create panels as blocks, which you could then place into any region on your site. There is an abundance of documentation, tutorials, etc. on using Panels and MiniPanels, but which resources to link you to would depend upon the version of Drupal you are using. There is an existing answer that will probably help you learn more.


How to jump to a specific page in a multipage Webform?

I've just published a webform_steps module that provides a navigation bar for multi page webforms. It solves the problem by implementing a submit-handler that simulates the next and previous buttons very similar to how you describe it.

The magic has to happen on the PHP side in the $form_state array.


Display definition of the term searched for - above search results

It turned out it was necessary to use Wordnik api (or similar) to get the definition service that I required. So I've written a module to handle the api and show definition/image for the searched terms if available.

After talking to Google support and verifying my research that google no longer provides a definition service (they did back in 2011) to private websites, I realized it best to abandon the idea of using the google custom search engine. Instead I've setup Solr which is a bit more work but much more custom.


How to render an image at its original size?

You can also use the #theme property image (which does not appear to be documented anywhere), but gives a valid image tag.

$render= [
  '#theme' => 'image',
  '#uri' => $file->getFileUri(),
];

Which becomes <img src="/sites/default/files/image.png" alt="" /> once rendered.


Fallback value for contextual filter, in case the "provided default value" does not exist

Just set your contextual filter to return 1 when the value is not available like so:


Panels is a great module, but it can also be complex and it can take a while before you completely understand it. If you're interested in using panels for every page, the Panels Everywhere module is an interesting project.

Another great project that provides more flexible layouts is Display Suite.

Although people tend to use either Panels or DS, they are not competitors. They can be even used together as you can read on the blog of the author/maintainer of DS: Using panels on view modes in Drupal 7.


How to redirect a user to his own content after log in?

To list the contents of a ( the current) user you can set-up a view and add a filter ar URL argument. To redirect the user to this view after login you can use rules.


Recommended Drush version to use and install for Ubuntu 19 with PHP 7.2 and running Drupal 7

Drush 9 does not work with drupal 7, but drush 8 does work with it. I installed it by creating a new ubuntu user and making sure composer is installed globally then install cgr via:

composer global require consolidation/cgr

then add to your ~/.bashrc file

export PATH="$HOME/.config/composer/vendor/bin:$PATH"

then

cgr drush/drush:8.x-dev --prefer-source

link: https://github.com/consolidation/cgr#installation-and-usage

Then I followed the tutorial here: https://docs.drush.org/en/8.x/install-alternative/

  Install a global Drush via Composer

  Follow the instructions below:

  Install Composer globally.

  Install the cgr tool following the instructions in that project.

  Add composer's bin directory to the system path by placing export
  PATH="$HOME/.composer/vendor/bin:$PATH" into your ~/.bash_profile (Mac
  OS users) or into your ~/.bashrc (Linux users).

  Install latest stable Drush: cgr drush/drush.

  Verify that Drush works: drush status

  Please do not install Drush using composer global require. See Fixing
  the Composer Global command for more information.


How to reference taxonomy used by other content type?

For simple displaying of taxonomy term

Assuming your are using entityreference for Drupal 7 the module provides out of the box a field formatter that allows you to display the Rendered entity with a specific view mode

Thus you can display the referenced entity with the taxonomy term included.

Go to the manage display of your Content B and change the format to Rendered entity and choose teaser for the view mode

Go to the manage display of your Content A and modify the teaser view mode and add the taxonomy term field to be displayed.

For more advanced use cases

You might want to try any combination of the following

field_extractor to extract a specific field from a referenced entity
inline_entity_display similar to above
field_reference refer to specific field on the same node/entity or other node/entities


Ok, well, I don't know what the problem was. I tried everything I could think of (see above). So I just changed the name of the image in 'default/files' and changed the name of the file in the link to it in the block. Now it's showing correctly.


You can use the Drupal theme suggestions to specify templates based on any of the users fields.

I've implemented a theme for each of the different roles on my site for instance:

function [theme]_preprocess_user_profile(&$vars) {

foreach($vars['elements']['#account']->roles as $role):

    $vars['theme_hook_suggestions'][] = 'user_profile__'. str_replace(' ','-', $role);

endforeach;

}

To do the same with a users name for instance you could do:

$vars['theme_hook_suggestions'][] = 'user_profile__'. str_replace(' ','-', $vars['elements']['#account']->name);

Then make sure you've got the corresponding theme files inside your theme folder. All underscores are converted by Drupal to dashes so a suggestion of user_profile__dave would become user-profile--dave.tpl.php for instance.


"An illegal choice has been detected" error on user creation

When you submit a form Drupal checks the integrity of it, i.e. it checks that the submitted values fall in line with the list of possible values for each element in the original form definition.

So, if you've got a select/checkboxes/radio buttons element on the form and you change the possible options for this using javascript on the client side, the new options won't match up with the ones Drupal knew about when the form was built. In this instance Drupal will rightly inform the user "An illegal choice has been detected.", because it has. This is an excellent security feature and is the default behaviour. It can't be switched off without some serious effort.

I would take a guess in your case that this problem is happening in the JS you're attaching to the autoassignrole_user element.

If you want to change a form's structure using JS you need to do it the 'Drupal' way, using AJAX to update the form on the server-side:

function MYMODULE_my_form($form, &$form_state) {
  // If the checkbox is ticked, load one set of options
  if (isset($form_state['values']['check']) && $form_state['values']['check']) {
    $options = new_options();
  }
  else {
    // Otherwise load the default options
    $options = default_options();
  }

  $form['check'] = array(
    '#type' => 'checkbox',
    '#title' => 'Click to change options',
    '#default_value' => isset($form_state['values']['check']) ? $form_state['values']['check'] : 1,
    '#ajax' => array(
      'wrapper' => 'options-wrapper',
      'callback' => 'my_form_ajax_callback'
    )
  );

  $form['options'] = array(
    '#type' => 'select',
    '#title' => 'Options',
    '#options' => $options,
    '#prefix' => '
',
    '#suffix' => '
'
  );
}

function my_form_ajax_callback(&$form, &$form_state) {
  // Return the options element which will have been changed in the re-build of the form
  return $form['options'];
}

The above is a very simple AJAX example that uses a checkbox change event to change the values in a select list on the form. Doing it this way will keep the internal structure of the form intact and you will no longer get the error message you're currently getting.

Have a look at the Form API documentation and AJAX framework documentation for a lot more information on this.


Print multiple files field links, descriptions and file extensions in Twig

You should be able to do something like this,

{% for file in node.field_file['#items'].entity %}
  {{ file.uri.value }}
  {{ file.name.value }}
{% endfor %}


How do I get node revisions to use my custom template?

You can try my patch from Make node_is_page() work on revisions and previews as well. If that doesn't fix it, you can probably use the relatively simple code update from inside node_is_page() to add your own template suggestions using hook_theme_suggestions_alter.


Is there a way to pass multiple arguments to menu_name while creating menu links programmatically?

No. When you're building links for D7's menu system, you'll need to specify the entire link array because you're creating link metadata here. If you're trying to keep your code DRY you could try to create a template array (or function) then copy/update as you needed new links, but you're probably doing just as much work for little/no performance gain or clarity.


Trouble setting up a search for a single field

You can do this with Views.

Install Views.
Go to Structure>Views then + Add new view.
Set Show [content] of type [Your Content type here] (also tick Create a page) then Continue & edit button.
Under FORMAT select Show: Fields. Then under FIELDS click Add button and add the fields you want to show in the result. Then click Add button next to FILTER CRITERIA and add your zip-code field. On the settings screen of that field tick "Expose this filter to visitors, to allow them to change it".


How to copy Location Country field value from Parent object to Child object field default value?

Guess you want this to take place, when you create (aka save to db) a new node. You could do this in hook_node_presave.


How to check if field exists in an entity?

You can use the method hasField():

$entity->hasField('abc')


The documentation for the plugin says:

  The node row style will display each item of the view through Drupal's standard node_view() function. Views has very little control over this output, except for the options you see.  You can choose from different Build modes. By default there are "Teaser" and "Full node". You can also decide if you want to "Display links" and/or "Display node comments".

  Because the output is run through the standard node template mechanism (typically node.tpl.php or a variant thereof), any decisions about what is output may be done there.

  Views does add an extra 'suggestion' to the list of possible node templates: node-view-VIEWNAME.tpl.php—you may use this to theme a node specifically for the view. This can be handy for creating very small teasers and the like.

The template file could be different from node.tpl.php if there are other template files suggested for the content type, or a node in particular; the Views module itself suggests a template file whose name depends from the view name. Then, between the node.tpl.php defined from the Node module, and the same file defined from the theme, the latter is the used one.

The rendering method use for that plugin is views_plugin_row::render(), which contains the following code.

return theme($this->theme_functions(), $this->view, $this->options, $row, isset($this->field_alias) ? $this->field_alias : '');

With Drupal 7, the method is views_plugin_row_node_view::render(), which contains the following code.

  if (isset($this->nodes[$row->{$this->field_alias}])) {
    $node = $this->nodes[$row->{$this->field_alias}];
    $node->view = $this->view;
    $build = node_view($node, $this->options['view_mode']);

    return drupal_render($build);
  }

References

The documentation page for views_plugin_row_node_view (Drupal 6)
The documentation page for views_plugin_row_node_view (Drupal 7)


Programmatically fill the "Publish On" date field value provided by the Scheduler Module

You should be able to provide a default value using a hook_field_widget_form_alter() to modify the #value_callback of the TimestampDatetimeNoDefaultWidget that scheduler uses to a custom one, and this is how you can pass custom logic for a default value. Here's some sample code that could go in your custom module, you could add/modify conditions and logic as needed, but this should at least get things moving in the right direction:

<?php

/**
 * @file
 * Publish On Default module file.
 *
 * This module provides a default value for the "Publish On" value
 * for nodes.
 */

use Drupal\Core\Datetime\Element\Datetime;
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\scheduler\Plugin\Field\FieldWidget\TimestampDatetimeNoDefaultWidget;
use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_field_widget_form_alter().
 */
function mymodule_field_widget_datetime_timestamp_no_default_form_alter(&$element, FormStateInterface $form_state, $context) {
  // Only alter the callback for the "Publish On" instance of the `datetime_timestamp_no_default` widget.
  if (isset($element['#title'])) {
    if ($element['#title']->__toString() == "Publish on") {
      $element['value']['#value_callback'] = 'mymodule_publish_on_default_value_callback';
    }
  }
}

/**
 * Callback function to add default time to the publish on widget.
 */
function mymodule_publish_on_default_value_callback(&$element, $input, $form_state) {
  // If no default value, set the default to the current date/time.
  if (empty($element['#default_value'])) {
    $date_format = $element['#date_date_format'];
    $time_format = $element['#date_time_format'];
    $timezone = !empty($element['#date_timezone']) ? $element['#date_timezone'] : NULL;
    $date_time_format = trim($date_format . ' ' . $time_format);
    $date_time_input = date('Y-m-d H:i:s');
    $date = DrupalDateTime::createFromFormat($date_time_format, $date_time_input, $timezone);
    $element['#default_value'] = $date;
    $input = FALSE;
    return Datetime::valueCallback($element, $input, $form_state);
  }
  // Fallback to the original valueCallback() method.
  else {
    return TimestampDatetimeNoDefaultWidget::valueCallback($element, $input, $form_state);
  }
}


To make the form variable available in the Twig template you need to supply a context like follows.

$build['page'] = [
  '#type' => 'inline_template',
  '#template' => $template,
  '#context' => ['form' => $block_content],
];

Generally, I would recommend using custom #theme hook instead of an inline template.

Another way to render block within a template is using Twig Tweak module.

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


Cloudflare country code for language negotiation

Drupal provides a hook for those module that implements a new method for detecting the language to use: hook_language_negotiation_info(). This hook gets information about some callbacks, including the one that returns the language ID.
As example of hook, you can look at locale_language_negotiation_info(), and to the three callbacks used for the first provider: locale_language_from_url(), locale_language_switcher_url(), and locale_language_url_rewrite_url().

Any provider the modules implement are listed on admin/config/regional/language/configure, where the administration user can enable each of them.

The providers that are enabled are called to provide a language ID. For what I can understand code similar to the following one should work.

function mymodule_language_negotiation_info() {
  $providers = array();

  $providers['mymodule_cloudflare_provider'] = array(
    'callbacks' => array('language' => 'mymodule_language_from_cloudflare'),
    'weight' => -4,
    'name' => t('Cloudflare'),
    'description' => t("Use Cloudflare to detect the language used where the user is actually located."),
  );

  return $providers;
}

function mymodule_language_from_cloudflare($languages) {
  if (isset($_SERVER["HTTP_CF_IPCOUNTRY"])) {
    $langcode = mymodule_get_langcode($_SERVER["HTTP_CF_IPCOUNTRY"]);
    if (isset($languages[$langcode])) {
      return $langcode;
    }
  }

  return FALSE;
}

mymodule_get_langcode(), the function for which I didn't write the code, should return the language code from the country code returned from Cloudflare.com.


drupal 7 - drupal_add_js - inline doesn't execute

Go through this document http://drupal.org/node/171213 It shows how to use Jquery. The syntax for jquery ready function is:

jquery(document).ready(function($) {
// Code that uses jQuery's $ can follow here.
});


Migrate Multiple URLs from a Spreadsheet into ONE Link Field

The two main ways to approach this with php are via hook or plugin.
The first is with a hook, specifically, hook_migrate_MIGRATION_ID_prepare_row().

Allows adding data to a row for a migration with the specified ID.

For example, you could combine your two link columns to a new column formatted as an array.
function my_module_migrate_MY_MIGRATION_ID_prepare_row(Row $row, MigrateSourceInterface $source, MigrationInterface $migration) {
  // Assuming your url fields are keyed event_url and ticketing_url in your migration.yml.
  $links_array = [];
  if ($row->hasSourceProperty('event_url')) {
    $event_url = $row->getSourceProperty('event_url');
    if (!empty($event_url)) {
      $links_array[] = [
        'title' => 'Event URL',
        'uri' => $event_url,
      ];
    }
  }
  if ($row->hasSourceProperty('ticketing_url')) {
    $ticketing_url = $row->getSourceProperty('ticketing_url');
    if (!empty($ticketing_url)) {
      $links_array[] = [
        'title' => 'Ticketing URL',
        'uri' => $ticketing_url,
      ];
    }
  }

  $row->setSourceProperty('event_and_ticketing_url', $links_array);
}

You can use your programmatically added source value in your process section like:
process:
  ...
  field_links: event_and_ticketing_url
  ...

I prefer to use plugins over hooks whenever possible for a few reasons, but one is because plugins are more visible to anybody looking at the implementation later. By looking at the migration.yml, a future developer will know that a custom plugin does something to this thing and the plugin can be found in the src/Plugin directory.
An example doing the same thing, but with a plugin might look like:
my_module/src/Plugins/migrate/process/EventAndTicketingLinks.php:
/**
 * Process plugin to combine event and ticketing url sources to one links array.
 *
 * Example Usage:
 *
 * field_my_links_field:
 *   plugin: my_module_event_and_ticketing_links
 *   link_fields:
 *     event: event_url
 *     ticketing: ticketing_url
 *
 * @MigrateProcessPlugin(
 *   id = "my_module_event_and_ticketing_links",
 * )
 */
class EventAndTicketingLinks extends ProcessPluginBase {

  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
    $config = $this->configuration;
    $links = [];

    if (!empty($config['link_fields']['event'])) {
      $event_url = $row->getSourceProperty($config['link_fields']['event']);
      if (!empty($event_url)) {
        $links[] = [
          'title' => 'Event Url',
          'uri' => $event_url,
        ];
      }
    }
    if (!empty($config['link_fields']['ticketing'])) {
      $ticketing_url = $row->getSourceProperty($config['link_fields']['ticketing']);
      if (!empty($ticketing_url)) {
        $links[] = [
          'title' => 'Ticketing Url',
          'uri' => $ticketing_url,
        ];
      }
    }

    return $links;
  }

}

Additionally, since you ended up combining the urls into one source column anyway, you could use the hook or a plugin to work with that data too.


You need to:
 - Set the filter granularity to "Day"
 - Add a date format "Ymd" admin/config/regional/date-time/formats
 - Add a date type to attach that to...admin/config/regional/date-time
 - OR, just change whatever date type the view is using to use it


Bearer Token in url is not parsed by route

Finally after spending few days doing debugging and searching I noticed that the error was due to my Nginx configuration , this configuration from Nginx website was what solved the problem for me:
server {
    server_name example.com;
    root /var/www/drupal/MYSITE/web;

    location = /favicon.ico {
      log_not_found off;
      access_log off;
    }

    location = /robots.txt {
      allow all;
      log_not_found off;
      access_log off;
    }

    # Very rarely should these ever be accessed outside of your lan
    location ~* \.(txt|log)$ {
      allow 192.168.0.0/16;
      deny all;
    }

    location ~ \..*/.*\.php$ {
      return 403;
    }

    location ~ ^/sites/.*/private/ {
      return 403;
    }

    # Block access to scripts in site files directory
    location ~ ^/sites/[^/]+/files/.*\.php$ {
      deny all;
    }

    # Allow "Well-Known URIs" as per RFC 5785
    location ~* ^/.well-known/ {
      allow all;
    }

    # Block access to "hidden" files and directories whose names begin with a
    # period. This includes directories used by version control systems such
    # as Subversion or Git to store control files.
    location ~ (^|/)\. {
      return 403;
    }

    location / {
      try_files $uri /index.php?$query_string;
    }

    location @rewrite {
      rewrite ^ /index.php;
    }

    # Don't allow direct access to PHP files in the vendor directory.
    location ~ /vendor/.*\.php$ {
      deny all;
      return 404;
    }

    # Protect files and directories from prying eyes.
    location ~* \.
    (engine|inc|install|make|module|profile|po|sh|.*sql|theme|twig|tpl(\.php)?
    |xtmpl|yml)(~|\.sw[op]|\.bak|\.orig|\.save)?$|/(\.(?!well-
    known).*|Entries.*|Repository|Root|Tag|Template|composer\.
    (json|lock)|web\.config)$|/#.*#$|\.php(~|\.sw[op]|\.bak|\.orig|\.save)$ {
      deny all;
      return 404;
    }

    # In Drupal 8, we must also match new paths where the '.php' appears in
    # the middle, such as update.php/selection. The rule we use is strict,
    # and only allows this pattern with the update.php front controller.
    # This allows legacy path aliases in the form of
    # blog/index.php/legacy-path to continue to route to Drupal nodes. If
    # you do not have any paths like that, then you might prefer to use a
    # laxer rule, such as:
    #   location ~ \.php(/|$) {
    # The laxer rule will continue to work if Drupal uses this new URL
    # pattern with front controllers other than update.php in a future
    # release.
    location ~ '\.php$|^/update.php' {
      fastcgi_split_path_info ^(.+?\.php)(|/.*)$;
      # Ensure the php file exists. Mitigates CVE-2019-11043
      try_files $fastcgi_script_name =404;
      # Security note: If you're running a version of PHP older than the
      # latest 5.3, you should have "cgi.fix_pathinfo = 0;" in php.ini.
      # See http://serverfault.com/q/627903/94922 for details.
      include fastcgi_params;
      # Block httpoxy attacks. See https://httpoxy.org/.
      fastcgi_param HTTP_PROXY "";
      fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
      fastcgi_param PATH_INFO $fastcgi_path_info;
      fastcgi_param QUERY_STRING $query_string;
      fastcgi_intercept_errors on;
      # PHP 5 socket location.
      #fastcgi_pass unix:/var/run/php5-fpm.sock;
      # PHP 7 socket location.
      fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
    }

    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
      try_files $uri @rewrite;
      expires max;
      log_not_found off;
    }

    # Fighting with Styles? This little gem is amazing.
    location ~ ^/sites/.*/files/styles/ {
      try_files $uri @rewrite;
    }

    # Handle private files through Drupal. Private file's path can come
    # with a language prefix.
    location ~ ^(/[a-z\-]+)?/system/files/ {
      try_files $uri /index.php?$query_string;
    }

    # Enforce clean URLs
    # Removes index.php from urls like www.example.com/index.php/my-page -->
    www.example.com/my-page
    # Could be done with 301 for permanent or other redirect codes.
    if ($request_uri ~* "^(.*/)index\.php/(.*)") {
      return 307 $1$2;
    }
}


How do I pass an object from javascript to PHP?

You are using a POST, it is the same way you, use

$new_ships = $_POST['new_ships'];
$destroyed_ships = $_POST['destroyed_ships'];

Read more on php POST.


Programmatically develop search exposed filters

I finally managed to do this with the following changes.

I have changed the form method from post to get and then took the value of search term for url using $_GET
Assigned action to the current page on which I am.

Changed the following code to

    'page callback' => 'drupal_get_form',
    'page arguments' => array('recordingcrud_sort_with_pager_content'),

to

'page callback' => 'recordingcrud_sort_with_pager_content',

and removed the second line.


Programmatically alter taxonomy term tree options

This can be accomplished by modifying the #after_build item of your term_reference_tree field in hook_form_alter:

function MYMODULE_form_alter(&$form, &$form_state) {
  // You might want to do this only for certain forms,
  // or only for forms that have the field to be altered.
  $language = $form['my_taxonomy_field']['#language'];
  $form['my_taxonomy_field'][$language]['#after_build'][] = 'MYMODULE_branch_group_form_element_after_build';
}

function MYMODULE_branch_group_form_element_after_build($form_element, &$form_state) {
  MYMODULE_taxonomy_tree_form_element_alter($form_element[0]);
  return $form_element;
}

function MYMODULE_taxonomy_tree_form_element_alter(&$element) {
  foreach ($element as $tid => $data) {
    if (($tid[0] != '#') && is_numeric($tid)) {
      // MODIFY HERE:  If you do not want to show the term with
      // a specified tid, hide() it here.
      if ($tid == 60) {
        hide($element[$tid]);
      }
      else {
        // OPTIONAL: Alter the way each individual term is rendered.
        // See BONUS ANSWER, below.
        MYMODULE_taxonomy_tree_form_element_term_alter($element[$tid][$tid], $tid);
        // Recursively alter the children of the tree -- the item we
        // want to modify may be nested somewhere inside the tree.
        if (array_key_exists($tid . '-children', $element[$tid])) {
          MYMODULE_taxonomy_tree_form_element_alter($element[$tid][$tid . '-children']);
        }
      }
    }
  }
}

BONUS ANSWER:  In addition to filtering out items, I also wished to add a rendered icon with each taxonomy term in the tree.  In order to allow the specific fields of the taxonomy vocabulary to be selected and ordered, and the rendering mode (i.e. thumbnail size) of the image field to be selected through the admin user interface, I used the entity_view_mode module to define a new view mode for my taxonomies.

/**
 * Alter the data built by term_reference_tree.widget.inc.
 * @see: _term_reference_tree_build_item()
 */
function MYMODULE_taxonomy_tree_form_element_term_alter(&$element, $tid) {
  $term = taxonomy_term_load($tid);
  // In order for this to work, you will need to install the
  // entity_view_mode module, and make a 'term_with_icon'
  // view mode for your taxonomy vocabulary.
  $term_render_array = taxonomy_term_view($term, 'term_with_icon');
  $element['#title'] = drupal_render($term_render_array);
}


Entity field query condition to match multi-value field

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
       ->entityCondition('bundle', 'node_type')
       ->fieldCondition('field_myfield', 'target_id', array(
          $id_1,
          $id_2
        ), 'IN');

For reference see https://www.drupal.org/docs/7/creating-custom-modules/howtos/how-to-use-entityfieldquery-for-drupal-7


Login from one Drupal instance on another Drupal instance

Have a look at the Single Sign On module. It's only for Drupal 6, which is what you need, but it's not actively maintained. If it works as advertised, I think you are good to go.

There is also the Bakery Single Sign-On System, but I don't think it fits your specs and requirements.


The conents of the template files are not cached. So your concern is misplaced.

I am assuming that it is views. Edit the view goto Advanced->Others->Theme Information you can find out which template file is being used. Goto to the file and make the necessary changes or else copy the default file from the views module to the location.

Even if the above is not solving your problem, the var_dump is coming from the database and not code.


Trouble with contextual links after node teaser refresh via ajax

Once new HTML has been added to the DOM in a custom way, then to attach all Drupal behaviors defined by active modules, you need to call Drupal.attachBehaviors().

It may be possible that you are not calling Drupal.attachBehaviors() after new content is injected into the DOM. Until you do this, NO Javascript will be applied to the newly inserted elements.

Example of attaching behavior ('YOUR_DOM_SELECTOR' will the element which you are refreshing via ajax):

Drupal.attachBehaviors('YOUR_DOM_SELECTOR');


Entity translation: views with and without language fallback

There doesn't seem to be a solution with "Enable language fallback" activated. I guess it has to be made the other way around. Disabling it and add a fallback on views level using the "No results behavior".


What is the difference between Referenced Entity and Referencing entity in views

Say you have a content type called course that has a entity reference field that targets a content type called school.

In views you could now add a relationship using "Entity Reference: Referenced Entity" and fetch values from the school that the course belongs to.

You list of courses could now show something like:
Course X - School X

So far so good.

Now let's say you want to list schools and which courses they provide.
Since the entity reference field points from course to school you need to fetch the reference the other way. Now you can instead use "Entity Reference: Referencing entity". This way you could list schools and courses:

School X - Course X.

You will end up with duplicate rows in some cases if several courses points to the same school, but that's another story :)

Hope this made the relationship bit clearer.


Existing module for logged in user image upload

You can make that in different ways, you can use the media module to create image galleries, remember if you use that module installing Styles


View with relationship - column displaying count of related nodes

You can do this with Aggregation.

First create your normal Views listing Interviewee nodes. Add the Media reference field and set to show all values in one row.

Turn Aggregation on, and change the Aggregation settings for the Media reference field to Count or Count DISTINCT.

Sorting criteria can sometimes mess up Aggregation counting so it's best not to have any while you're configuring the Aggregation, then add later once you know Aggregation is working and check each step that it's working as expected.

You can even add the Sort criteria for the reference field and use Aggregation on it (again Count or Count DISTINCT), Expose it if you want to allow users to change the order Ascending/Descending.

Sorting also works in a table Format if you turn on sorting for that field.


You would probably have an easier time using the services module it's better supported and used far more than the restws module. It supports several types of web service calls including RESTful.

SERVICES:

  A standardized solution of integrating external applications with Drupal. Service callbacks may be used with multiple interfaces like REST, XMLRPC, JSON, JSON-RPC, SOAP, AMF, etc. This allows a Drupal site to provide web services via multiple interfaces while using the same callback code.


In the View create a relationship with the User uid. After this You should see a few more field options for you to use.


Below code is redirecting to my-page

<?php

function my_module_block_info() {
$blocks['visit'] = array(
    'info' => t('Visit'),
    'cache' => DRUPAL_CACHE_GLOBAL
);
return $blocks;
}
function my_module_block_view($delta = '') {
$block = array();
if (arg(0) == 'node' && is_numeric(arg(1)) && arg(2) == '') {
    $nid = arg(1);
}
switch ($delta) {
    case 'visit':
        $block['content'] = drupal_get_form('visit_project', $nid);
        break;
}
return $block;
}
function visit_project($form, &$form_state, $nid) {
$form['id'] = array(
    '#type' => 'hidden',
    '#value' => $nid,
);
$form['actions'] = array('#type' => 'actions');
$form['actions'] = array(
    '#type' => 'submit',
    '#value' => t('Visit'),
    '#attributes' => array('class' => array('general_button')),
    //'#submit' => array('_visit_project_details')
    '#submit' => $form['actions']['submit']['#submit'],
);
$form['actions']['#submit'][] = '_visit_project_details';
return $form;
}

function my_module_menu() {
$items['my-page'] = array(
    'title' => 'Title of my page',
    'page callback' => 'project_details',
    'access callback' => TRUE,
);
return $items;
}
function _visit_project_details($form, $form_state)
{
   //$form_state['redirect'] = 'my-page';
   drupal_goto('my-page');
}
function project_details() {
    return '
ok in details of '.$_POST['id'].'
';
}


Display the size and format of a file attached to an article

Try getSize and getMimeType in your my_theme.theme as in the example below

function my_theme_preprocess_node(&$vars) {
  $node = $vars['node'];
  $type = $node->getType();
  if( $type == "article" && $node->hasField('field_file')){
      //next gets FieldItemList
      //$file = $node->get('field_file');

      //you need get the file entity
      $file = $node->get('field_file')->entity;
      $vars["size"] = $file->getSize();
      $vars["type"] = $file->getMimeType();
  }
}


Product Page Uploads and Automatic Updates

You probably will have to alter the 'ubercart product-content type' and add some taxonomy fields to create the categories (electronics etc.). (Not sure if ubercart has this by default.)

Then you will have to use a view to override the ubercart product page. Look into views and Contextual filters. You can for instance create a block (user-product-block) and use a contextual filter to fill this. You can choose to get the user id from url and then select all products created by that user.

Filtering by category is exactly as done on the page above.


What Drupal development environments are available besides XAMPP?

I think it's best if your local development environment matches the environment of the servers your site(s) are actually hosted on as much as possible.  I've used XAMPP with Drupal and I haven't ever had problems relating to extra libraries being loaded.

That said, if you're looking for a Drupal-optimized solution, Acquia, the company run by the founder of Drupal, provides a Dev Desktop which allows you to set up and host Drupal quickly on Windows or OS X.  This works similarly to XAMPP but it's easier to set up.  (Warning: Acquia's Drupal distribution is slightly different than the standard Drupal from drupal.org.  However, you can easily replace the Acquia Drupal distribution with the one from drupal.org if you want.)

For a different approach, you can try Drupal Quickstart, which is a Virtualbox VM that includes an install of Ubuntu Linux pre-configured with (as per the project page):

  Support for Drupal 7 and Drupal 6
  Ubuntu Linux, Apache, MySQL, APC, XDebug, IMAP, UploadProgress
  Firefox (with developer plugins) and Chrome
  Drush, drush make, and custom drush commands
  Install scripts for: Apache Solr, Aegir, Hudson, and Oracle
  Netbeans and Eclipse, configured with XDebug
  XHProf and Webgrind profilers. Emails logged as files
  cvs, subversion, git, bazaar

This is the "whole development environment in a box" solution.


Is "settings" needed in hook_field_widget_info()?

If the hooks your module implements don't set that array index, the function invoking them will set them to an empty array. See _field_info_collate_types().

  foreach (module_implements('field_widget_info') as $module) {
    $widget_types = (array) module_invoke($module, 'field_widget_info');
    foreach ($widget_types as $name => $widget_info) {
      // Provide defaults.
      $widget_info += array(
        'settings' => array(),
      );
      $info['widget types'][$name] = $widget_info;
      $info['widget types'][$name]['module'] = $module;
    }
  }

  foreach (module_implements('field_formatter_info') as $module) {
    $formatter_types = (array) module_invoke($module, 'field_formatter_info');
    foreach ($formatter_types as $name => $formatter_info) {
      // Provide defaults.
      $formatter_info += array(
        'settings' => array(),
      );
      $info['formatter types'][$name] = $formatter_info;
      $info['formatter types'][$name]['module'] = $module;
    }
  }

It is then up to the module implementing those hooks, and any related one, to correctly handle the values for that array index, even in the case another module changes it to a value the module is not expecting.


Im not sure what your error is. Every field has different widget settings and differing options ... keeping all the options you can set straight in my head is beyond me ... I have created fields in install profiles and using hook_install.  I tend to build the fields using the Field UI found at Structure -> Content Type -> then add/edit Fields then export those settings to code for use in a module.

I found this blog post immensely helpful:

Exporting and creating field definitions in Drupal 7

From the blog post you can get a field and its instance config with:

$field_data = field_info_field('field_article_image');
$instance_data = field_info_instance('node', 'field_article_image', 'article');

You can create a field and instance(s) in PHP using the Field API:

field_create_field($field_data);
field_create_instance($instance_data);

You can use Devel or Drush with drush php-script or eval and the following code nabbed from the blog post. It will generate the above 2 lines of code with the $config and $instance data all filled out for you to use in your custom code:

$entity_type = '';
$field_name = 'field_';
$bundle_name = '';

$info_config = field_info_field($field_name);
$info_instance = field_info_instance($entity_type, $field_name, $bundle_name);
unset($info_config['id']);
unset($info_instance['id'], $info_instance['field_id']);
include_once DRUPAL_ROOT . '/includes/utility.inc';
$output = "field_create_field(" . drupal_var_export($info_config) . ");\n";
$output .= "field_create_instance(" . drupal_var_export($info_instance) . ");";
drupal_set_message("<textarea rows=30 style=\"width: 100%;\">". $output .'</textarea>');

EDIT:

Once you see a valid export from an example field you are trying to create. It can be easy to re-use, tweak, or fix small parts of that field configuration to use in the same project or other projects. But I never sit down from scratch and try to code it all by hand for every field.


Can I call two callback function in one ajax call?

You can't do that directly. Instead, use a function that calls the two other functions.

'#ajax' => array(

  'callback' => 'my_callbacks_wrapper',
)
...

Then:

my_callbacks_wrapper($form, $form_state) {

  $first_callback_processed_form = first_callback($form, $form_state);

  $second_callback_processed_form = second_callback($first_callback_processed_form, $form_state);

  return $second_callback_processed_form;

}

Make sure your callbacks don't interfere.


Two Login Forms for the Site in Drupal 7

If you are talking about a single account that everyone who uses the site will use, the security implications are horrible. In the context of a business site, what happens if an employee is terminated. Does everyone have to learn a new password. What about the case of one disgruntled user who does something malicious? Do you want to have to track responsibility by back-tracing an IP address? There are so many reasons not to implement this requirement.

Drupal looks up password by user (user name or unique email) and being able to attribute site changes to an individual user, and to control access by individual user is extremely important with most sites. To deviate from the tried and true method will require a custom module, and I seriously doubt it is a good idea simply to alter the user experience.


Views with both menu and jump menu taxonomy terms as contextual filters

I'm editing my response based on your latest comment!

============================================================

One way I think you can do what you're trying to do is incorporate facets into your page with those specific taxonomy terms placed on the page as facets.

You'd need to use the Facet API module and the Faceted Navigation for Search module.  You can see the module page for an example interface - do you see how the screenshot on the module page shows a site where you can narrow the results based on fields/facets on the side?  I'm adding a screenshot from a site of my own that I've set up to use facets, though it's themed very differently.  The other great thing about facets is that they show you how many nodes you have tagged with the fields/terms you want to filter on.

Essentially, what facets do is give you the ability to FILTER/narrow listings based on select-type fields or taxonomy terms.  You can combine these filters, just as you describe.

I've only used the facet api with solr search, not core drupal, so I don't know if I can help you much on the exact setup, but perhaps this can at least guide you into another potential way to achieve your goal (if it's not overkill to learn all about facets and how you may be able to do this through search).

Let us know how it works out or if you figure it out!


unblock ip address after failed login attempts?

I presume you are using Drupal 7. Did you check the {blocked_ips} table?


I'd say go ahead - your plan to remove the Title from the page template and print it instead in the node template makes sense to me. I've done similar things in the past.

One thing you may want to look into is creating a custom page template for your content types, in addition to your node templates. This will give you even more control over your final rendered page on a per-content-type basis. This could help you avoid inadvertently removing the title from other pages, eg. your Front page.

Here's a quick function you can add to your theme's template.php file that will get Drupal to look for a custom page template (eg. *page_node_yourcontenttype* for each content type.

/**
* Tell Drupal 7 to look for a custom page template for each node type.
*/
function YOUR_THEME_NAME_preprocess_page(&$vars, $hook) {
    if (isset($vars['node'])) {
        $suggest = "page__node__{$vars['node']->type}";
        $vars['theme_hook_suggestions'][] = $suggest;
    }
}

Please note that I didn't write this particular snippet, but I have done the exact same thing successfully. Check out http://leepowers.net/drupal-node-custom-content-type-page-template (not my site) for the original snippet with a nice explanation.

Hope that helps!


Just pass html => TRUE as an option:

$options = array('html' => TRUE);
l('Visit Website &raquo;', 'http://' . $site->purl_prefix . '.' . $base, $options);

From the docs:

  'html' (default FALSE): Whether $text is HTML or just plain-text. For example, to make an image tag into a link, this must be set to TRUE, or you will see the escaped HTML image tag. $text is not sanitized if 'html' is TRUE. The calling function must ensure that $text is already safe.


Should be just (whatever your drupal directory)/blog, if it's installed in root directory, then it would look like http://www.example.com/blog, if the blog you created is different from the system default one, it would be http://www.example.com/your_blog_machine_name


Why can't I call theme functions declared in template.php in mymodule_nodeapi hook?

Functions defined inside of template.php will not reliably be available (nor are they meant to be) outside of the theme. When it comes to overriding preexisting theme functions, the overrides created within template.php will automatically be applied by Drupal core, there is no reason to actually invoke the function.

For example, if you wanted to override the functionality of theme_menu(), and you created in your theme's template.php a function named mytheme_menu(), that new function will not actually be invoked anywhere within the site's code. The function that is invoked will still be theme_menu() and Drupal core will automatically override that invocation with the functionality within mytheme_menu(). This is the intended use of the template.php file; to override existing themable output, not to create new theme functions.

Now, if you create a custom element and need to create a brand new theme function for that custom element, this function must be declared within the context of a custom module. For example, you would need to define the function theme_myelement() inside of mymodule.module. You will also need to implement hook_theme() by defining the function mymodule_theme() in order to tell the Drupal theme system about your new function. There's a bit more to it, which is explained in the Drupal module developer's handbook for Drupal 6 and Drupal 7.

If this doesn't answer your question, please edit your question to provide specific details about your custom module and custom theme functions.


"Error: Undefined class constant 'Symfony\Component\DependencyInjection\ContainerInterface::SCOPE_CONTAINER'"

The problem is exactly that you executed composer update twice, in two different directories. You don't execute it from the core directory, but only from the directory containing the core directory. In fact, the composer.json file you find in the directory where you decompressed the Drupal archive contains the following lines.

    "merge-plugin": {
        "include": [
            "core/composer.json",
        ],
        "recurse": false,
        "replace": false,
        "merge-extra": false
    }

The include part is telling to Composer to include the core/composer.json file too when updating. Supposing that mysite is the directory containing the core directory and the other Drupal files, it is enough you execute the following commands to get in mysite/vendor all the dependencies necessary.

cd mysite
composer update

In my case, I get the following output. (It may change, basing on how often you execute those commands.)

  Loading composer repositories with package information
  Updating dependencies (including require-dev)
     Removing symfony/polyfill-iconv (v1.1.1)
     Installing symfony/polyfill-iconv (v1.2.0)
       Downloading: 100%

  Drupal\Core\Composer\Composer::vendorTestCodeCleanup
    Removing symfony/polyfill-mbstring (v1.1.1)
    Installing symfony/polyfill-mbstring (v1.2.0)
      Downloading: 100%

  Drupal\Core\Composer\Composer::vendorTestCodeCleanup
    Removing symfony/polyfill-php54 (v1.1.1)
    Installing symfony/polyfill-php54 (v1.2.0)
      Downloading: 100%

  Drupal\Core\Composer\Composer::vendorTestCodeCleanup
    Removing symfony/polyfill-php55 (v1.1.1)
    Installing symfony/polyfill-php55 (v1.2.0)
      Downloading: 100%

  Drupal\Core\Composer\Composer::vendorTestCodeCleanup
    Removing guzzlehttp/promises (1.1.0)
    Installing guzzlehttp/promises (1.2.0)
      Downloading: 100%

  Drupal\Core\Composer\Composer::vendorTestCodeCleanup
    Removing symfony/polyfill-apcu (v1.1.1)
    Installing symfony/polyfill-apcu (v1.2.0)
      Downloading: 100%

  Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  Writing lock file
  Generating autoload files
   Drupal\Core\Composer\Composer::preAutoloadDump
   Drupal\Core\Composer\Composer::ensureHtaccess

Both Drupal 8 and Drush work for me.

drush status

  Drupal version                  :  8.1.1
  Site URI                        :  http://default
  Database driver                 :  mysql
  Database hostname               :  localhost
  Database port                   :
  Database username               :  database_username
  Database name                   :  database_name
  Drupal bootstrap                :  Successful
  Drupal user                     :
  Default theme                   :  bartik
  Administration theme            :  seven
  PHP configuration               :  /etc/php.ini
  PHP OS                          :  Darwin
  Drush script                    :  /usr/local/bin/drush
  Drush version                   :  8.0.5
  Drush temp directory            :  /tmp
  Drush configuration             :
  Drush alias files               :
  Install profile                 :  standard
  Drupal root                     :  /Library/Server/Web/Data/Sites/mysite
  Drupal Settings File            :  sites/default/settings.php
  Site path                       :  sites/default
  File directory path             :  sites/default/files
  Temporary file directory path   :  /tmp
  Sync config path                : sites/default/files/config_WZrobbGFfHIWBRmKDknFVfKgdyG1gKNFLBYcpBlbTZtEarG_rPEixLJFW6faE9yNFTjdkieQbA/sync

As side note, if you need to include the composer.json files modules could have, you can edit the mysite/composer.json file to contain the following lines.

    "merge-plugin": {
        "include": [
            "core/composer.json",
            "modules/*/composer.json"
        ],
        "recurse": false,
        "replace": false,
        "merge-extra": false
    }

Alternatively, you can use the Composer Manager module. I would suggest installing it, if you need to include any dependecy modules could have.


Drupal add arguments to page classes to make it possible to theme the page depending on the current page type (e.g. node, admin, user, etc.) as well as more specific data like node-12 or node-edit.


After searching for a while, I have found some kind of workaround solution for this here: https://stackoverflow.com/a/38268567/2267244

I have tested it and it works, here is bit modified version which I have used.

Also I'm not sure if we should mark this question as dpulicate as I found the solution on stackoverflow.com.

Anyway Here is how your form field should looke like:

$form['image_with_preview'] = [
  '#type' => 'managed_file',
  '#title' => t('Image with preview'),
  '#upload_validators' => [
    'file_validate_extensions' => ['gif png jpg jpeg'],
    'file_validate_size' => [25600000],
  ],
  '#theme' => 'image_widget',
  '#preview_image_style' => 'medium',
  '#upload_location' => 'public://',
  '#required' => FALSE,
];

And also you will need to implement hook_preprocess_HOOK in your module like this:

function YOUR_MODULE_preprocess_image_widget(&$variables) {
    $element = $variables['element'];

    $variables['attributes'] = array('class' => array('image-widget', 'js-form-managed-file', 'form-managed-file', 'clearfix'));

    if (!empty($element['fids']['#value'])) {
      $file = reset($element['#files']);
      $element['file_' . $file->id()]['filename']['#suffix'] = ' (' . format_size($file->getSize()) . ') ';
      $file_variables = array(
        'style_name' => $element['#preview_image_style'],
        'uri' => $file->getFileUri(),
      );

      // Determine image dimensions.
      if (isset($element['#value']['width']) && isset($element['#value']['height'])) {
        $file_variables['width'] = $element['#value']['width'];
        $file_variables['height'] = $element['#value']['height'];
      } else {
        $image = \Drupal::service('image.factory')->get($file->getFileUri());
        if ($image->isValid()) {
          $file_variables['width'] = $image->getWidth();
          $file_variables['height'] = $image->getHeight();
        }
        else {
          $file_variables['width'] = $file_variables['height'] = NULL;
        }
      }

      $element['preview'] = array(
        '#weight' => -10,
        '#theme' => 'image_style',
        '#width' => $file_variables['width'],
        '#height' => $file_variables['height'],
        '#style_name' => $file_variables['style_name'],
        '#uri' => $file_variables['uri'],
      );

      // Store the dimensions in the form so the file doesn't have to be
      // accessed again. This is important for remote files.
      $element['width'] = array(
        '#type' => 'hidden',
        '#value' => $file_variables['width'],
      );
      $element['height'] = array(
        '#type' => 'hidden',
        '#value' => $file_variables['height'],
      );
    }

    $variables['data'] = array();
    foreach (\Drupal\Core\Render\Element::children($element) as $child) {
      $variables['data'][$child] = $element[$child];
    }
}

I have tested it on my local Drupal instance and it works fine, image preview was displayed after AJAX upload finished.


meta tags don't display when not authenticated

You have a patch for this issue. There is a README.txt file updated.

All you need to do is to render meta tags in your page--front.tpl.php, add following in this file of your theme:

<?php
 render($page['content']['metatags']);
?>

Or you can try to add this in your template.php file of the theme:

<?php
function THEMENAME_preprocess_page(&$vars) {
  if (!empty($vars['is_front'])) {
    metatag_page_build($vars['page']);
  }
}
?>

Just replace THEMENAME with the name of your theme.


How can i add text custom field on product detail page?

The uc_attributes module, which has been part of Ubercart for 12 years, was specifically designed to handle this situation.

Enable the uc_attributes module. Edit your product, then go to the "Attributes" tab and add a "textfield" type attribute to your product. Your customer will then be able to add text to the purchased product. This textfield will be displayed in the cart, on the checkout page, on the review order page, and in the admin/user view of the completed order.

In short, the correct way to do this is to "Use Attributes and set up a Textfield attribute on your product" as I stated in my previous answer (which was erroneously turned into a "comment" by some unknown user).

The Ubercart project page at https://www.drupal.org/project/ubercart gives links to detailed information about how to do this. Specifically, see:
https://www.drupal.org/docs/7/modules/ubercart/all-about-products/product-attributes-and-options
and the video tutorial at https://www.youtube.com/watch?v=fVDOqI7Gge4


Updating module using _update_n not appearing on update.php or in /modules/update

Rename cloudinary_update_7200 to cloudinary_update_7100 in case if you are using 7.1 version (refer to hook_update_N) and try once again.
If it doesn't work perform SQL query to figure out the number of the latest performed update  of the module:

SELECT schema_version FROM system WHERE type = 'module' AND name = 'cloudinary';

If it is 0 - 7100 should work, if it is for instance 7101 - try cloudinary_update_7102.


User passwords are stored using a one-way hashing algorithm and cannot be converted to plaintext.  In addition, each Drupal site uses a unique cryptographic salt, so that the same plaintext password on two Drupal sites will not result in the same hashed password.

In other words, there is no way to generate a list of usernames and plaintext passwords.


JSON:API resources error: "This resource attempted to serve data that contains unsupported resource types."

This error is the result of not setting the _jsonapi_resource correctly in the routing file:
MYMODULE.routing.yml
# Defines a route where a user's flaggings can be found.
MYMODULE.user_flaggings:
  # %jsonapi% is a placeholder for the JSON:API base path, which can be
  # configured in a site's services.yml file.
  path: '/%jsonapi%/MYMODULE/queue'
  defaults:
    # Every JSON:API resource route must declare a _jsonapi_resource. The
    # value can either be a class or a service ID. Unlike the _controller
    # route default, it is not possible to declare a method name to be called.
    _jsonapi_resource: Drupal\MYMODULE\Resource\MyQueue
    _jsonapi_resource_types: ['node--page', 'flagging--MY_FLAGGING_TYPE']


How do I retrieve values of a taxonomy field inside a field collection of a profile2 node?

You could try using entity_metadata_wrapper to load the profile2 entity.

You could then drill down to the field value on the field_collection.

Something like:

$profile = profile2_load_by_user($account, 'main');
// Use entity metadata wrapper, because it's awesome.
$profile_wrapper = entity_metadata_wrapper('profile2', $profile);
// We can access the term as the "value" of the field_collection child field
$term = $profile_wrapper->get('field_my_field_collection')->field_my_taxonomy_term->value();
// Just print out the term for now
drupal_set_message('<pre>'.var_export($term,1).'</pre>');


How to deal with login attempts coming from 1-127.0.01 and what does it means?

After attempt five login drupal block account automatically

Install the Flood module flood_control
Enable the Flood module
Go to admin/settings/system/Flood control
Change the "Failed login (username) window" from 6 hours to None
Save

Flood Control

  This project is intended to add an administration interface for hidden
  flood control variables in Drupal 7, like the login attempt limiters
  and any future hidden variables.

Flood Unblock

  This module makes it possible for site administrators to remove
  ip-adresses from the flood table, or to remove all ip-adresses from
  the table depending on the event type.

Different ways to reset Drupal admin password

Protect site from flooding when user login is attacked...


What are best practices for Drupal 7 my.conf settings?

You need to profile this yourself, every server is different - there's not really any such thing as 'best practice' here; get mysqltuner up and running, and follow the recommendations.

Don't try to think of it in terms of Drupal, rather in terms of any web application which needs optimising. If you get too hung up on the 'Drupal' aspect you'll end up looking in the wrong places to optimise


Drupal has a service for serialisation, pre-configured with the normalisers and encoders you need. The error you currently have is because you're not setting up the instance of the serialiser with the Symfony\Component\Serializer\Encoder\JsonEncoder, but you'll also need, for example, the Drupal\serialization\Normalizer\ConfigEntityNormalizer normaliser.

This code works well for me:

$serializer = \Drupal::service('serializer');
$node = \Drupal::entityTypeManager()->getStorage('node')->load(1);

$output = $serializer->serialize($node, 'json');
$deserialized_node = $serializer->deserialize($output, \Drupal\node\Entity\Node::class, 'json');

As always, inject the services if possible.


How to Programmatically add javascript dynamically from a custom module to modify a popup calendar property

You can attach a script to a form using the form's #attached attribute. You can do this in hook_form_alter as follows:

function hook_form_alter(&$form, &$form_state, $form_id)
{
  if($form_id == 'targeted_form')
  {
    $form['#attached']['js'][] = array
    (
      'type' => 'file',
      'data' => drupal_get_path('module', 'my_module') . '/scripts.js',
    );
  }
}

If you need to pass values from PHP to the form, you can attach values using Drupal.settings:

function hook_form_alter(&$form, &$form_state, $form_id)
{
  if($form_id == 'targeted_form')
  {
    $form['#attached']['js'][] = array
    (
      'type' => 'setting',
      'data' => array('myModule' => array('someSetting' => 'some value')),
    );
  }
}

Now the value will be available in your form at:

Drupal.settings.myModule.someSetting

Combine these two techniques to attach a form and pass it some settings.


How can I alter the HTML output of a specific content-type in display mode via a module, without creating the node type in a module?

IMO, a very good approach would be using Display Suite to generate the basic markup/layout and then add the appropriate styling to the theme.


FAPI initial checked state for #type => radio

I may be totally remembering this wrong,  but I'm pretty sure you want to add "checked" as an attribute.
attributes => array("checked")


How to create a views that display all the publish content type as one output per user

I finally did that with Relation module. I was assuming I don't need that because there is a relation between the two content type, the author is the same for the two node, but I was not able to combine the two node in one.

My solution Relation Module to combine the two node. I created a relation between the project and the project images node. In views I created a content type view with the field I need from the project type than I add the relation : Relation(node <-> node) add I add the field "Image(from Projet Image)" to display the image and Bingo I have one view output for two different node.

To make the relation automatic I created a Rules with Rules module. I fire the rule when a Projet is added or a Projet Image is added than I create the relation.

A quick help for rules 5 actions step
1st action : create a variable / create a list
2st action : fetch entity by property / node / Author
3rd action : place the fetch result in the list created at step 1 (you may have to create a lot) personally because the node hare limit to 1 per content type per user I just repeats the step 3 two time
4ft action : create a entity / relation / with the list created at step 1.

Those step have to be improve because those are my first step with Rules and I rules are not strong at all.

Hope it help someone.


When creating a page view using views, it gives you the ability to assign a menu for that page, in this situation you can define all views with same parent path like parent/view1 , parent/view2, then in middle box when adding menu item you can select views as menu tab entry while default menu tab can be assigned for the view you want to be shown when navigating to parent path.


How to create dynamic select list in form using FAPI

You need to use the #ajax property in your State select list, with a callback function that returns the district element.  So something like this:

$form['state'] = array(
  '#title' => t('Name of your State:') ,
  '#type' => 'select',
  '#default_value' => array(
   ),
  '#options' => $options,
  '#required' => '1',
  '#ajax' => array(
    'callback' => 'MY_MODULE_state_ajax_callback',
    'wrapper' => 'edit-district',
 );

then create a callback called MY_MODULE_state_ajax_callback($form, &$form_state)
and within the function,

MY_MODULE_state_ajax_callback($form, &$form_state) {
    $form_state['rebuild'] = TRUE;
    return $form['district'];
}

It may be slightly more complicated than this, based on your use-case, but this is the meat of it.


I think that you need make an authenticated request, unless you want any user to create nodes.
I have created nodes before using curl. You need enable the "Session authentication", activate the user login action in the resources section of you service, and enable request "application/x-www-form-urlencoded" in the server section.

This is the code

    $base_url = 'http://localhost/endpoint';
    $params = http_build_query(array(
       'username' => 'admin',
       'password' => 'qwerty',
    ));
    // set up the request
    $curl = curl_init($base_url . '/user/login.json');
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
    // make the request
    $response = curl_exec($curl);
    curl_close($curl);
    $user_data = json_decode($response);
    // login successful
    if (isset($user_data->sessid)) {
      $node_params = http_build_query(array(
        'type' => 'page',
        'title' => 'Test page',
      ));
      // set up the authenticated request
      $curl_node = curl_init($base_url . '/node.json');
      curl_setopt($curl_node, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($curl_node, CURLOPT_POST, true);
      curl_setopt($curl_node, CURLOPT_POSTFIELDS, $node_params);
      curl_setopt($curl_node, CURLOPT_COOKIE, $user_data->session_name . '=' . $user_data->sessid);
      // make the authenticated request
      $node_response = curl_exec($curl_node);
      curl_close($curl_node);
      var_dump(json_decode($node_response));
    }


Displaying Taxonomy Term Field for Multiple Entries on a Taxonomy Term List View

You are going to have to adjust this to your own use case, but the approach I would use is a little different.

First, delete the relationship.

Add (or configure) the term reference field (field_divisions?) in your query. Set it to no label, and exclude from display. Rewrite the output to [field_tags-tid] . This will give you a list of term id's.

Install and enable the Views PHP module.

EDIT:

The $row variable does not play well with multiple values, so we will switch to the $data variable.

In your view, add a Global:PHP field, and in the Output code box enter something like:

<?php
  // Select your field object.
  $obj = $data->_field_data;
  // Then get your field array
  $divisions = $obj->field_divisions[LANGUAGE_NONE]
  foreach($divisions as $division) {
    if ( is_numeric( $division['tid'] ) ) {
      $term = taxonomy_term_load($division['tid']);
      $icons= $icons. "
";

      if (isset($term->division_icon['und'][0]['uri'] )) {
        $icons= $icons. "
division_icon['und'][0]['uri']) . "' class='term-image' />
 ";
      }
      $icons = $icons . "
";
    }
  }
  print $icons;
?>

Make sure the PHP field follows the term reference field so the $row values are available to the PHP field. Then style your icons to display as you wish.


When making a new core release, how do mantainers tag the core modules and update their info files?

Yes, it is an automated process, check below:

  The version string will be added by drupal.org when a release is
  created and a tarball packaged. However, if your module is not being
  hosted on the drupal.org infrastructure, you can give your module
  whatever version string makes sense (eg. see Release naming
  conventions).

NOTE: The above description is exact copy paste from Drupal.org link.


Thanks all

I found the solution as that comment form-plural in po

Edited on of the po files after exporting the last state to keep translation.

Import the file using drush (uploading from the interface always fail)

Installed drush_lang module

Apply that patch langimp relative path in /home/$_USER/.drush/drush_language

Clear cache for drupal and drush (drush cache-clear drush)

use the commands that module provides and every thing will be fine


The problem was about a relative path in the file:

  web/sites/default/settings.php

$config_directories['sync'] = 'web/profiles/DISTRIBUTION_NAME/config/install';


In Drupal Commerce - Rules configuration. What is the default operator in the conditions section?

AND

And here's some filler text to get me over the 30 character minimum.


How do I set a Node's Paragraph field in a different language programmatically?

The paragraphs ERR field only contains one (pertinent) bit of info - the relationship to the paragraph entity. The field itself shouldn't be translated, because every time you set it, you're setting the paragraph for every translation of that node.
To provide translations, you translate the paragraph entity itself, e.g.
$node->field_images_descriptions->entity
  ->addTranslation($lang_code, [
    'field_product_image' => $img[$key],
    'field_product_description' => $desc[$key],
  ])
  ->save();


Mostly .htaccess is hidden While viewing cpanel click to show hidden files also, Else download .htaccess file and put it on root directory


Why does "Cancel People Account" not work?

I can confirm your suggestion what it actually should be like and that actually exactly that should happen what you expect. After canceling an account you will be provided with further steps about the users written content etc. and finally you will become a progress bar showing the deletion or re-assigning of the written content of this user and the final confirmation about the success of it all.

The misbehaviour what you describe can be caused by several issues I only can list here for your research:

there is a mod_rewrite issue sometimes if the server is not set up correctly but this would actually also come up by many other tasks
is your admin account clean and has never been modified? The user 0 is something special in Drupal world and can sometimes be corrupted by some changes on it
you mentioned a local installation. Does has your DB user which is connected to the DB management of your Drupal installation, the right to DELETE in the mysql database?
and as mentioned by Molot also the redirecting via overlay or any other modal frameworks and jquery can be the issue, often fixed by using jquery_update module and playing around with jquery versions in the settings of the module.
Also, any PHP cache or similar can cause freezing batch processes or overwrite the use of pecl progressbar (default in Drupal)
Did you tried different users or only one? Or is this user you try to delete a spam account? They also can cause issues since they are not really registered but somehow signed up. This would be another story ...

Sorry, just some ideas...


I hate to answer my own question, but all you have to do is enable the "Contextual links" module. This is a Drupal core module, and it can be enabled here:

admin/modules

Or with Drush via:

drush en contextual

This module is automatically enabled with a "Standard" Drupal installation, but if you use a "Minimal" installation this module will not be enabled.


Drush command to show installed modules but not being used?

Drush has no way of knowing if a module might have some hook that is performing an active service for the site, even in the absence of any configuration information, so no, this feature is not available.


Drupal 7: hook_menu not working correctly

Try this:

function page_arg_menu() {
  $items = array();

  $items['flashcards'] = array(
    'title' => 'Flashcards',
    'page callback' => 'page_arg_callback',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function page_arg_callback() {
  // Do stuff
  return theme('page_arg');
}

function page_arg_theme($existing, $type, $theme, $path) {
  return array(
    'page_arg' => array(
      'template' => 'page-arg',
      'path' => drupal_get_path('module', 'page_arg') . '/theme/templates',
    ),
  );
}

Create a file page-arg.tpl.php and put it in /theme/templates in your module (page_arg) directory.


Modules to create submenu with custom markup

Check Out these two modules..: TB Mega Menu and Nice Menus

Here is a post which lists some of them  Mega Menu modules for Drupal


'TwitterException' with message 'Not Found'

This looks like it is failing in a portion of the code that has to do with authorization. Just starting with the simplest explanation, are you sure that your credentials/oauth settings are correct?


Show item as local task but hide if argument is not provided

I solve this by argument load function, but I don't think it is correct to do like this.

// Menu item change
//....
'system-log/%ebanq_custom_log_id/view' => array(
//....

/**
 * Implements hook_load().
 */
function ebanq_custom_log_id_load($arg) {
    if (!is_numeric($arg)) {
        return FALSE;
    }
    return $arg;
}


Join User Profile fields with custom View type

Views itself makes a join to the uid, so if you add the Users uid as a relationship, you should be able to get the profile fields as well.

Alternatively you could join the profile field table yourself.

For reference this is how Views makes the profile -> user join:

$data['profile_values']['table']['group']  = t('Profile');

$data['profile_values']['table']['join'] = array(
  // The node table
  'node' => array(
    'left_table' => 'profile_values',
    'left_field' => 'uid',
    'field' => 'uid',
  ),
  // The users table
  'users' => array(
    'left_table' => 'profile_values',
    'left_field' => 'uid',
    'field' => 'uid',
  ),
);


How to add phone number field with extension to webform component

You could add a phone field as you described for the phone number.

And add another field of type number for the phone extension, you can limit this field to be only numeric and 4 digits.

And even to make sure that the phone number is introduced and not only the 'phone extension', you can add a Webform conditional to display the 'phone extension' field only if the 'phone' field has been filled.


Cant display dropdown values on drupal commerce review page

You could use

hook_commerce_checkout_pane_info_alter

and set a different 'review' callback for the relevant checkout pane.

You can then control the output from your review callback.

See hook_commerce_checkout_pane_info for the option detail there.

You could also try theming the review page with

THEME_NAME_preprocess_commerce_checkout_review(&$variables) {} or
THEME_NAME_commerce_checkout_review(&$variables) {}


How to email all group members after a new node is added when using the Group module?

Only using the Groups module
The Group module is an upcoming alternative for the Organic Groups module for D7, for which right now there is only a beta version available.
Remark: the Groups, Communities and Co module (= GCC) is yet another alternative (with an official release for D7).
The Group module appears to be an interesting alternative, though it doesn't come with a lot (if any) documentation so far.
The best docu available, I think, is to read its sources. In doing so, I learned that its Group Invite submodule "Allows group members to invite people into their group", which will trigger appropriate eMails. Of course, that implies that the user who wants to send these invites, is already a group member. But this "function" is not really what you seem to be looking for (as per your additional comment to my answer here).
Instead, you want to "Send an email to group members of particular group when a new node is created". To do so, I'd narrow down your question to 3 sub-questions (= tasks), and try to implement this using the Rules module, as further detailed below ...
Also using the Rules module
Rules Event
That's easy, more or less out-of-the-Rule-box: When a new node is created.
Rules Condition
This is your Challenge 1: Only if "Node type of the created node belongs to some group".
Rules Action
Create a Rules "component" to send an eMail (anybody can do that, right?). Here is a typical sample of such component (in Rules export format, just import it in your own environment via copy-paste):
{ "rules_send_email_notification" : {
    "LABEL" : "Send eMail notification",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "user_to_notify" : { "label" : "User to be notified", "type" : "user" } },
    "ACTION SET" : [
      { "mail" : {
          "to" : [ "user-to-notify:mail" ],
          "subject" : "New node was added",
          "message" : "New node was added for content type ...",
          "from" : "[site:mail]",
          "language" : [ "" ]
        }
      }
    ]
  }
}

Obviously, the Subject and Content of the eMail may need review / tuning, while you might also want to use some other From eMail ID.
This is your Challenge 2:  construct the "To" content of such eMail, i.e. all eMail IDs of all members of the group. That is what the value should be for user-to-notify:mail in the Rules component shown above.
Write your custom Rule(s)
To address the above Challenges 1 and 2, you could write your custom module, in which you basically would do 2 things:

Take advantage of the very well documented API provided by the Group module.
Write your own custom Rules, similar to what's explained in the great tutorial Drupal custom Rules how to write your own events conditions, actions and custom object (+ custom tokens).

If you're looking for more Rules related coding samples, you may want to look at the Rules URL Argument module. Here is a quote about it (from its project page, bold markup added here):

... provides two rules conditions based on URL arguments:

check if a URL argument is present.
compare the value of an URL argument.

It also provides an action that makes the value of an URL argument available as new variable to Rules.

The newly provided Rules actions and conditions can be found under the "URL Argument" conditions and actions groups in the rule configuration interface.
For an example of how to use it, refer to Comment # 3 in issue # 1686360 which is about "Pass an amount to the url, ie; site/content/node-title?amount=10 or /node-title?=amount:10".


contextual and downward filterable tagcloud

What I think you are saying you want to do is this:

Grab all content that is tagged with a certain term, then
List in a block all taxonomy terms from that content

And if so, it's pretty straightforward to loop through a list of node and aggregate and each taxonomy term that is attached to each node, and then stylize a block of those terms, eg,

$nids= // execution results of a view or other sql that filters on a term;

$found=array();
foreach ($nids as $nid) {
   $node=node_load($nid);
   foreach ($node->taxonomy as $t) {
      found[$t->tid]=$t->name;
   }
}

which will (if my off the top of the cuff php code is accurate ;-) produce an array $found that is a list of terms that can be styled however you wanted in a variable or block, most simply like:

 foreach ($found as $tid => $name) {
    $content.=l($name,'taxonomy/term/' . $tid) . ' ';
 }
 return $content;

You can probably do all of this in a View itself with some funky templating, too, if you didn't want to create a module and/or theme preprocess function.


Display Suite: Panel layouts in doesn't appear in "Manage fields"

The Manage Fields tab is used for arranging fields for the Node Add/Edit form, as well as to Add/Edit/Remove fields to the Node/Entity.

If you want to use Panels for the layout of your Node Add/Edit forms, then you would do this through the Panels Interface by enabling and editing the Node add/edit form Panel that comes included when you install Panels. You would create variants in this Panel to handle the layouts for each content type you have. Hope that can help.


How do I use add the image field Product entity in to my view?

To show just a single image, you can add a filter to the view to restrict the product reference field to delta 0.


How to set a specific taxonomy with Rules during feeds import?

Solution

Rules

Before saving a node from xml feeds
Data comparision TRUE with rem id Fruit
Set data value -> node:field-taxonomy-type -> click on "Switch to direct mode input" and it will show the terms for that Vocabulary.


addClass in Twig with if statement in item-list.html.twig

I might be wrong here, as we do know know what problem you are having...

But {{ item.attributes.addClass('list-group-item') }} will add the list-group-item class to the item-element. (It does not print this class.)

Because of the surrounding code: {% if item.attributes.hasClass('facet-item') %} ... {% endif %}, I feel you want to add a class to the childs of item, not to item itself.

Why not output this instead?

{{item.value}}

So the condition becomes:

{% if item.attributes.hasClass('facet-item') %}

{{item.value}}

{% endif %}


How to use the Webform Serial in a Webform Rule?

Have a look at comment #2 in issue #2572067, which states this:

The correct token for that is [submission:serial], but some module is going to have to make that token available to the rules module. Webform itself doesn't do that. I haven't tried it, but the Webform Rules modules would be the place to start.
The serial number is a relatively new feature, but I would have though it would work without an update to the Webform Rules module. If not, you might file an issue in that module's queue.


How would we add Drupal Core modules as dependencies on custom modules post 8.6.2?

If you're referencing a recent change in a core module, it was a style/formatting change.

Adding namespaces for dependencies has been in core for a while. The {project}:{module} format is a better practice for removing ambiguity in the event of module/project machine name overlap, but both will work.

For documentation reference, see Let Drupal 8 know about your module with an .info.yml file under the example section for dependencies:

    dependencies - A list of other modules your module depends on. Dependencies should be namespaced in the format {project}:{module}, where {project} is the project name as it appears in the Drupal.org URL (e.g. drupal.org/project/views) and {module} is the module's machine name. Dependencies can also include version restrictions, for example webform:webform (>=8.x-5.x). Note that if your module has dependencies on other contributed modules or libraries, these should be declared in the module's composer.json file.


How do I move the "Login or Register to Post Comments" links?

The "Login or Register to Post Comments" link is created via:

theme('comment_post_forbidden', array('node' => $node));

so I'd create a variable with that in the appropriate preprocess hook that has  $node available.


You have to add a submit function if you dont have and set the url you want redirect in $form_state['redirect'].

function my_custom_form_submit($form, &$form_state) {
  $form_state['redirect'] = 'node/10';
}

More information here.


How can I turn off the caching for a Paragraph type?

Declare the dependency on the GET parameter with a cache context:
/mymodule/mymodule.module
function mymodule_preprocess_paragraph(&$variables) {

  $foo = \Drupal::request()->query->get('foo');
  $variables['content']['foo'] = [
    '#markup' => "foo = $foo",
    '#cache' => ['contexts' => ['url.query_args:foo']],
  ];
}

More info https://www.drupal.org/docs/drupal-apis/cache-api/cache-contexts
However, if you have more than a few possible values of foo this is a problem with cache performance, especially for nested entities like paragraphs. Each value creates a new cache entry for the paragraph and its parent entities.
To avoid this put a placeholder in the paragaph:
/mymodule/mymodule.module
function mymodule_preprocess_paragraph(&$variables) {

  $variables['content']['foo_placeholdered'] = [
    '#lazy_builder' => ['\Drupal\mymodule\MymoduleLazyBuilders::getFoo', []],
    '#create_placeholder' => TRUE,
  ];
}

and build the content which depends on the GET parameter in a lazy builder:
/mymodule/src/MymoduleLazyBuilders.php
<?php

namespace Drupal\mymodule;

use Drupal\Core\Render\Element\RenderCallbackInterface;

class MymoduleLazyBuilders implements RenderCallbackInterface {

  public static function getFoo() {
    $foo = \Drupal::request()->query->get('foo');
    return  [
      '#markup' => "foo = $foo",
      '#cache' => ['contexts' => ['url.query_args:foo']],
    ];
  }

}

For time consuming calculations such placeholders can be delivered through BigPipe. So if you enable this module you can also improve page speed.


How do I get that same invalidation goodness that different routes
  seem to have?

Cache contexts are not invalidated. If you set a cache context, you increase the number of variants cached. For example if you would make a custom cache context for the weekday and set this cache context on a block, you would get 7 variants of the block in the cache. If you don't set any other cache metadata they will remain in the cache and will never be invalidated or updated.

  I notice, in core's core.services.yml, the cache_context.route service
  depends on the current_route_match service, which links to
  CurrentRouteMatch.php and depends on the request_stack service. Which
  of these things is what causes Drupal to end up checking if the route
  has changed? I want to do this same thing for my custom cache context.

Injecting other services in your own service is not enough. You have to use the injected service.

As example this code from the cache_context.route service you've mentioned:

public function getContext() {
    return $this->routeMatch->getRouteName() . hash('sha256', serialize($this->routeMatch->getRawParameters()->all()));
  }

$this->routeMatch is the injected service current_route_match. You can see how the service is used to build the context from the route name and the hashed route parameters.

  Will I have to depend on some core service, or is there something I
  can put in either a service definition (in the module's services.yml)
  or the service class itself that says it wants to be updated?

You only have to inject other services, if you need them in your code. But this depends, on what you try to do with your custom cache context.


How do I show content in an iframe as a specific user?

The thing to keep in mind here is that an iframe runs on the client side. It is basically a browser within a browser. This also means that it will use an existing session if the client is logged in on the site (you already discovered this):

  When logged in with my regular user on that other site, the iframe was
  displayed for my regular user.

The problem is that Drupal runs server side. Theoretically you should be able to use drupal_http_request() to send the login data to the other site, catch the session cookie and initiate a session. But that would initiate a session on the server, not on the client. The same with cURL, it would log the server in, not the client. So the iframe for the client would still show the login button.

In order to do something client side, your only option is probably to use javascript and perform an POST the login data to the other site. This unfortunately means that the data to login (username and password) also will be sent to the client. A little tech savvy user will be able to compromise your account on the 3rd party site. (If he changes your password, it would break your own site)

  Can I trigger the pressing of the login button and then fill in the
  login form, or is it possible that that is not possible?

Unfortunately also no, browsers implement safety measures to prevent one site form interacting with another. You cannot use javascript (or CSS or anything else) to modify the site within the iframe.

For a second I thought you can try to start the session on the server and then send the session variables to the javascript to process client side. This will not expose your credentials but will still allow someone to take over your session.

So I will conclude with no. There is unfortunately no sensible way of doing this.

Finally there are 2 more things to keep into account;

Do the terms of use of the other site allow you to share an account with multiple users (you could get into a lot of trouble)
What if the client happens to already have an account on the site? You would override his session and he would be you. I would personally hate your site if it forced me to logout and in again on another website.


Trigger highlight in maparea when mouseover on link

An IT guy delivered the solution. Here the code

jQuery(document).ready(function() {
    jQuery('a[typeof].kisiler').each(function() {
        var txt = jQuery(this).text();
        var maps = jQuery('area[title="'+txt+'"]').attr('coords').split(',');

        maps[0]-= maps[2];
        maps[1]-= maps[2];
        maps[2] = maps[2]*2;

        jQuery(this).hover(function() {
            jQuery('.maphilighted').before('

');
        }, function() {
            jQuery('.tagbox'+maps[0]+maps[1]).fadeOut();
            setTimeout("jQuery('.tagbox"+maps[0]+maps[1]+"').remove();", 100);
        });

        console.log(txt, maps);
    });
})


Organizing uploaded files in folders created by date

You can use the Filefield Paths module to automatically rename uploaded files according to a scheme defined by tokens. The node creation date is one of the available tokens, so that module should be able to do what you want to achieve.


Unable to sort view based on search index by taxonomy weight

I'm not sure if you have figured this out yet, but I found the solution to this, so I'll post it here in case anyone else comes along this page.

If you go to your search index and go to the Fields tab, you'll see at the very bottom there is text that says "Add related fields". It took a while for me to see this there, since it's kind of inconspicuous and under the form submit button. But if you click that and select your taxonomy, it will add the set of taxonomy fields to the available list of fields to index. Check "Weight", then that will be available in your view.


How to configure the CONTEXTUAL FILTER in a View for Rules?

Make 2 rules-views on NODES, on both views add relationship to author, on first view only add one field UID using relationship and aggregation, filter your nodes as needed, this will display only one user for several nodes that matched your ‘delete criteria’. On second view add only one field NID (with no aggregation) and same filter criteria as first view, in this view add a contextual filter on UID. On both views set  row variable settings in middle column, make all fields and parameters as Data Type = Integer, do not send them as objects, it does not work well.
Now in your component or rule, first add your first view-loop (UIDs), fetch user by id using your UID variable, inside that loop, add your second view (NIDs), set contextual filter as your variable UID, loop all those nodes, fetch each node by id usig your NID variable, and do your stuff, outside second view loop, but inside first view loop send your email. On second view loop you can add node-content to a variable previously added to hold all node-data for that user and included in your email body.