Attaching custom JS to form

Adding css and javascript to a drupal 8 module

Here's an example of using hook_form_FORM_ID_alter. For this you'll need to make a custom module (conveniently named custommodule in the example below).

Module directory:

custommodule/
|- js/
   |-- custommodule.js
|-- custommodule.info.yml
|-- custommodule.libraries.yml
|-- custommodule.module

File contents:

custommodule.info.yml

type: module
name: Custommodule
description: 'Custom stuff'
package: Custom
core: '8.x'

custommodule.libraries.yml

custommodule:
  version: 1.x
  js:
    js/custommodule.js: {}
  dependencies:
    - core/jquery

custommodule.module

<?php

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_FORM_ID_alter().
 */
function custommodule_form_node_article_edit_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['#attached']['library'][] = 'custommodule/custommodule';
}

custommodule.js

(function($) {

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

      var num1 = $("#edit-field-num-1-0-value").value;
      var num2 = $("#edit-field-num-2-0-value").value;
      var result = (Number(num1)+Number(num2));
      $("#edit-field-num-3-0-value").value = result;
    }
  };

})(jQuery);

The example uses the default article node type, with 3 integer fields (field_num_1, field_num_2, field_num_3), and works on the article edit form (form id -> node_article_edit_form). The js part is also very basic so all it does is set the third field value once the page loads. Drupal_add_js is deprecated, so we use the $form['#attached']['library'] array to attach a library (defined in the custommodule.libraries.yml file) that contains the JS file (a single libraries.yml file can define more libraries, which can include more js/css files).


How to send e-mail in users selected languages

Cron runs as the anonymous user, so any emails sent by cron will use the site's default language.

Your code snippet has the following:

 $language = user_preferred_language();

This is wrong.  It will get the preferred language of the anonymous user, not the user you're sending the mail to.

Instead: figure out the recipient's preferred language:

$userobj = user_load($user);
$language = user_preferred_language($userobj);

Now, you can send mail with the correct language:

$result = drupal_mail($module, $key, $to, $language, $params, $from, $send);


How is drupal able to see a module even when I renamed it

Drupal stores information about where to find module files in the system and registry tables.  If you want to revert an update, you'll have to replace the updated version with the old version. If you ran database updates to update the module, you'll have to disable and uninstall it first, and then re-enable it after you've replaced the module files.

If you've removed the module without disabling it, the site should break. If it's still running with the updated module, there must be another copy of it somewhere.

If you want to know where drupal's reading the files from you can run the following SQL on the db:

SELECT filename FROM system WHERE name = 'mediabox';


Update same table using dynamic query in drupal 7

To execute clauses like that you would use a where funtion. so your code would be something like

$query = db_update('books','pb');
$query->fields($update_values);
$query->where("b.pdays * (36400) + b.ptime_from > 6546");
$isbn_reds = $query->execute();


Does the Context module check block visibility settings?

Context module ignores Block visibility settings

The Context module does not check (take into account) the "Block visibility settings". If you want that to be the case, then you need to also use the Context Respect module. Some details about this module, from its project page:

  Extends the Context module by making it respect default block settings.

  This makes it so you can retain your block visibility when assigning them into various Contexts. You can also 'Override' from the block level to ignore Context Respect.

Alternative to Context module

Have a look at the Rules block visibility module as a valid alternative. Refer to my answer to "How to stop a Views block from displaying to admins, such as user/1?" for more details about it.

By using this module as an alternative, you'd only have to create a Rules Component with Rules Conditions that could be identical to the "PHP code" as in your question. However, if you can, you should try to avoid such PHP code if you have other Rules Conditions available that could be used as an alternative to such PHP code.


Well, I got something up and running via hook_toolbar. Only thing left is, that you can't click directly on the "Language: EN" string in the toolbar. You have to click slightly next to it. Maybe you can fix this.

Apart from that, please also have a look at the Devel module and their implementation of hook_toolbar where they have an extra src/ToolbarHandler.php class for everything. You better should rebuild the code below into a dedicated handler.

use Drupal\Core\Url;
use Drupal\Core\Link;

/**
 * Implements hook_toolbar().
 */
function MYMODULE_toolbar() {

  // Get languages, get current route.
  $current_language = \Drupal::languageManager()->getCurrentLanguage()->getId();
  $languages = \Drupal::languageManager()->getLanguages();
  $route = \Drupal::service('path.matcher')
    ->isFrontPage() ? '<front>' : '<current>';

  // Get links.
  $links = [];
  foreach ($languages as $language) {
    $url = new Url($route, [], ['language' => $language]);
    $links[] = [
      '#markup' => Link::fromTextAndUrl($language->getName(), $url)
        ->toString(),
    ];
  }

  // Set cache.
  $items['admin_toolbar_langswitch'] = [
    '#cache' => [
      'contexts' => [
        'languages:language_interface',
        'url',
      ],
    ],
  ];

  // Build toolbar item and tray.
  $items['admin_toolbar_langswitch'] += [
    '#type'   => 'toolbar_item',
    '#weight' => 999,
    'tab'     => [
      '#type'       => 'html_tag',
      '#tag'        => 'div',
      '#value'      => '' . t('Language') . ': ' . strtoupper($current_language) . '',
      '#attributes' => [
        'class' => ['toolbar-item-admin-toolbar-langswitch'],
        'title' => t('Admin Toolbar Langswitch'),
      ],
    ],
    'tray'    => [
      '#heading' => t('Admin Toolbar Langswitch'),
      'content'  => [
        '#theme'      => 'item_list',
        '#items'      => $links,
        '#attributes' => [
          'class' => ['toolbar-menu'],
        ],
      ],
    ],
  ];

  return $items;
}


Something like the following should work:

drupal_render(drupal_get_form('uc_addresses_get_address_form'))

Check Render form in template


Module Dev: How to attach a button to a field?

This example comes close: Publishing to Facebook Wall. It shows how to post a facebook message when a node or comment form is submitted, and provide an option to opt-out on the node or comment form.


IMO $base_url in settings.php should work

Alternatively you can try

RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://example.com/$1 [R,L]

or

RewriteEngine On
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]


jQuery is not working for inserting data

I added 'async': false to the jQuery.ajax call as follows.

jQuery.ajax({
  url: 'postcomment',
  type: 'POST',
  dataType: 'json',
  'async': false,
  data: post,
  success: function(data) {
    alert(data);
  },
  error: function(jqXHR, textStatus, errorThrown) {
    alert(textStatus + errorThrown);
  }
});

The code is now working.


How to disable the comment for a specific node programmatically?

In D8, the comments are stored as field containing various comment properties including comment status.

You can disable node/entity comments using something like below:

use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;

/**
 * Implements hook_comment_insert().
 */
function [MODULE_NAME]_comment_insert($comment) {
  // Get comment field name, default comment.
  $field_name = 'comment'; // $comment->getFieldName();

  // Get entity.
  $node = $comment->getCommentedEntity();
  $node->get($field_name)->status = CommentItemInterface::CLOSED;
  $node->save();
}


Drupal 7 has IP address blocking feature by default.

Login to admin
Navigate to configuration page
Click on "IP address blocking" which available in under People panel
Add IP address which you wanted to block.

OR

Navigate to below page
http://[yourwebsitename.com]/admin/config/people/ip-blocking


How can I allow users to cancel their accounts without requiring e-mail confirmation?

The behaviour seems to be hard-coded into the user_cancel_confirm_form_submit(), which sends a message to the user if they don't have the administer users permission.

I can't see any pretty way of getting round it really, but there is something you can do.

First you need to set an undocumented variable called user_mail_cancel_confirm_notify to FALSE. I'd recommend using Drush to do it:

drush vset user_mail_cancel_confirm_notify FALSE

But you can do it in PHP if you need to:

variable_set('user_mail_cancel_confirm_notify', FALSE);

That will stop the _user_mail_notify() function from sending the cancellation confirmation email.

Next, you need to hook into the form submission for the cancellation confirm form, and force-cancel the account (otherwise it would be waiting for the user to click the cancellation link in the email you've just stopped):

function MYMODULE_form_user_cancel_confirm_form_alter(&$form, &$form_state, $form_id) {
  $form['#submit'][] = 'MYMODULE_user_cancel_form_submit';
}

function MYMODULE_user_cancel_form_submit(&$form, &$form_state) {
  // Rather than negating the complex access expression from the original form we can
  // just make the change in the else portion

  global $user;
  $account = $form_state['values']['_account'];
  if (user_access('administer users') && empty($form_state['values']['user_cancel_confirm']) && $account->uid != $user->uid) {
    // Account has already been cancelled by the system.
  }
  else {
    // Cancel the account
    user_cancel($form_state['values'], $account->uid, $form_state['values']['user_cancel_method']);
  }
}

I haven't tested any of that but after reading the functions involved in the user module I'm pretty sure it will work.


How to deactivate the automatic emails sent to administrator?

Enable and Install the Mailcontrol module and then go to admin/config/people/accounts turn off the checkbox.

  This small module extends original Drupal 7 account settings page with
  the ability to globally turn ON/OFF all standard mails.

By default Drupal 7 provides no option to globally disable the following mails:

Welcome (new user created by administrator)
Welcome (awaiting approval)
Welcome (no approval required)
Password recovery


How to print the product variation separately from the submit/pay button in a Commerce add to cart form?

This is how I fixed this issue:

Added this preprocess function in my .theme file

function YOURTHEME_preprocess_commerce_product(&$variables) {

   // Get the commerce product.
   $product = $variables['elements']['#commerce_product'];
   // Pass the price.
   $variables['price'] = $product->variations->entity->getPrice();
}

And in my twig file I print the price like this:

{{ price|commerce_price_format }}


Want to show url like termname (parent)/[termname] (Child: referenced by node) /node (node which is referenced to particular term)

In your URL aliases patterns, use this token : [node:YOURTAXONOMYFIELD:parents-all] (Ancestors of the term, i.e. parent of all above hierarchy levels).

Then your whole pattern for your node type will be [node:YOURTAXONOMYFIELD:parents-all]/[node:title].

If you have languages matters, I guess it might work with i18n prefix.


What happens to a render array after hook_form_alter() that does not happen after an AJAX callback?

Since hook_form_alter() is returning the correct results, there is a way to use that to our advantage.

By calling drupal_rebuild_form() in our ajax callback, we can return the specific part of the resulting array that should fill in our wrapper div.

e.g.

function _send_item(&$form, &$form_state) {

    $delta   = $form_state['triggering_element']['#delta'];
    $lang    = $form_state['triggering_element']['#language'];

    $new_form = drupal_rebuild_form('mymodule_node_form', $form_state);

    return $new_form['mymodule_item_id'][$lang][$delta]['item_data'];
}


On submission function is not being called in custom module

Could you try like this:

function my_form($form, &$form_state) {
  $pl_name=array();
  $pl_name=getplaylist_to_edit(arg(1));

  $form['text'] = array(
    '#type' => 'textfield',
    '#id'=>'edit-playlist-name',
    '#value' => $pl_name[1],
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Update',
  );

  return $node;
}

function my_form_submit($form, &$form_state){
  echo '<script>alert("You have submitted the form.");</script>';
}


How to count number of published nodes of a specific content type in twig template?

In a preprocess hook function for your template, you can code something like this.
function MYTHEME_preprocess_TEMPLATE_HOOK(&$variables) {
    $query = \Drupal::entityTypeManager()->getStorage('node')->getQuery();
    $query->condition('type', 'promotions');
    $query->condition('status', 1);
    $query->range(0, 1); // only need one
    $results = $query->execute();
    $variables['has_published_promotions'] = (bool)count($results);
}

has_published_promotions will be available in your Twig template and will be TRUE only when there are published nodes of that type.


New content type not listed in content types

The problem you're facing is producing symptoms very similar to the ones in this bug. Especially because one of the symptoms you mentioned is that after you create any new content type with the same machine name that had a problem ('address' in your case) you get the message:

  The content type XXX has been updated

This issue is because one of the content types that you previously created originally had a machine name of 'address' but was renamed to something else. This is because Drupal actually preserves the original machine name of any content type in the DB Table named "Node_Type" in the column "Orig_Type".

Firstly, I suggest that you open the "Node_Type" table and try to investigate. You will most likely find that one of the listed Content Types has 'address' in its "Orig_Type" column.

The bug I've linked above contains patches in order to prevent this kind of issue from happening in the future. Unfortunately, in your case, the issue had already happened and you must now clean-up.

I'm not an expert in this field as I've only been involved with drupal for 6 months. However, I'll try my best to list the steps you need to do to remedy the issue. Note that there may be better/cleaner methods than the ones I've listed below so please be cautious:

Step 1 - Please carefully investigate the "Node_Type" table in your Database as I've mentioned above before proceeding. You may be facing a different issue and this solution may or may not work in that case.

Step 2 - Backup your Database before proceeding

Step 3 - Please try to perform one of the following procedures, preferably in order until one of them works for you:

A. Try the Deletion URL

Try to go to the URL YOUR_SITE/admin/structure/types/manage/MACHINE_NAME/delete and delete the content type
Check the "Node_Type" table to see if the problematic content type was deleted.

B. Programatic Deletion

Try to programatically delete the unwanted content type by running node_type_delete($type) and then optionally node_types_rebuild(). In order to use these 2 functions in a module you must use the hook_node_info(). Something similar to this code may work in your module's ".module" file:

<?php
function MYMODULENAME_node_info()
{
  node_type_delete("address");
}

Check the "Node_Type" table to see if the problematic content type was deleted.

C. Manually Replicate node_type_delete($type)

Visit the node_type_delete($type) hyperlink, and carefully read all the functions that it invokes. They are all clickable hyperlinks too.
Either write code to use each of its functions individually.
Or, replicate the actions that all the functions perform exactly and manually in your Database.

@Mods. The site restricts me from posting more than 2 hyperlinks because of my reputation, so apologies for lack of links.


"Last comment time" is sort.

Then use 'Sort descending'


Views 2 filter: field x = current user's ID

There is a filter called User: Current which will "Filter the view to the currently logged in user."


How do I define the block visibility for content types and term pages?

If you control the code for the block, then it really is a simple matter of:

Defining the correct cache contexts (path probably)
In the build method, determining the context (getting current node, tax info from the node, and the like.)
Deciding what to output for the context
If you don't want to display it, return and empty build array (or NULL).

If you don't control the block content (e.g. view or 3rd party module), you can do the same as above and use the various methods to render the block from code.


Delete content problem in Multilingual site with module Global redirect

If not already in use, I recommend using the i18n module instead of global redirect (which is imo more a SEO module) which let set you a fall back for not (yet) translated pages as well.
With this module you can also translate menu entries, path-settings, taxonomy terms etc. (even the site name and the site slogan (when using together with the variables module)).

Greetings krueschi


Rendering a content type with Views, in Drupal 7

To create a list of two content types in Views you can't set it directly in the 'wizard'. For now just select 'All', at the bottom click 'Continue & Edit'. To only show two content types go down to 'Filter Criteria' and click 'Add'. Find 'Content: Type' in the list and check it, then click 'Add and configure filter criteria'. This will allow you to select the content types you'd like to show. Finally click 'Apply'.


Extra template name suggestions for main-menus based on regions

You should install the Menu Block module, which will let you dictate the name of the instance of the menu for easy theming. It is then up to you to give it a name.

TBH you don't want to get in the game of trying to manipulate region suggestions based on what it may or may not contain.


Field not rewritten even though "Hide rewriting if empty" not selected

Although I don't understand why Drupal doesn't behave as I posit in my original question, I have found a solution. It is to use [first_name] as the No results text. If the last name is empty, the no results text is used, and the first name is displayed. If the last name is non-empty, the rewrite results are used, and the first and last names are displayed. Kind of roundabout, but it works.


What does it take for field in an entity to be able to be used in cotexetual filter, or relationship?

Since you changed the cardinality to more than 1.

Add a contextual filter of Has Taxonomy Term ID, then scroll all the way down, click on the blue MORE button and checkmark allow multiple values.

Yeah, it's hidden, lol.


How to correctly handle date formats that needs i18n

Try something like:

$text = t("Some text @date more text @time", array(
  '@date' => format_date($timestamp, NULL, 'Y-m-d'),
  '@time' => format_date($timestamp, NULL, 'H:i'),
));

More info at:

http://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/t/7
http://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/format_string/7


Update webform without losing existing webforms

In the comment section of the documentation there is written: Note that you must be running the latest 3.x version of Webform (for either Drupal 6 or Drupal 7) before upgrading to Webform 4.x.


hook_page_attachments() is only needed so you can attach it to any possible route/url. You should be to just add it directly to the response that you re returning, and it should bubble up and be added.


Views: adding "new" image when published date < 1 month

If the list is always going to be in date order, then it can be done without PHP by using a View with an attachment. See this answer for an explanation of how to do that.

If the list is not sorted in date order, PHP may be the way to go. (Though I'd be delighted to be contradicted.) You'll need the Views PHP module installed.

Add the Content: Post date to your list of fields. If you don't want it displayed set the 'Exclude from display' check box. Displayed or not, it's needed.
Add a 'Global: PHP' field to your list of fields. In the Value code box, insert the following snippet:

$interval = time()-  $data->node_created;
$days = round($interval/(60*60*24));
return $days < 30 ? $days : 0;

This snippet grabs the value of the Post date field from the database query that the view has executed. It then works out the number of seconds difference between the post date and the current time. It converts the seconds into days. If the post is less than 30 days old it returns the number of days as a field value, otherwise it returns 0. (It could just return 0 or 1, but returning the value could be useful in some cases.)

In the No Results Behaviour section check the boxes for 'Count the number 0 as empty', 'Hide if empty' and 'Hide rewriting if empty'. This means when the PHP returns zero, nothing will be displayed.
In the Rewrite Results section, insert whatever output you want when the node is less than 30 days old. In the question you talk about an image, so maybe put in something such as .

Additional Notes

If you want to use different date fields etc. you can work out what to put in the PHP by switching on the display of the SQL query in preview. (See the Views settings tab from the main Views page.)

If you want a bit more control over your output, you can use the Output code box. For example the following code will put a red 'new!' label against new fields. When doing this you don't want to also have Rewrite Results set.

<?php if ($value) echo '
new!
' ?>

This code checks to see if the result of the earlier PHP code is TRUE (and not zero is TRUE). If it is is displays the red 'new!'


Sharing article to facebook adds reserved html characters in heading (&amp #039)

Those are the encoded values of the characters. Before you share it to the facebook, check any hook if module is providing to decode it and then share it.

You'll have to use htmlspecialchars_decode($str); to do that.


In THEMENAME_preprocess_page (in template.php located in your themes directory) you can set as many template hook suggestions as you wish. Drupal then goes through the list from bottom to top and once it finds the existing template suggestion, it stops and uses that one.

function THEMENAME_preprocess_page(&$vars) {
  // Add theme hook suggestions based on path for nodes only.
  if (isset($vars['node'])) {
    // get whatever you want here into $path variable
    $path = $vars['node']['type'];
    $vars['theme_hook_suggestions'][] = 'page__node__' . $path;
  }
}

in the $vars there should be the node object that you can check for
$vars['node']. also don't forget to sanitize anything you are adding there. good choice would be to use the drupal_clean_css_identifier function


Is it possible to use different tokens in metatag based on content type

In Drupal 7
When you configure Metatag, you can click on + Add default meta tags and this will allow you to set them up by Content Type.

You will see this gets added to the config tree. Simply now edit the content type you just added.
Bonus/Extra Info
If you need to alter only specific nodes, edit your node and scroll down to the end and select the Meta tags tab.


check if you have installed the latest module(7.x-2.2) and selected the reCaptchas challenge type dropdowns(for the required pages).. I too had error in displaying reCaptchas..Later i figured that i installed old versions.


Display one time message to user upon logging in

You can try the Splashify module

  Display a splash page anywhere on your site by redirecting the user,
  showing a lightbox, or displaying a popup. This module is designed to
  be search engine friendly, mobile device friendly and offers multiple
  configuration options.


programmatically saving a node doesn't add any record to dblog

The reason that the save operation is not logged during node_save is because it is done during the node form submission process by node_form_submit which internally uses node_save.

Please refer this elaborate and well-written response of saving the node using drupal_form_submit answered by user Francisco Luz. Pasting the code for the sake of completion here for saving an article resulting in both the watchdog logging and the drupal_set_message of the acknowledgement.

global $user;
module_load_include('inc', 'node', 'node.pages');

$node = (object) array(
  'uid' => $user->uid,
  'name' => $user->name,
  'type' => 'article',
  'language' => 'und',
);
node_object_prepare($node);

// Get default values from attached fields.
$fields = field_info_instances('node');
$form_state = array();
foreach($fields['article'] as $field_name => $values) {
  $form_state['values'][$field_name] = array('und' => array());
}

// Add the $form_state field values.
$form_state['values']['title'] = 'my title';
$form_state['values']['body']['und'][0] = array(
  'value' => 'my body',
  'format' => 'full_html',
);
//$form_state['values']['field_MYFIELD']['und'][0]['value'] = 'blah blah';

// Without this line, not quite sure why, it wont work.
$form_state['values']['op'] = t('Save');

drupal_form_submit('article_node_form', $form_state, $node);

// Tell watchdog if any of the fields fail validation.
$errors = form_get_errors();
if (!empty($errors)) {
  foreach ($errors as $field_name => $message) {
    watchdog('MYMODULE', '%field: %message',
      array('%message'=> $message, '%field' => $field_name));
  }
}

I did run this once with devel php console and it logged the node during the node creation. Hope this helps.


Just in case someone else finds this.

You can use Entity Rules This was made for Entityform 1.x but could be used with 2.x

You could probably also use Field Validation if you didn't want to use Rules.


Caching issue with View and anonymous users

Here is a small hack to prevent some pages from being cached for anonymous users:

// Prevents frontpage caching
if (drupal_is_front_page()) {
  $GLOBALS['conf']['cache'] = FALSE;
}

Hope this helps, cheers!


Stripping the wrappers in a custom field d7

You can override field.tpl.php and its derivatives if you want to code it manually.

Or the Fences module might do the trick:

  Fences is a an easy-to-use tool to specify an HTML element for each field. This element choice will propagate everywhere the field is used, such as teasers, RSS feeds and Views. You don't have to keep re-configuring the same HTML element over and over again every time you display the field.

It lets you control the base markup for each field through the UI - a must have for any project these days in my opinion :)


How to display node in view and allow users add comment?

Yes, you can show node in view and also allow users to add comment. See example below:

Create a view normally.
Under Format section, change Show settings to Content
Select the view mode as Full Content and enable Display
Comments. (Check screenshot below)
Click on Apply


The Manual Crop module does the best job.

To quote the project page:

  The Manual Crop module exposes a set of image style effects that
  enables users, if enabled in the widget settings, to crop (and scale)
  an image after uploading.

Essentially this means you can choose a different crop area for each image style used.


How to handle the cache per user in REST Resource?

@Leigh is right and user does exist. Cache contexts are hierarchical (see change record https://www.drupal.org/node/2451661) and user is a top level context.

So this should work (note the plural form of contexts):

  '#cache' => [
    'contexts' => ['user'],

You can also add the cache context by IDE autocompleting:

$response->getCacheableMetadata()->addCacheContexts(['user']);


Module always returns the default language in hook_theme()

Data from hook_theme is cached, any logic decisions you make in it will only apply when the theme registry is rebuilt.

The point of variables is that they're passed in at the time the theme is called, not when the theme hook is declared.

For example hook_theme() should look like this:

MODULENAME_theme($existing, $type, $theme, $path) {
  return [
    'modulename_block_template' => [
      'variables' = [
        'description' => '',
        'image' => '',
        'current_language' => '',
      ],
    ],
  ];
}

And you pass the variables in when you use it:

$currentLangCode = \Drupal::service('language_manager')->getCurrentLanguage()->getId();
$imageUrl = '';
# If current language code is english
if ($currentLangCode == "en") {
    $imageUrl = "English image url"
} elseif ($currentLangCode == "fr") {
    $imageUrl = "French image url"
}

$build = [
  '#theme' => 'modulename_block_template',
  '#description' => '...',
  '#image' => $imageUrl,
  '#current_language' => $currentLangCode,
];


The error message suggests that the script you're invoking has embedded \r characters, which in turn suggests that it has Window-style \r line endings.

Try to install from other source or something


Like for any css file, add it into the theme's info file, but rather than 'all', just specify it to be only for print.

stylesheets[all][] = css/everytime.css
stylesheets[screen][] = css/screen-only.css
stylesheets[print][] = css/print-only.css


Sanitization functions, which include filter_xss(), are used when a value is shown as output, not when something is saved in the database.

None of those functions is called when saving a node in the database.

See Writing secure code.

  Use check functions on output to prevent cross site scripting attacks

  No piece of user-submitted content should ever be placed as-is into HTML.

  Use check_plain() or theme('placeholder') for plain text.
  Use check_markup() or filter_xss() for markup containing text.
  Use the t() function with @ or % placeholders to construct safe, translatable strings.


Attaching a system js library using #attached property (D7)

Going from the working example, I imagine this is what you need:

$form['#attached']['library'][] = array('system', 'ui.droppable');

Without the module name Drupal won't know where to find the library hooks.

But if you want to add a custom library from sites/all/libraries/myAwesomeLibrary this is the right way:

$form['#attached']['libraries_load'][] = array('myAwesomeLibrary');


Just clearing cache is not enough, you need to uninstall and then re-install your module in order for the .module file to be discovered.

In the Admin panel go to Extend and select the Uninstall tab. Select your custom module and click the Uninstall button. Now go back to the List tab and re-enable your module as before. Your implementation of hook_entity_insert() should now be recognised.


drupal commerce - when adding to cart on review page, get redirected back to checkout

I had this exact same problem with a very similar workflow.  I created a workaround to this issue by integrating the commerce_cart_product_add($uid, $line_item) function from the Commerce Cart module into my custom module.  This way I could test what was happening in Commerce without hacking the contrib module.  From there I discovered that the issue stemmed from an invoked rule at the bottom of this function:

 rules_invoke_all('commerce_cart_product_add', $order, $product, $quantity, $line_item);

Removing this rule from my local version of this function solved the redirect issue. I looked through the Commerce Settings and the Rules UI in the Drupal admin to see if I could find this rule to disable it, but I could not find a reference to it anywhere.  This is not the best solution, but for now it solves the redirect issue.  I would be interested to hear if anyone else has run into a similar issue though.


Need help with my form with duplicate file and resetting form

As described in the docs file_save_upload
file_save_upload($form_field_name, $validators = array(),
$destination = FALSE, $replace = FILE_EXISTS_RENAME)

the last parameter $replace

$replace: Replace behavior when the destination file already exists:
FILE_EXISTS_REPLACE: Replace the existing file.
FILE_EXISTS_RENAME: Append _{incrementing number} until the filename is unique.
FILE_EXISTS_ERROR: Do nothing and return FALSE.


Is it normal for a database to have 3600 tables?

Those tables are tables for fields. Whenever you add a field to a content type Drupal creates two tables, one to store the field value and another one to store historical data of that field.

Deleting those table will break your site.

This just means that you have a lot of fields. Usually, in drupal 7 it is a watchdog table that contributes to the size of your database unless you want to keep historical log data feel free to clear some data from watchdog table.


Compound field that includes a file field

A file field is an entity reference field pointing to the File entity (or in D8.4 to the Media entity). To build such a file field extend FileItem (which parent is EntityReferenceItem). An example for this would be the image field ImageItem, which is a compound field adding properties like title, alt, height and width:

ImageItem::propertyDefinitions()

public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    $properties = parent::propertyDefinitions($field_definition);

    unset($properties['display']);
    unset($properties['description']);

    $properties['alt'] = DataDefinition::create('string')
      ->setLabel(t('Alternative text'))
      ->setDescription(t("Alternative image text, for the image's 'alt' attribute."));

    $properties['title'] = DataDefinition::create('string')
      ->setLabel(t('Title'))
      ->setDescription(t("Image title text, for the image's 'title' attribute."));

    $properties['width'] = DataDefinition::create('integer')
      ->setLabel(t('Width'))
      ->setDescription(t('The width of the image in pixels.'));

    $properties['height'] = DataDefinition::create('integer')
      ->setLabel(t('Height'))
      ->setDescription(t('The height of the image in pixels.'));

    return $properties;
  }

The properties for the referencing part are inherited from the parent.


I think that the best way to go is jQuery.

Create new block with text that you want to show
Using CSS, set block position that you want
Set display:none; for that block
Add jQuery script in your block (or implement on some other way).

Script should looks something like:

jQuery("#logo").hover(
        function () {
            jQuery("#blockId").fadeIn(); //change the blockId with Id of your block
            jQuery("#block-views-projects-block").fadeTo(1000,0.5);
        },
        function () {
            jQuery("#blockId").fadeOut(); //change the blockId with Id of your block
            jQuery("#block-views-projects-block").fadeTo(1000,1);
        }
    );

Of course, if you add this code in your block, it must to be added into <script>...</script> tag.


Displaying multiple fields in referenced webform option?

The issue is coming from Drupal core and is fixed in Drupal 8.8.

@see Issue #2174633: View output is not used for entityreference options


If the fields you're interested in are attached to the user entity directly (i.e. not using something extra like the Profile2 module), then your assumption is 100% correct. You'll also see a field_revision_field_user_job_title, which is used to store the current revision (for entities that have that functionality).

The user entity doesn't have revisions, so in my experience if you need to go directly into tables, the field_data_* ones are the best bet.

To get as much reusability as possible, though, you should really use the EntityFieldQuery class to perform such queries. For example, if you wanted to get all users with a certain "job_title", you can use something like this:

$query = new \EntityFieldQuery();
$query->entityCondition('entity_type', 'user')
  ->fieldCondition('field_title', 'value', 'foo');

$results = $query->execute();
if (!empty($results['user'])) {
  $users = user_load_multiple(array_keys($results['user']));
}


Can i make a node reference to some field but not the title field?

You can make node reference to a view
In a case I added a title and an image in an auto-complete and it worked fine
you can check it by adding any field not a title


You need to replace HOOK with your module name. As well as MYMODULE.


Adding attributes to a link to an uploaded file

file-link.html.twig
{{ link|merge({'#attributes': {'target': '_blank'}}) }}
{% if file_size %}
  {# @todo remove class before Drupal 9.0.0 #}
  ({{ file_size }})
{% endif %}

Alternatively, you can also solve this via preprocess.
mytheme.theme
/**
 * Implements hook_preprocess_HOOK().
 */
function mytheme_preprocess_file_link(&$variables) {
  $variables['link']['#url']->setOption('attributes', ['target' => '_blank']);
}


Views Bulk Operations has an "Unpublish comments containing keyword" operation.


How do I make a list of Users and their total number of posts in a given date?

You may want to check if using the Views Date Format SQL module could be a solution for you. Here are some quotes about it (from its project page):

  ... allows to format date fields using SQL.

  The core functionality is to remove the date formatting from render() and put it in query(). I.e. format date values using SQL's DATE_FORMAT rather than PHP's format_date.
  This is achieved by assigning a new default handler to node 'created' and 'changed' date fields. This handler extends and overrides views's build in views_handler_field_date.

  The UI is completely unobtrusive, only a single checkbox "Use SQL to format dates" is added to the handler configuration popup.

Your question is not about creating charts in Drupal, but you may want to refer to this comment also for an example of how we typically use it within the Charts (disclosure: I'm a co-maintainer) module.


display selectable drop down options based on a checkbox selection

Programatic way

  $form['checkbox_form'] = array(
    '#type' => 'checkbox',
    '#title' => t('sometitle'),
    '#default_value' => variable_get('checkbox_form', TRUE),
  );

  $form['selectbox'] = array(
    '#type' => 'select',
    '#title' => t('sometitle'),
    '#default_value' => variable_get('selectbox'),
    '#options' => array(
          TRUE => t('Yes'),
          FALSE => t('No'),
     ),
    '#states' => array(
      'visible' => array(
        ':input[name="checkbox_form"]' => array('checked' => TRUE),
      ),
    ),
  );

Second form element visible makes the trick.

Module Way

Use Conditional Fields module.

  Conditional Fields allows you to manage sets of dependencies between
  fields. When a field is “dependent”, it will only be available for
  editing and displayed if the state of the “dependee” field matches the
  right condition. When editing a node (or any other entity type that
  supports fields, like users and categories), the dependent fields are
  dynamically modified with the States API. A simple use case would be
  defining a custom “Article teaser" field that is shown only if a "Has
  teaser" checkbox is checked, but much more complex options are
  available.


The field structure you are using for your entity reference field is not correct. See entityreference_field_schema().

The correct column name is target_id, not product_id, so it should be like this:

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

$node->field_product[LANGUAGE_NONE][]['target_id'] = $entity->product_id->value();

node_save($node);

This assumes you are using an entity wrapper to access the $entity object but not for accessing the $node object.

[edit]

Regarding your dpm() not firing, it is quite possible it is firing but you aren't seeing the output. This can happen depending on where you are calling it from.

A good alternative in these cases could be dd() or watchdog() since their output will be visible regardless of where you call it from.


_menu_tree_check_access() should go a long way towards understanding what Drupal does internally.

It declares a new array of items, then loops through each item currently in the menu and checks access. Only if the current user has the correct access is the item added to the new array. At the end of the function, only the new array is returned. So Drupal's method is actually a bit more low-tech than I think you were going for.

Just so the process is a bit more obvious the functions are called in this order:

menu_build_tree() calls
menu_tree_access() which in turn calls
_menu_tree_access()

If you're looking to emulate the way Drupal builds its menus, I think menu_build_tree() is probably the best place to start.


Have you looked into the Context module for this (https://www.drupal.org/project/context)? One of the "reactions" is to change the theme. You can do it by system path.


How to create a menu child of an other menu?

You can use the Menu block module

  .. allows you to display blocks of menu links starting with any desired level of a menu and limited to any desired depth.

  .. you can choose to expand all menu links with children or to root
  the menu tree to a specific menu item.


Putting an extra <div class="img-responsive"> wrapper around the standard atom markup generated by Scald works (sort of - the legend doesn't look good).

However, I've solved this by just copying the Bootstrap img-responsive class, using it as an override for the Scald dnd-atom-wrapper class:

// Just copy the Bootstrap CSS for img-reponsive.
.dnd-atom-wrapper {
  max-width: 100%;
  display: block;
  height: auto;
}

This seems to work for all image atoms in Scald (it may break other types of atoms - I only use Scald atoms for images).

I really want to emulate the complete Bootstrap "thumbnail" concept (including nice borders and captions), but using  standard Scald atom css classes, so I ended up with these overrides for the relevant classes (this is the default player - must be slightly adapted to work with the HTML5 player):

// CSS fror Scald image atoms
.dnd-atom-wrapper {
  max-width: 100%;
  display: block;
  height: auto;
  background-color: #ffffff;
  border: 1px solid #dddddd;
  border-radius: 4px;
  line-height: 1.42857;
  margin-bottom: 5px;
  padding: 4px;
  transition: border 0.2s ease-in-out 0s;
}
.dnd-legend-wrapper {
  margin: 0;
  text-align: center;
  font-size: 0.8em;
  width: 100%;
}
.dnd-atom-wrapper,
.dnd-drop-wrapper img {
  margin-left: auto;
  margin-right: auto;
  float: none;
  display: block;
}
.dnd-atom-wrapper.atom-align-right {
  @media (min-width: @screen-lg-min) {
    margin-left: 0.7em;
  }
}
.dnd-atom-wrapper.atom-align-left {
  @media (min-width: @screen-lg-min) {
    margin-right: 0.7em;
  }
}
.atom-align-right {
  @media (min-width: @screen-lg-min) {
    float: right !important;
  }
}
.atom-align-left {
  @media (min-width: @screen-lg-min) {
    float: left !important;
  }
}

I have this CSS in less/overrides.less in my Bootstrap subtheme.

Remember to compile it with lessc and clear caches for it to work.

Below you can see it in action.  Big screen on the left, small screen on the right.


Views 3 supports grouping.

For views 2, aside of Views Group By, you can also write a custom module, implement hook_views_query_alter(&$view, &$query) and do something like:

function MYMODULE_views_query_alter(&$view, &$query) {
  if ($view->name == 'view_name') {
    if ($view->current_display == 'page_XXXXXX') {
      // Tell the query constructor these fields must be used with the GROUP BY clause
      $query->add_groupby('field1');
      $query->add_groupby('field2');

      // hack to make the query constructor just ignore these fields (not adding them to the GROUP BY clause. It's needed to let it continue without problems
      $query->fields['fieldalias3']['aggregate'] = TRUE;
      $query->fields['fieldalias4']['aggregate'] = TRUE;
      // ... all but the grouped and aggregated fieldaliases must have this.

      // Configure the fields that perform the aggregation (SUM, AVG, etc)
      $query->fields['aggregatedfieldaliasA']['table'] = '';
      $query->fields['aggregatedfieldaliasA']['field'] = "SUM(fieldA)";
    }
  }
}

You now should be able to see the resulting query in the preview when editing the view and make sure it is correct. Field aliases in the code refer to "SELECT table.field1 as fieldalias1 ...", it's easy to get them just by checking the query shown in the preview.


How can I force administrator to provide a reason when cancelling a user account

In User fields, add field of type: List Text with checkboxes radio button as widget
Use the Filed Permissions module so only admins can see this user field.
Download Rules and enable Rules UI
Create a New Rule
React on: After Updating an Existing User Account
Add Condition: Data Comparison >> account-unchanged:status >> Operator: Equals DATA Value: Blocked
Add Action >> Send Mail >> Body: [user:name] was blocked because [user:field-example]


IMCE is an image/file uploader and browser that supports personal
  directories and quota.

You'll need to integrate this file browser with your WYSIWYG editor (supports almost every editor), and you can work with personal or shared folders for users or permissions per directory.


I have issue with commerce_order_load_multiple function

when i use static value of integer in place of uid i am getting result

Logically speaking, that can only mean that $mm->uid doesn't contain what you think it does.

Install the devel module and use the dpm function to inspect the var:

foreach ($mms as $mm) {
  dpm($mm);
}

That should tell you what's going wrong.


After studying up the Feeds module, I what I needed. The Feeds module, set up properly, mapped the organic group of the Feed node to the newly created [Blog] node.

Link: /admin/build/feeds


Using JSON:API to replicate content on external location

For consideration, an interesting way do this that was suggested to me by gabesullice, is to deny access to the fields. This also resulted a performance improvement in jsonapi 1.x, maybe 2.x as well.

/**
 * Implements hook_entity_field_access().
 */
function MYMODULE_entity_field_access($operation, $field_definition, $account, $items = NULL) {

  $request = \Drupal::request();
  if (strstr($request->getUri(), '/jsonapi/node/')) {
    $name = $field_definition->getName();
    switch ($name) {
      case 'field_blah':
      case 'uid':
      case 'moderation_state':
      case 'promote':
      case 'sticky':
      case 'unpublish':
      case 'review_date':
      case 'vid':
      case 'type':
      case 'revision_translation_affected':
      case 'revision_timestamp':
      case 'revision_log':
      case 'revision_id':
      case 'revision_uid':
      case 'langcode':
      case 'default_langcode':
        return AccessResult::forbidden();
    }
  }
  return AccessResult::neutral();
}


Save patch changes after module upgrading

Well...no, not really.

When you apply a patch, you change the contents of the file. When you upgrade the module, you overwrite the contents of the file again, so your changes have been lost. This is a simple file-system issue and transcends Drupal's involvement entirely.

I guess you could set up some fancy file watching script which automatically applies your patch after files have been changed, or automate your upgrades in such a way that the patch is applied straight afterwards - but again that's nothing to do with Drupal as such, it's about your own workflow techniques. You'll also need to factor in the fact that your original patch may no longer apply to the newly updated file(s), so some manual intervention is probably wise.

Patches are of course unavoidable sometimes, but wherever possible don't alter core or contrib modules (for this very reason). 90% of the time you can find a clean way round the problem if you look hard enough


How to change order and depth of user account tabs

I forked User Tabs and added new subtabs (see NEW-SUBTAB in code):

/**
 * Implements hook_menu_alter().
 */
function usertabs_menu_alter(&$callbacks) {
  $callbacks['user/%user/account'] = array(
    'title' => 'Account',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
    'load arguments' => array('%map', '%index'),
  );
  //move the original edit and view items to below this container
  _usertabs_move_item($callbacks, 'user/%user/view', 'user/%user/account/view', MENU_DEFAULT_LOCAL_TASK);
  _usertabs_move_item($callbacks, 'user/%user/edit', 'user/%user/account/edit', MENU_LOCAL_TASK);
  _usertabs_move_item($callbacks, 'user/%user/NEW-SUBTAB', 'user/%user/account/NEW-SUBTAB', MENU_LOCAL_TASK);
  unset($callbacks['user/%user_category/edit/account']);
  if (($categories = _user_categories()) && (count($categories) > 1)) {
    foreach ($categories as $key => $category) {
      // 'account' is already handled by the MENU_DEFAULT_LOCAL_TASK.
      if ($category['name'] != 'account') {
        //it was too friggin complicated to support %user_category
        //see comments in user_category_load
        //all it does is check that the category name is valid
        _usertabs_move_item($callbacks, 'user/%user_category/edit/' . $category['name'], 'user/%user/account/'.$category['name']);
        $callbacks['user/%user/account/'.$category['name']]['tab_parent'] = 'user/%/account';
      }
    }
  }
}


rewrite with nginx conf result 502 bad gateway

The location of file phpfpm.sock may vary depending on Operating System:

Try find the phpfpm.sock file on your server:

find / -name php*fpm.sock

and then change the following line

fastcgi_pass unix:/tmp/phpfpm.sock;

to reference phpfpm.sock from the correct location.

Example (Ubuntu 14):

fastcgi_pass unix:/var/run/php5-fpm.sock;


Unable to configure SMTP authentication support module

Try to clear cache and go to the following path: admin/config/system/smtp or Home » Administration » Configuration » System » SMTP Authentication Support


I think you can do what you want using OG and Views with nothing custom. This is a good place to get started: https://modulesunraveled.com/organic-groups-7x-2x.


metatag_display_extender plugin does not exist

I had this issue when trying to add metatag_views to an install profile.
I fixed this issue by adding a config dependency on metatag_views to the top of views.settings.yml:
dependencies:
  module:
    - metatag_views

There's more information on this Drupal.org issue.


Views Conditional is a simple module that allows you to define conditionals (if xxx then yyy)
with fields in views.

  Conditions include:

  Equal To
  Not Equal To
  Greater Than
  Less Than
  Empty
  Not Empty

For D6

Views - Control field display

  It provides a views filter that allows users to control which fields
  are displayed.

  To use, install the module, then add the Global: Control field
  visibility filter to your view. Select which fields are controllable
  (either defaulting to visible or invisible). This will add an exposed
  element that allows users to toggle the fields you specify on or off.


Search system based on two taxonomy vocabulary for Local Business Directory for Drupal 7

You need to familiarize yourself with Views module. Simply create a view of nodes of your particular content type, add two filters, one for each taxonomy, expose them and you are done.


How to automatically assign a (sequential) number to a user-created node

The Serial module allows you to do exactly that. You can simply have an integer number that is incremented per content type and if you wanted a prefix you could do that in the display formatter.

  Unlike Drupal's built-in auto-increment node ID, which is global and
  shared by nodes belonging to all content types, serial fields are
  managed per content type (D6) / entity (D7). For example, the serial
  field of an Invoice instance will generate a unique sequential number
  (starting at 1, then 2, etc.) exclusively for Invoice instances.


How to tell if my Drupal site is comprised from the SA-CORE-2018-002 -- 2018 March exploit?

How can I tell if someone used this exploit to hack my site?
Your Drupal 7 or 8 site can experience loss or theft of data, data can be removed, deleted or changed, wreaking havoc on the site in many different ways.
See this Stack Exchange post for general information on checking to see if your website has been hacked.
What can they do with this exploit if executed properly?
The exploit is a remote code execution vulnerability, which means any data has the potential of being affected.
This exploit has been given a risk score of 21/25, which is almost the highest that it gets. This risk score also defines the following vulnerabilities, among others:

AC (Access complexity): easy (no skill) to access and exploit
A (Authentication): no special authentication needed
Cl (Confidentiality impact): all non-public data is accessible
II (Integrity impact): All data can be modified or deleted

Read more about risk scoring and definitions here.
I can't update my Drupal sites now, what is a good alternative to patch up this hole easily?
There is a patch available if you are unable to update core right away. From Drupal.org:

If you are running 7.x, upgrade to Drupal 7.58. (If you are unable to
update immediately, you can attempt to apply this patch to fix the
vulnerability until such time as you are able to completely update.)
If you are running 8.5.x, upgrade to Drupal 8.5.1. (If you are unable
to update immediately, you can attempt to apply this patch to fix the
vulnerability until such time as you are able to completely update.)

To read more, here is an FAQ about the exploit


custom module date formatter for publication date

The publication date module provides a function to define which formatters can be used. I added a patch, which we maintain locally, to add the defined "timestamp_ap_style" format to the options. Optionally, I could have added it inside a custom module, but the patch seemed to make more sense.

 function publication_date_field_formatter_info_alter(array &$info) {
   $info['timestamp']['field_types'][] = 'published_at';
   $info['timestamp_ago']['field_types'][] = 'published_at';
   $info['timestamp_ap_style']['field_types'][] = 'published_at';
 }


If you know the node NID of this special page, it would be a quick...

<?php if ($_GET['q']=='node/NID'): ?>

extra logo

<?php endif; ?>

...in your page.tpl.php file.  You could also create a special template for this node:

page--NID.tpl.php // for Drupal 7
page-NID.tpl.php  // for Drupal 6

...and have it in there all the time.

If you want to make sure that www.example.com/special uses a special template regardless of what node/NID it is really, eg, special is really an alias for node/6 or something, then you will need to get a bit more "special" with some preprocessing to look at the path alias and check if it is special and then do things different.  And I say preprocessing because there should be as little logic in the templates as possible.


How do I disable the default user system or view pages without login?

It depends on the type of page really, what module provides it, how permissions are implemented by that module - the short answer is by setting correct permissions at /admin/people/permissions.

You can't disable the user module, it's a required part of Drupal. Conceptually, if you were to disable it you'd have no authentication control over the admin section, and any user could make whatever changes they wanted - obviously that's not a situation that can be allowed to exist for 99.99% of users. And if you do want that, you just need to set up permissions to allow it.

But you can stop users from registering, which avoids that problem. And by setting appropriate permissions you can decide exactly what users (or even groups of users, using the Roles system) can see/do.


How to add class to embedded Paragraphs field-items?

Drupal 7
You should be able to copy this function into your template.php file of your theme:
/**
 * Process variables for paragraphs-items.tpl.php
 */
function mytheme_preprocess_paragraphs_items(&$variables, $hook) {
  $variables['view_mode'] = $variables['element']['#view_mode'];
  $variables['field_name'] = $variables['element']['#field_name'];

  $variables['content'] = $variables['element']['#children'];

  $variables['classes_array'][] = drupal_html_class('paragraphs-items-' . $variables['element']['#field_name']);
  $variables['classes_array'][] = drupal_html_class('paragraphs-items-' . $variables['element']['#field_name'] . '-' . $variables['view_mode']);
  $variables['classes_array'][] = drupal_html_class('paragraphs-items-' . $variables['view_mode']);

  $variables['theme_hook_suggestions'][] = 'paragraphs_items__' . $variables['element']['#field_name'];
  $variables['theme_hook_suggestions'][] = 'paragraphs_items__' . $variables['element']['#field_name'] . '__' . $variables['view_mode'];

  // your code here
  $variables['classes_array'][] = 'your-class';
  $variables['classes_array'][] = 'your-other-class';
}

You should also be able to do this for individual item:
/**
 * Process variables for paragraphs-item.tpl.php
 */
function mytheme_preprocess_paragraphs_item(&$variables, $hook) {
  // your code here
  $variables['classes_array'][] = 'your-class';
  $variables['classes_array'][] = 'your-other-class';
}

After adding this function, clear the cache so it is registered. You can then check if either one are being called by adding a breakpoint or print 'called'; exit; if you do not have something like XDebug installed.
Note how the second function is paragraphs_item and not paragraphs_items. Both of these are defined as theme hooks in paragraphs.module.
You can even do this as well:
/**
 * Implements hook_preprocess_entity().
 * @param $variables
 */
function mytheme_preprocess_entity(&$variables) {
  if ($variables['entity_type'] == 'paragraphs_item' && $variables['elements']['#bundle'] == 'your_bundle') {
    $variables['classes_array'][] = 'your-class';
  }
}


How to pre-populate a field with the current users name?

To answer the question posed in the title of this question, you could in a custom module do something along the lines of...

function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  global $user;

  if ($form_id=='NODETYPE_node_form') {
     $form['field_FIELD'][0]['#default_value']['value']=$user->name;
  }

  // any other form alters you need

}

where MYMODULE is the name of your custom module, NODETYPE is the content type in question and FIELD is the field name in question without the field_ prefix.  Now, whenever you are editing or creating a content type of NODETYPE, the FIELD in question will have a prefilled default value of the current user's name.

Now, if this is a different form, you'll just need to adjust the $form_id== construct to point to that form, the field in that form, etc, but the rest of the logic should be the same.


What is the suitable file permission for 'files'?

This really depends on how you have Apache configured.

I almost always run Apache in prefork mode.  When I do this, I

chown -R apache.apache sites/default/files
find sites/default/files/ -type d -exec chmod 755 {} \;
find sites/default/files/ -type f -exec chmod 644 {} \;

This lets Apache write to that directory.  Note that the owner/group depends on the setting from httpd.conf.

When I use FastCGI, then I use the user that Apache runs as.

The main key is that your files/ directory is owned and writable by just Apache, and that the rest of the files in docroot are owned and writeable by someone else, and not writable by Apache.  Normally this is the user I run drush as.

One quirk has to do when drush runs things that write to this directory, like bam-backup.

Then I will add my drush user to the Apache group, and do

chown -R apache.apache sites/default/files
find sites/default/files/ -type d -exec chmod 775 {} \;
find sites/default/files/ -type f -exec chmod 664 {} \;

so that drush can write to files, but Apache can't write to the rest of docroot.


How can I add a CSS class to a View Field programmatically?

You can add any css class, HTML tag to any field through views admin UI, why don't you add the class from there?

UPDATE

Because you need add the css class based on some condition, you have to use the following preprocess function. your code is going to be some thing like this (maybe a few modification will be needed )

function mytheme_preprocess_views_view_field(&$vars){
     $view = $vars['view'];
    if($YOUR_CUSTOM_CONDITION == TRUE && $view->name == VIEW_NAME)
           $vars['classes_array'] = 'my-conditionally-added-class';
}

because you output the content on views you have to use mytheme_preprocess_views_view_field function.

For more information visit Themeing Views field output with Preprocess function.


How to use the node title in the "Override title" field of contextual filter

Simply add title as a field and checkmark hide from display, now {{ title }} should work despite not being listed as replacement pattern.
Also make sure your view's title is set to none

Alternatively, you could also solve it by not overriding it in the contextual filter settings and instead overwrite it directly in the view's title.
Add title and type as fields, hide them if you want/need to.

But, if you're using teaser

The above two solutions won't work, so you can solve it programmatically:
/**
 * Implements hook_views_post_render()
 */
function mymodule_views_post_render($view) {
  if ($view->id() == "view_name" && $view->current_display == 'page_1') {
    $node = $view->result[0]->_entity;
    $new_title = $node->type->entity->label() . ' ' . $node->getTitle();
    $view->setTitle($new_title);
  }
}


How to add Attributes to the input tag of a field

If you can write your own module, you can implement the hook_form_alter:

function my_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'the_form_i_want_to_change') {
    $form['the_field']['#attributes']['autocorrect'] = 'off';
    $form['the_field']['#attributes']['autocapitalize'] = 'off';
    $form['the_field']['#attributes']['spellcheck'] = 'false';
  }
}


When webform block submitted send email to node author and site admin -how?

The best solution (IMHO) doesn't actually work: you should be able to use the Tokens module and use a proper token to fill a recipient field. For example:
[node:author:mail]

However, Webforms only appears to support its own %something tokens, and those only relate to the current user and the webform id (not the id of the node being read).

So instead, write the site's inevitable custom module and use hook_mail_alter() to change the To address.

Another resource I read (and have now lost) suggested setting the Webforms recipient to something easily recognizable, like "replace-me@mysite.com".

Then in your hook_mail_alter() function,

confirm the form's identity,
get the current post's author,
get that user's email address, and
use it in the Recipients. (Along with the admin & the poster, as you like.)


Understand message before updating a module

The message on red background are critical or security fixes means the module is insecure or has known vulnerabilities. It's important to you to update flagged (red highlighted) modules as soon possible so you can prevents hacks.

A recommended module means your modules are many version(s) behind the current release, the module is known to be secure, and simply not up to date with features the current module offers.


As suggested by Ivan Jaros, you can override input--file.html.twig if you want to use twig templates. Basic input template is as follow:

{#
/**
 * @file
 * Theme override for an 'input' #type form element.
 *
 * Available variables:
 * - attributes: A list of HTML attributes for the input element.
 * - children: Optional additional rendered elements.
 *
 * @see template_preprocess_input()
 */
#}
<input{{ attributes }} />{{ children }}

If you need to add more dynamic variables, you can use template_preprocess_input() preprocess function.

Also, you can use debug: true under twig.config in services.yml. This will help for theme-related development.

Note: Drupal provides default classes that are from generic to specific to the field. If generic classes helps to theme, I would suggest to avoid all the above.


Award user points for selecting an avatar?

I don't think there already exists a module for this.

What you need to do is implement hook_user_update() and check if the user now has a picture assigned but didn't before. If so, use userpoints_userpointsapi() to grant the user the number of points you want.

Something like this:

<?php
function yourmodule_user_update(&$edit, $account, $category) {
  if (!empty($edit['picture'] && empty($account->picture)) {
    $params = array(
      'uid' => $account->uid,
      'points' => 10,
      // You probably want to provide additional arguments,
      // refer to the API documentation.
    );
    userpoints_userpointsapi($params);
  }
}
?>


Ideas for implementing a shift scheduler? calendar? custom content type?

Maybe you are aware of the calendar module https://drupal.org/project/calendar
It has a very nice integration with views, and you could create a calender from template for a specific content type that has date fields in seconds (that generates also a view of it per week).
Of course for the case you have described you will need custom coding, surely the Drupal Ajax Framework and some other stuff... but that sounds more like fun :)


Extended default form inside block, possible?

Using php inside blocks or simply pouring your database with php used to be bad practice.

Said that, the function toy are looking for is drupal get form:

https://api.drupal.org/api/drupal/includes%21form.inc/function/drupal_get_form/7


using form_state->set() inside ajax callback but cannot get the value back outside the callback

As 4k4 mentioned, you cannot change the form state inside an ajax callback function.

You can, however, change it in the ajax button submit function.

$form['ajax_button']['#submit'][] = [static::class, 'ajaxButtonSubmit'];

public static function ajaxButtonSubmit($form, $form_state) {
  //...
}


Drupal Commons make group content visible for anonomous users?

Simple solution - in Permissions (People), check 'Anonymous User' for the 'Node' setting 'View Published Content'.


Internationalization (i18n) + Translation Management - No interface for adding translator available

In the meantime I found the answer: I just realized that "ICanLocalize translation service" module wasn't enabled.

After enabling, I can see the following:

So I think I can consider my problem solved. :)

You could also enable "Local translation service" module to add your local translators.


How to track and display selected user activities in a site?

There are a few modules that could help you out (quotes included are from their project pages):

Activity:

  ... keeps track of the things people do on your site and provides mini-feeds of these activities in blocks, in a specialized table, and via RSS. The module is extensible so that any other module can integrate with it. The messages that are produced are customizable via the admin interface and are context sensitive.

Heartbeat

  ... displays user activity on a website. This module is an API to log activity. The logged data contains message structures, attributes and variables. Once the activity messages exist in the database, they will be parsed and build into activity streams.

User Activity

  ... calculates an activity index based on a user's logins, page impressions, created nodes and comments. The weight for each value is adjustable by an administrator. It provides an activity-o-meter on the user's profile page, a block with the most active users and an overview page of users sorted by activity.

User Stats

  ... provides commonly requested user statistics for themers, IP address tracking and Views integration.

Which one(s) you choose really depend on what exactly you want to accomplish (use Views or not, display only post info or login stats, etc).  I'm sure there are more out there that I am missing.

Activity stream modules (on Groups.Drupal.org) contains a comparison about the functionality and architecture of some activity modules.


duplicate order_number in commerce/orders

Finally I found the solution for my problem, the problem came from relation of views to product_order table, I just go to that views and revert views.
and worked


Exposed date filter against >= "today" fails until 5pm Mountain time

Since the server timezone, Drupal timezone, and \Drupal::time()->getCurrentTime() are all pointing to the same time, you have probably been bitten by the same bug in Views that I was, Date/time Views filter tries strotime() relative to Unix epoch.
Basically, all relative values like "today" "yesterday - 5 hours", etc. can have timezone issues in Views.  There's another related issue I reported as well.  This bug has yet to be fixed.
In my case, I needed to filter by "midnight of the current day", and Views was giving me incorrect results depending on the timezone.
I fixed it like this (code more or less pasted directly from my site, but it should give you an idea of what you can do):
function MYMODULE_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  if (($view->id() === 'VIEW_MACHINE_NAME') &&
    ($display_id === 'page_1')) {
    $filters = $view->display_handler->getOption('filters');
    if ($filters['field_MY_FIELD']) {
      $user_timezone = date_default_timezone_get();
      $current_timestamp = \Drupal::time()->getCurrentTime();
      $midnight_usertimezone_datestring = MYMODULE_get_midnight_datestring("$current_timestamp", MYMODULE_get_utc_offset($user_timezone));

      $filters['field_MY_FIELD']['value']['value'] = $midnight_usertimezone_datestring;
    }
    $view->display_handler->overrideOption('filters', $filters);
  }
}


How can I check whether cck field's content is changed in node_update hook?

From documentation:

  Note that when this hook is invoked, the changes have not yet been written to the database

So you can use

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

Then simply compare $node provided to a hook with $old_node obtained from database.


Fetching user account additional field in views global php

Use user_load function to load your account, like so:

$logged_in_user = user_load($user->uid);

Then dpm($logged_in_user) or print_r($logged_in_user) you will see you have access to the field you added.


Taxonomy Term Hierarchy(not programmatically nor content related)

you can use the Views Tree module for this: https://www.drupal.org/project/views_tree

It works pretty well, you just need to use the Tree (list) views FORMAT, add the parent taxonomy term in RELATIONSHIPS, add the parent term's Name field to the FIELDS list, and then use it as the Parent field on the Tree settings:

The module will link the terms hierarchically and output a nested list, and you can always hide the parent term's name field to show just the children terms names.


In the specific example, you should simply write the condition as:

$query->condition('n.language', 'ab', '<>');

In the generic case, where you need to select the rows in a database basing on the values returned from a sub-query, you should consider what follows:

"NOT IN" is accepted as operator from SelectQuery::condition(). In fact, the following query would be executed:

$query = db_select('node', 'n')->fields('n');
$query->condition('n.nid', array(1, 2, 3), 'NOT IN');
$nodes = $query->execute();

foreach ($nodes as $node) {
  dsm($node->nid);
}

As reported in Conditional clauses ("Subselects"), SelectQuery::condition() accepts  also an object implementing SelectQueryInterface as value for $value, such as the one returned by db_select(); the problem is that actually you can just use it when the value of $operator is equal to "IN". See Subselects don't work in DBTNG conditions, except when used as value for IN.

The only way I can see to use the "NOT IN" operator with a sub-query in condition is to:

Execute the subquery to get an array
Execute the main query setting the condition as in the following snippet

$query->condition($key, $subquery_result, 'NOT IN');

$subquery_result is the array containing the result of the sub-query.

Otherwise, you could use where() as others said, which accepts a string for the part of the query you need to add.

Keep in mind that db_select() is slower that db_query(); you should use the first when you know the query could be altered by other modules. Otherwise, if other modules are not supposed to use hook_query_alter() to alter your query, you should use db_query().
In the case of accessing nodes, if you need to obtain only the nodes to which a user has access, then you need to use db_select() and add 'node_access' as tag of the query, with SelectQuery::addTag(). For example, blog_page_last() uses the following code.

  $query = db_select('node', 'n')->extend('PagerDefault');
  $nids = $query
  ->fields('n', array('nid', 'sticky', 'created'))
    ->condition('type', 'blog')
    ->condition('status', 1)
    ->orderBy('sticky', 'DESC')
    ->orderBy('created', 'DESC')
    ->limit(variable_get('default_nodes_main', 10))
    ->addTag('node_access')
    ->execute()
    ->fetchCol();

Similar code is used by book_block_view().

$select = db_select('node', 'n')
  ->fields('n', array('title'))
  ->condition('n.nid', $node->book['bid'])
  ->addTag('node_access');
$title = $select->execute()->fetchField();


How to add link in user menu which is available for loggedin users in drupal

I have taken the easy way out on this one with all my projects. I have two menus, one for logged in users and one for logged out. This works because I can set the 'logged out' menu block to show only to anonymous users, and then I can set the logged in for only authenticated users (in block settings). The solution works great with no custom programming needed!


Unwanted / duplicated temporary css files if CSS Optimization is enabled

I think your problem is about aggregate css files. The issue you give is unrelated. Each page may need a different aggregate CSS file (even in D7, it's much better than it was in D6). It results in hundreds of CSS files as you may state.

Nothing to worry about. Unused file will be deleted automatically. I can't suggest you to use Advagg module because it is only for D6 now, but take a look to have an idea about aggregate files actually work (and how they should work).


CSS for Display Suite Fields not applied

First of all, remove the . from your classes in your HTML code, e.g. you should have
 and not
.

If you want to have one element next to another by using float, your combined element's width should be smaller than their container's. And since both your image and the text are inside divs and a div has 100% width by default, you have to specify a smaller width to each.

.floatleft {
    float: left;
    width: 40%;
}

.floatright {
    float: right;
    width: 30%;
}

Just change the widths accordingly.


One solution is to use the Prepopulate module and then customize the URL to send a privatemsg.  This works well if you are using Views to generate the links, for example.


How to add a view dependency to a Drupal 8 functional test

Sometimes the code in core is not as pretty and consistent as we would like, which can make it a but tricky to find out what is best practice.

For views, it seems that this is pretty consistent. You should create a test module and have the view config yml files be placed inside a test_views folder of the module.

There are examples of this in node and rest modules.


Configuration page for module does not apear?

Got the solution, just have to remove '' from 'MENU_NORMAL_ITEM' because MENU_NORMAL_ITEM is drupal constant for handling Menu Items, after removing '' the code is working as expected.


we had a similar requirement for a site we built recently. In this case we ended up creating a content type representing a "page" with entity reference fields used to pull in the other content to be displayed.

We also used the Entity Connect to make the users' lives a bit easier by providing the ability to add new content from within the page edit form.

So just to clarify, there's one content type you might call a "page" or "container", and several other content types used to comprise its contents. Each entity reference field was laid out in a different area of the page when displayed, and could have multiple values.


Is there a module that can "lazy load" content, not just images?

You can try out infinite scroll. It (lazy)loads the content as you scroll through the page.


How to check the value for specified field across all nodes?

You can make this work by using Rules in combination with the Views Bulk Operations module, as further detailed below.

In what follows, I'm assuming that the machine name of your field is field_optionlist (change to whatever fits).

Step 1 - Create a VBO view

Use the Views Bulk Operations (VBO) module to create a view of all relevant nodes, in which you should:

Add a VBO field to it.
Add a contextual filter for the field_optionlist field for which you want to check that its value is unique. Make sure to correctly configure this contextual filter, similar to what is mentioned in this answer to "How to have a field that counts the nodes submitted by the current user?" (credits to Niall Murphy, merci!).

Include a field like nid for each node (no need for any other fields). Just make sure you get exactly 1 row for each node you want to take into consideration.

Here is an export of such VBO view:

$view = new view();
$view->name = 'relevant_nodes';
$view->description = 'Produce a list of node ids that satisfy a specific filter';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Relevant nodes';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Relevant nodes';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'title' => 'title',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'title' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Field: Content: Nid */
$handler->display->display_options['fields']['nid']['id'] = 'nid';
$handler->display->display_options['fields']['nid']['table'] = 'node';
$handler->display->display_options['fields']['nid']['field'] = 'nid';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: Content: OptionList */
$handler->display->display_options['fields']['field_optionlist']['id'] = 'field_optionlist';
$handler->display->display_options['fields']['field_optionlist']['table'] = 'field_data_field_optionlist';
$handler->display->display_options['fields']['field_optionlist']['field'] = 'field_optionlist';
/* Field: Bulk operations: Content */
$handler->display->display_options['fields']['views_bulk_operations']['id'] = 'views_bulk_operations';
$handler->display->display_options['fields']['views_bulk_operations']['table'] = 'node';
$handler->display->display_options['fields']['views_bulk_operations']['field'] = 'views_bulk_operations';
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['display_type'] = '0';
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['enable_select_all_pages'] = 1;
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['row_clickable'] = 1;
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['force_single'] = 0;
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['entity_load_capacity'] = '10';
/* Contextual filter: Content: OptionList (field_optionlist) */
$handler->display->display_options['arguments']['field_optionlist_value']['id'] = 'field_optionlist_value';
$handler->display->display_options['arguments']['field_optionlist_value']['table'] = 'field_data_field_optionlist';
$handler->display->display_options['arguments']['field_optionlist_value']['field'] = 'field_optionlist_value';
$handler->display->display_options['arguments']['field_optionlist_value']['default_action'] = 'default';
$handler->display->display_options['arguments']['field_optionlist_value']['default_argument_type'] = 'raw';
$handler->display->display_options['arguments']['field_optionlist_value']['default_argument_options']['index'] = '0';
$handler->display->display_options['arguments']['field_optionlist_value']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['field_optionlist_value']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['field_optionlist_value']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['arguments']['field_optionlist_value']['limit'] = '0';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'article' => 'article',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'relevant-nodes';

Step 2 - Create a Rule

Create a rule like so:

Rules Event: something like "Before saving content of type Article" seems most appropriate, though you can use any variation that fits.
Rules Condition: "Check number of results returned by a VBO view". And select the VBO view created in the previous step. In doing so, you will be asked to "specify arguments to pass to the view, one per line. You may use token replacement patterns.". The token to be entered there is node:field-optionlist. If the number of results is 1 or more, then you know the value already exists. So within Minimum number of results you should enter the value 1.
Rules Action: this is pretty much up to your own imagination. For example if the Rules Condition is TRUE, you could use "Set a data value", to restore the value of that field to what it was before, i.e. node-unchanged:field-optionlist. Maybe also display an appropriate message, such as (when trying to change the value from Advanced to Basic):

  The value "Basic" has already been used in at least 1 other node ... (field value remains "Advanced").

Here is an export of a Rule that does exactly what is described above (if you have the Rules UI enabled, and a field with the machine name field_optionlist, you should be able to just import this rule):

{ "rules_prevent_multiple_nodes_with_same_field_value" : {
    "LABEL" : "Prevent multiple nodes with same field value",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "views_bulk_operations", "rules" ],
    "ON" : { "node_presave--article" : { "bundle" : "article" } },
    "IF" : [
      { "views_bulk_operations_condition_result_count" : {
          "view" : "relevant_nodes|page",
          "args" : [ "node:field-optionlist" ],
          "minimum" : "1"
        }
      }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "The value \u0022[node:field-optionlist]\u0022 has already been used in at least 1 other node ... (field value remains \u0022[node-unchanged:field-optionlist]\u0022).",
          "type" : "error"
        }
      },
      { "data_set" : {
          "data" : [ "node:field-optionlist" ],
          "value" : [ "node-unchanged:field-optionlist" ]
        }
      }
    ]
  }
}

Note that my Rules Event is limited to "Article" (change to whatever fits), and replace (prior to trying to import this rule) the machine name of field_optionlist to whatever other machine name your field.

Done!


I had problem like this. You need to increase memory_limit.

For XAMPP: you can change it globaly in php.ini (in xampp located in '\xampp\php\php.ini')

  memory_limit = 8M // search for this "memory_limit" and adjust it by your needs (min 64M)

For WAMP: right click on the WAMP icon, then navigating to the PHP folder/menu-thingy and selecting php.ini, and find memory_limit (like on XAMPP)

After you made a change restart Apache and try to install Drupal from the beginning.


How to get field value after getting a node?

If you want to use node object from entityTypeManager, you need to get current value from the array after loading like below:

$schoolNode = \Drupal::entityTypeManager()
      ->getStorage('node')
      ->loadByProperties(['field_school_id' => $item['schoolId']]);
$node_load = current($schoolNode);
$schoolname = $node_load->field_school_name->getValue();

This is only for a single node. If you have multiple nodes, foreach node as

foreach(schoolNode as $node){
  $schoolname = $node->field_school_name->getValue();
}


How do I define a Drupal variable using phpmyadmin?

The variables are stored as serialised PHP strings so adding one to the database manually might just be a pain. You can do it quite easily though, just follow these steps:

Download and install the Devel module
Navigate to http://mysite.com/devel/php
Put this code in the textfield:

variable_set('drupal_weight_select_max', 1000);

Press the 'Execute' button.

If you do want to do it directly in PHPMyAdmin you can get away with a running a single query:

INSERT INTO variable (`name`, `value`) VALUES ('drupal_weight_select_max', 'i:1000;')
  ON DUPLICATE KEY UPDATE `name` = 'drupal_weight_select_max', `value` = 'i:1000;';

and then flushing your caches.


For periodic import select As often as possible.

Then use Ultimate Cron and make the Feeds & Scheduler cron run every 15 minutes only, this way cron will not do other tasks that you don't need to do every 15 min.


The website encountered an unexpected error. Please try again later( Olivero subtheme)

As @Leigh wrote in a comment one of the cause of my problem is that, sadly, OLivero doesn't support yet subtheming.


There are some PHP settings that can lead to WSOD. These are as follows:

max_execution_time: Apparently, on WAMP, the default is 30 seconds,
but some administrative pages may take longer than that to process
and load.

  Go to XAMPP/php/php.ini and change :

    max_execution_time = 360

PHP Memory Limits: Another common reason for the WSOD is issues with
memory limit.

memory_limit = 128M


how to change widget type of title field in content type Drupal 7

i think, it is better to remove the original field 'title' and create new field for node reference type, use:

<?php
    function your_module_form_alter(&$form, &$form_state, $form_id) {
        if($form_id == 'your_node_form'){
            $form['title']['#access'] = FALSE;
        }
    }

?>


Configuration Settings of Authcache + File Cache

After testing for several settings, I came up with the following configuration:

$conf['cache_backends'][] = 'sites/all/modules/filecache/filecache.inc';
$conf['cache_default_class'] = 'DrupalFileCache';
$conf['filecache_directory'] = '/var/www/clients/client1/web8/tmp';
$conf['cache_class_cache_authcache_key'] = 'DrupalFileCache';

$conf['authcache_builtin_cache_without_database'] = TRUE;

$conf['page_compression'] = 1;

$conf['page_cache_maximum_age'] = 600;

$conf['cache_backends'][] = 'sites/all/modules/authcache/authcache.cache.inc';
$conf['cache_backends'][] = 'sites/all/modules/authcache/modules/authcache_builtin/authcache_builtin.cache.inc';

I am using nginx and just change the $conf['cache_class_cache_page'] to $conf['cache_default_class']. I don't know if I am using the correct config, but this works for me.

And the speed of my server increase significantly when I ab test it.


You want to display a unique block for each user that can be publicly seen right?

Use Display Suite to put a block into a field instead of using Context.

Or, use Contextual filters in views to use the users UID, but that's more complicated and I'm not sure how to do that since I used Display suite. I found something that might help here Views and contextual filter as user id from url


<?php

if (!empty($field->original_value)) {

  $fields["field_image"]->content = '<image:loc>' . $field->original_value . '</image:loc>' . '<image:title>' . $row->field_field_image[0]['rendered']['#item']["alt"] . '</image:title>';

  echo $fields["field_image"]->content;

}


Access a 'global: custom text' field in fieldpluginbase render()

As indicated by @4k4 the solution is using advancedRender() inside a for loop

public function render(ResultRow $values) {
  $items = [];
  foreach ($this->options['field_types'] as $key => $value) {
   if ($value != '0') {
    $items[] = $this->view->field[$key]->advancedRender($values);
   }
  }
$build['theme_element'] = [
  '#theme' => 'dropdownlist-theme',
  '#title' => $this->t('Dropdown List'),
  '#items' => $items,
 ];
 return $build;
}


You should write a custom module that implements hook_form_alter().

Get the $form_id of the 'create new user' form that you want to alter.

( drupal_set_message($form_id); is an easy way to do this. )
Add a custom submit handler to the 'create user' form that uses the respective details and the og_group() function to add the new user to the group.

function MODULENAME_form_alter(&$form, &$form_state, $form_id) {

    if (isset($form_id) && $form_id == 'YOUROG_USERCREATION_FORMID') {
        $form['#submit'][] = 'MODULENAME_submit_handler';
    }

}

function MODULENAME_submit_handler($form, &$form_state) {

    $gid = $form_state['values']['groupID'];
    $uid = $form_state['values']['userID'];

    $account = user_load($uid);
    $values = array(
        'entity_type' => 'user',
        'entity' => $account,
        'state' => OG_STATE_ACTIVE,
       );

    og_group('node', $gid, $values);

    return $form;
}

Just as a point of information, this code sample is geared towards OG 7.2.x.

If you're using OG 7.1.x, you drop the first argument in og_group, so it would be og_group($gid, $values);

Also, the possible $values you can use, and defaults, are as follows:

# taken directly from og.module

$values += array(
     'entity type' => 'user',
     'entity' => FALSE,
     'state' => OG_STATE_ACTIVE,
     'save' => TRUE,
     'force reload' => TRUE,
     'membership type' => OG_MEMBERSHIP_TYPE_DEFAULT,
     'membership fields' => array(),
     'created' => time(),
    );


How do I get the (date)timestamp since last cron run?

A UNIX timestamp of the last cron run can be fetched with:

variable_get('cron_last');

If you need to, you can easily manipulate a UNIX timestamp with PHP's date function.


Webform select option list from another submission data

You could try the sandbox project Webform Views Select.


Create a new user in LDAP, not wherever Drupal normally creates it

You will never be able to use Drupal's core user module without using the database's user table (and many others), without seriously modifying core Drupal.

It sounds like the only reason you want Drupal to not use it's own user + roles + permissions management (and all of the other contributed Drupal modules that depend on the user module) is so that if a user updates some data in LDAP it's also updated in Drupal. If this is the case, find a method for synchronizing your LDAP user info with Drupal's user info.

You can use the hook_user_ functions in Drupal to perform whatever actions you want to happen when a user account is created, updated, etc., in Drupal. For example, if a new user account is created in the Drupal user registration form you'd be performing whatever logic you need (via PHP, or potentially something else) to insert a new record into your LDAP server.


The best way to do this is by using a display mode for the content you are trying to display. The whole purpose of display modes is to provide a way to render content in a consistent way across the site.

The field format for views is meant to provide granular control over the content displayed for that specific view. The best way to clone field formatting is to just clone the whole view and modify it from there; however, the first method is definitely the right way to do this.

[Edit] You can use the Entity View Modes module to create custom displays. Once the display is created, you can manage it from the "Manage Display" tab on the content type. If you need further customization to your display, Entity View Modes allows you to provide a custom template for each view mode.


Schedule Migrate to import XML data regularly

I think the best way to achieve your goal is to use Drupal's cron, not Rules.

Cron is a service that will trigger the execution of a function, depending on the frequency you want it to.

You just have to implement hook_cron in your custom module to execute your migration. You will have to take care of the frequency you need for your script. I found this example useful.

How to run migration programmatically? As stated here, it's very simple:

<?php
  $migration = Migration::getInstance($machine_name);
  $result = $migration->processImport();
?>


Since you're using Views module version 2.12, I looked up that file in the repository viewer:
http://drupalcode.org/project/views.git/blob/42fe4029ca7d7410f15933032a17e979bb0957c4:/handlers/views_handler_filter_in_operator.inc

Looks like line 206 should be:

$form['value']['#dependency'] = array($source => $this->operator_values(1));

I'd try re-downloading the entire Views module. Maybe your copy got corrupted along the way.


How to render comments at the top and the comment form at the bottom?

you attack this line in file :

<?php
    // Remove the "Add new comment" link on the teaser page or if the comment
    // form is being displayed on the same page.
    if ($teaser || !empty($content['comments']['comment_form'])) {
      unset($content['links']['comment']['#links']['comment-add']);
      unset($content['links']['comment']['#links']['comment-comments']);
            unset($content['links']['comment']['#links']['comment_forbidden']);
    }
    // Only display the wrapper div if there are links.
    $links = render($content['links']);
    if ($links):
  ?>
    <div class="link-wrapper">
      <?php
      hide($content['links']['comment']['#links']['comment-comments']);
      print $links;
      ?>
    </div>
  <?php endif; ?>


Moving to PHP 7 require any system change with Drush or in Drupal GUI?

No, there's no action that needs to be taken through the GUI or drush when you change PHP versions.


You could create a Fieldformatter that takes the input and converts it to percentage.


Are there any embedded video/media field modules which integrate with Rules?

You could use a hook_form_alter() to check if a youtube video has been added. Then run rules_invoke_event() to trigger the rule.

Btw, I personally like the Video Embed Field module.


Get pre-processed data from nested Paragraphs

I'd advice not to loop through the render array content, but go directly for the entity object, in your case $paragraphObject = $variables['paragraph']

Once you have the object, you can always query any data you want, to drill through a referenced/nested entity, use ->entity:
$paragaph->hostfield->first()->entity->field_whatever->value

For paragraphs, you can also query upwards:
$parentEntity = $paragraph->getParentEntity()

The example above works similar for almost all entity templates like node.html.twig or paragraph.html.twig and actually wouldn't need any preprocessing at all, since the entity object is passed to Twig:

Most of the time you can use
entity.fieldname.index.value

E.g. for a simple plain text field:
{{ paragraph.field_whatever.0.value }}

For nested paragraphs or referenced entities you can use:
{{ paragraph.hostfield.0.target_id }} /* only numeric ID of ref.ent. */
{% paragraph.hostfield.0.entity %} /* referenced entity object, can be queried again */
{{ paragraph.hostfield.0.entity.field_whatever.0.value }} /* field value of a nested paragraph */

For your hero paragraph you could do something like

{% include 'hero.twig' with { title: paragraph.field_title.0.value } %}


What is the use of node--product_display.tpl.php?

node.tpl.php is the default theme for all content types in a drupal installation.  If you want a specific content type to have different layout/theme you can override by creating a tpl.php file like this node--[CONTENTTYPENAME].tpl.php so for example for ARTICLE content type your would copy node.tpl.php and rename to node--article.tpl.php and adjust the new file to as you desire.

Now Commerce displays a product using a CONTENT type called product display thus to change the look of this content type you will create node--product_dispaly.tpl.php

here is some more explanation of things that you can do inside a node.tpl.php file and (all overrides) https://api.drupal.org/api/drupal/modules%21node%21node.tpl.php/7.x