Using #states to disable a field collection field

My original answer totally missed the point (apologies), this is updated version:

I do not think you can use Drupal's form api #state property to accomplish what you would like. States can be used to hide, reveal and disable whole form elements, such as a fieldset, text input or date field, but you aim to disable one part of a single (contrib) element (ie the second value of a date_combo field provided by the date module).

There are two possible solutions:

load your own jquery when the form is loaded, and add a change() function to disable the relevant date field component
separate the start/end dates into separate date fields and use the drupal #states functionality (as above) to disable the (whole) second date field:

$form['field_certification']['und'][0]['field_validity']['#states'] = array(
'disabled' => array(
    ':input[name="field_certification[und][0][field_auto_calculate_validity][und]"]' => array(
        'checked' => true
    ),
)

);

I hope this helps, I played around with it on a blank d7 install, and this was the only way I could get your intended functionality to work.


Yes, Drupal supports custom pages.
But with different naming conventions
Follow this link of drupal.org https://drupal.org/node/1089656


How to adapt #prefix/#suffix for each option in radio form using hook_form_alter()?

In your form_alter you can tell drupal to use your custom theme_radio like this:

$form['attributes']['#theme'] = 'MYCUSTOM_radio_theme';

Then in 'MYCUSTOM_radio_theme:

$element = $variables['element'];

$element['#attributes']['type'] = 'radio';

element_set_attributes($element, array('id', 'name','#return_value' => 'value'));

if (isset($element['#return_value']) && $element['#value'] !== FALSE && $element['#value'] == $element['#return_value']) {
    $element['#attributes']['checked'] = 'checked';

}
  _form_set_class($element, array('form-radio'));

  return '
<input' . drupal_attributes($element['#attributes']) . ' />
';


How variable_get and variable_set works in drupal

Variables created through variable_set() and variable_get() are stored in the variables table in the database.

variable_set('myvar', 'my_value')
is used to change the value of an existing variable to the provided value, or to create a new variable with the provided value if none exists.

variable_get('myvar', 'optional_default')
is used to retrieve the value of myvar. If myvar does not exist, then it is created using the value from optional_default. If optional_default is not specified, then myvar defaults to Null.


How do I attach a link or image to a radio/select input element

ok, so then you need two parts both stored in a custom module:

an admin interface where the client can upload images for each relevant form element. Use drupal_get_form('FORM_ID') and loop through the form elements. Create a new admin form with image form elements corresponding to the webform elements. save the images and create a mapping table mapping the image urls to the form elements.
an invokation of hook_form_alter() adding prefixes to the webform elements as stored in your mapping table.


How do I set up an article view that validates both article and category?

You can make the Validation through the Contextual filter.
When dealing with 2 Contextual filters it's always best to first fully configure each independently, make sure they work before you add both to work together.

First create the Category Contextual. Since you want to use term names, and not term IDs (only term IDs are stored in ER fields), you have to add the Relationship first for the ER field (require it if you want to show only the results that have this field filled in).

Once you add the Relationship you can add the Term Name Contextual fiter, it will use the Relationship, and configure it:
When the filter value is NOT available
Provide default value
Taxonomy term ID from URL
Load default filter from node page, that's good for related taxonomy blocks
Limit terms by vocabulary
Category
Filter to items that share any term
When the filter value IS available or a default is provided
Specify validation criteria
Taxonomy term name
Category
Transform dashes in URL to spaces in term name filter values
Action to take if filter value does not validate
Hide view
Adjust the Case options, and any other option to your needs.

Test that it's working by entering a name of your category into the View Preview field jazz and checking the results only show nodes with that term. (Preview only tests that Views filtering is working correctly, but it doesn't test passing of the argument to Views because you're feeding them manually, that needs to be tested on a live page.)
Test single word categories first, if they work test complex ones with dashes and adjust the settings if necessary until you get the desired result.
Test that you can bypass it by entering all into Preview, it should show all Views results (you can change it to something else in Contextual settings).
Entering a wrong word (notmycategory) should display No query was run in Views, which means you would get Page not found in live conditions.

Now create the second Contextual, for the Title. You don't have to remove the first one to test the second one without interference.
Bypass the first filter by always entering the all as the first argument into Preview. Once you add the second Contextual you will have to enter two arguments into Preview to test it (all/some-title, or jazz/all, or all/all to bypass both contextual filters).
When the filter value is NOT available
Provide default value
Raw value from URL
3
When the filter value IS available or a default is provided
Specify validation criteria
Basic validation
Action to take if filter value does not validate
Show "Page not found"
Adjust the Case and other options to your needs.

Test the second Contextual by entering various titles in your appropriate Case in Preview: all/my-title and entering the wrong title all/notmytitle to get the "No query was run".

Test that the two Contextual filters are working together, although if they work on their own there shouldn't be any problems combining them (jazz/some-title, notcategory/title, jazz/not-title, etc.)

Once it's working in Views Preview, test everything on the live page to make sure arguments are passed through correctly.

Once all this is said, if all you need is path control in your site you can do that with Pathauto module to create aliases for your nodes based on categories and their titles.
Views only creates lists of content, it doesn't affect the core paths. You will still have the node/ID paths active on your system, and any path aliases you might have. You should take care not to create duplicate paths for the same content, as it can be considered duplicate content by search engines (it dilutes in any case), and it's confusing to users.


I have done something like that with Custom Pagers module in the past.

I was hoping I could achieve the same thing with views and contextual filters but I can't figure it out.


It might be a bit easier to use the API rather than SQL for this. I'd be tempted to load all nodes, loop through all their fields and check values that way. If you hit a paragraph field, recurse and check its fields too.

This is a very rough example function, but it should get you going:

function entityHasFieldWithAbsUrl(\Drupal\Core\Entity\ContentEntityInterface $entity, array $types) {
  foreach ($entity->getFields() as $key => $field) {
    $field_type = $field->getFieldDefinition()->getType();
    $field_settings = $field->getSettings();
    if ($field_type == 'entity_reference_revisions' && $field_settings['target_type'] == 'paragraph') {
      foreach ($field as $item) {
        if ($item->entity instanceof \Drupal\paragraphs\ParagraphInterface) {
          if (entityHasFieldWithAbsUrl($item->entity, $types)) {
            return TRUE;
          }
        }
      }
    }
    elseif (in_array($field_type, $types)) {
      foreach ($field as $item) {
        // Change this to something better...
        if (strpos($item->value, 'https://www.example.com/') !== FALSE) {
          return TRUE;
        }
      }
    }
  }

  return FALSE;
}

And you'd use it something like this:

$nodes_with_abs_urls = [];
$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple();
$types = ['text', 'text_long', 'text_with_summary', 'string'];
foreach ($nodes as $node) {
  if (entityHasFieldWithAbsUrl($node, $types)) {
    $nodes_with_abs_urls[] = $node->id();
  }
}

You probably need to tweak the types to suit your installation, but it should work at a basic level.


multiple views want single search field is it possible in drupal?

You can't use a single exposed filter for multiple views.
There is a workaround though:

Make a new view that displays the three types of nodes you declared before.
Make sure you use "display: content" in your view
Choose a view mode
Expose the name field that is used on the different content types

So it all comes down to using 1 view


How do I load multiple nodes by a user reference?

And like magic, I've found the answer as a result of this answer..

EntityFieldQuery causing column not found PDO exception

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'property')
  ->fieldCondition('field_user_ref', "uid", $user_id)
  ->propertyCondition('status', 1);


I had the same requirements, and I used the Custom search module, which includes a submodule called Custom Search Internationalization : "search content from all or current language only, and all label and selectors translation handling" (note this module provides also several other helpful features like custom search blocks). Works perfectly.


Update drupal module with existing custom changes

You are not supposed to hack modules or core directly, because when you update drupal and modules your changes will get lost.  If you have some valuable changes or corrections that others might benefit from its best to submit a patch to the issue queue of the module and if maintainer accepts them you benefit as well.

If maintainer does not decide to use your changes you can also consider making your own module or perhaps with a custom theme you can  accomplish what you want to do.  Drupal has a great system in place to override parts of code with your own logic without hacking core or contributed modules.

If you actually decide to keep those changes as hacks you will have to do your own merge confict resolution as drupal internal update process or even drush updating will not do it for you.


D8: Best way to implement terms of use acceptance requirement AFTER log in, and gate content if they don't accept?

Specifically, the issue here is that the common Terms of Use modules out there happen during registration rather than after first log in. The problem scenario can arise if you are using a SSO implementation with your Drupal install.

My solution involved creating a module that, as a kernel event, redirected users that had not accepted the terms of use to the terms of use page until they had done so. Once they accepted the terms of use, I gave them a role - "Accepted Terms" - that let me know they were free to go.


Calculate the sum of two form fields with javascript?

Replace your code to next:

<?php
  $form['Contract']['twelfth'] = array(
   '#type' => 'textfield',
   '#title' => t('Plus FEE of:'),
   '#size' => 40,
   '#field_prefix' => "$",
   '#form_panel_row' => 7,
   '#form_panel_col' => 1,
   '#attributes' => array(
      'class' => array('summable'),
    ),
  );
  $form['Contract']['thirteenth'] = array(
   '#type' => 'textfield',
   '#title' => t('For a OTHER PRICE of:'),
   '#size' => 30,
   '#field_prefix' => "$",
   '#form_panel_row' => 7,
   '#form_panel_col' => 3
   '#attributes' => array(
      'class' => array('summable'),
    ),
  );
  $form['Contract']['fourteenth'] = array(
   '#type' => 'textfield',
   '#title' => t('For a TOTAL PRICE of:'),
   '#size' => 40,
   '#default_value' => "",
   '#field_prefix' => "$",
   '#form_panel_row' => 8,
   '#form_panel_col' => 1
   '#attributes' => array(
      'id' => 'totalsum',
    ),
    '#js' => array(drupal_get_path('module', 'YOURCUSTOMMODULE') . '/js/custom.js'),
   );
?>

Don't forget rename YOURCUSTOMMODULE to your module name.

Create custom.js in your module path/js folder:
custom.js:

(function ($) {

Drupal.behaviors.custom = {
  attach: function (context) {
    $('input.summable').keyup(function() {
      var sum = 0;
      $('input.summable').each(function() { sum += parseFloat(this.value); });
      $('#totalsum').val(sum);
    });
  }
};

})(jQuery);

p.s. Don't forget add summing code for inputs in submit function of your form in drupal module, since user can disable JS in browser.


How can I programmatically create a link/URL with querystrings set from parameters?

Let's say if your $args is an array like below:

$args['content_type'] = 'type';

Then you have to append type to it rather than just giving your $id to $args

$args['content_type'] = ['type' => '123'];

Then your overall query will be like:

$this->args = \Drupal::request()->query->all();
$this->args = [$id => $value];
$url = $this->url = Url::fromRoute('<current>');
$url->setOptions(array('query' => $args));
$link = 'toString() . '">' . $label . '';


Try the Commerce Ajax Add to Cart module.

  Using this module you can ajaxify the add to cart operation. The updated cart
  will be displayed without page refresh and a popup message will be shown after you add an item to cart. You can customize the look of the blocks using its template files.


Invoking AJAX on a form messes up my form_alter function

function mytheme_form_node_form_alter(&$form){
    $form['title']['#default_value'] = 'Some value';
    $form['title']['#value'] = $form['title']['#default_value'];
    $form['title']['#disabled'] = true;
}

This should solve the problem.
In HTML, disabled form elements' value will not be sent back to the server so server gets nothing back, which result in a form error if the value is required. Storing value in #value overrides any browser input which is a must (for security purposes) when you disable a form element and expect its value back.


Language links shown enabled for pre-translated nodes

Manually saving those pre-existing nodes does it. Untranslated languages are shown striked out.


Show a Particular Page in Drupal 7 Table Pager

I think theme_pager in your case never know about current page, by which it can decide where to add 'page-current' class.

Try passing 'element' parameter the way you are doing for quantity.

$html =  theme('table', array('header' => $header, 'rows' => $chunks[$page], 'sticky' => TRUE)) . theme("pager", array('element'=> $page, 'quantity',count($table_rows)));

While $page will be less than a value of actual current page value. Please see theme_pager to see how it works.


How to use DefaultSelection::getReferenceableEntities in custom controller?

Okay, it took me over 2 weeks to get to the bottom of this, but turns out, that DefaultSelection::getReferenceableEntities is just a wrapper for Drupal::entityQuery. This becomes especially clear when realizing that DefaultSelection::getReferenceableEntities makes a call to DefaultSelection::buildEntityQuery. And this method is only a complicated way to make a customized query.
So for my purposes, all I had to do was learn about entity queries. Here's how I ended up performing a search:
For taxonomy terms
            $query = \Drupal::entityQuery('taxonomy_term');
            $query->condition('vid', 'my_taxonomy_terms'); //select the collection
            $query->condition('name', $search_term, 'CONTAINS'); //searching the title for a search term
            $term_ids= $query->execute();
            $terms = \Drupal\taxonomy\Entity\Term::loadMultiple($term_ids);  //process the nodes however is desired

            $result = [];

            foreach($terms as $term){
              $result[$term->id()] = $term->getName();
            }

            return $result;

For other entities and nodes
            $query = \Drupal::entityQuery('node');
            $query->condition('field_somefield', 'somevalue'); //optional condition to filter results by
            $query->condition('title', $search_term, 'CONTAINS'); //searching the title for a search term
            $node_ids = $query->execute();
            $nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($node_ids); //process the nodes however is desired

            $result = [];

            foreach($nodes as $node){
              $result[$node->id()] = $node->getTitle();
            }

            return $result;

Reference: https://api.drupal.org/api/drupal/core!lib!Drupal.php/function/Drupal%3A%3AentityQuery/8.2.x


validating the Uploaded Image name in Image field of Content type

function hook_form_alter(&$form, &$form_state, $form_id){
    if($form_id == "YOUR_FORM_ID"){
        $form['#validate'][] = 'myvalidation_function';
    }
}

function myvalidation_function($form, &$form_state) {
    $file_fid = $form['field_your_content_type_image_field']['LANGUAGE_NONE'][0]['#value'][fid];
    $file = file_load($file_fid);
    $file_name = explode( '.', $file->filename);
    if($file_name[0] != $form['type']['#value']){
        drupal_set_message('your validation error');
    }
}

Hope this works. I have tested on my system :)


Seeking a Better way to Create a Collapsible Fieldset

Form submit would not work unless you have an action for it.

You should rather do it in Drupal way, you will need following.

Create Custom Module in drupal.
Block API to create your custom block
Forms API. to create a custom form and call it in your custom block.

Here goes a demo module which will help you understanding the API
https://github.com/arpitr/demo_block_form

Installing the module will give you a block which will look like as


Why would I get a 404 on "Authoring Information" autocomplete?

Most likely because your autocomplete isn't actually using the standard path for the user autocomplete.

From the image, your autocomplete is pointing to /login/autocomplete, a path that doesn't exist in a standard Drupal installation (or indeed one with about 200 contrib modules enabled, I just grepped a couple of large projects).

The correct path for the user autocomplete is /user/autocomplete.

Presumably there's some custom/contrib code changing the autocomplete to a different path, but failing to actually implement that path.

The best thing to do would be to search your codebase for the string login/autocomplete and go from there.

UPDATE

The change might be being made by the User Tweaks module:

function user_tweaks_form_alter(&$form, &$form_state, $form_id) {
  if (user_access('view login autocomplete')) {
    switch ($form_id) {
      case 'user_login_block':
      case 'user_login':
      case 'user_pass':
        $form['name']['#autocomplete_path'] = 'user/login/autocomplete';
        break;
    }
  }
}


In ajax view, by default this functionality is already there. When you click on ajax pager it will automatically scroll to top of content. If it is not working check your console for is there any error showing.


View using views content pane not updating on node save

Take a look at the Views content cache module.  It allows you to expire the views cache on add/edit/delete of nodes in your view.

Also, be sure to look at the Panels caching on your home page, whether that be in Page Manager, or Panelizer, you can set caching on items in Panels using the Panels Content Cache module.


{{ front_page }} doesn't work in partial

Try:

<a href="{{ path('<front>') }}" title="{{ 'Some Title'|t }}" rel="home" class="some-class">
     Some Text
    </a>


Node titles disappear sometimes when using tokens with Autonodetitles

Upraded the site to latest version of Drupal. The problem got resolved automatically.


How to how a table with previously collected data in a custom form page?

Yes you can do this.
First of all you need to fetch the 'Table1' data in top of the form.

$query = db_select('Table1' , 'tb');
    $query->fields('tb');
    $results = $query->execute()->fetchAll();

//table structure

$Details = '

	Employee Id	Employee Name
';
    foreach($results as $res)
    {
        $Details .= ''.$res->empid.'	';
        $Details .= '$'.$res->empname.'	';
    }

$form['details'] = array(
        '#type' => 'item',
        '#markup' => $Details,
        '#suffix' => '
'
    );

$form['eid'] = array(
    '#type' => 'textfield' ,
    '#title' => t('Employee Id'),
    '#maxlength' => 45,
    '#required'=> true,
);
$form['ename'] = array(
    '#type' => 'textfield' ,
    '#title' => t('Employee Name'),
    '#maxlength' => 45,
    '#required'=> true,
);

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


School needs to have a nodereference field pointing to teacher. Then, as tim.plunkett said, you need to make the number of teachers node reference field to unlimited.
Same as the one detailed here, but the number of values set to unlimited.


Why drush is not maintained in drupal.org?

The motivation for moving to GitHub is discussed on our wiki page:

  Drupal.org is poor fit for Drush as we get features we don't want on our project page

  Usage statistics (Drush isn't a module and thus can't report usage)
  Release names must map to a single Drupal version
  The issue to fix this stuff is nearly five years old.


How do I return an SQL query result as custom variable in a template?

You can add variables using a hook_preprocess_THEME() function. For example, if you are trying to add a variable to the page.html.twig template, the theme hook is page. So you would use the following:

function hook_preprocess_page(&$vars)
{
  // Add your result to the $vars array:
  $vars['some_variable'] = db_query('SELECT something FROM {some_table} WHERE some_column = :some_value', [':some_value' => 'some value'])->fetchField();
}

Because you've added some_variable to the $vars array, some_variable will be available in your template.


If you don't want to add CSS you can comment out the $messages variable in your page.tpl.php file while you are developing.


How do I create a "platform" and "site" from CLI, using the drush extension provision

There is a good article on this question in Aegir official documentation here:
http://community.aegirproject.org/content/manage-your-aegir-system-command-line


What does exacly mean by Entity CRUD API?

The CRUD API is the set of functions that allows an entity to be Created, Readed, Updated and Deleted.

An entity has a CRUD API when its entity controller implementes de EntityAPIControllerInterface. The EntityAPIController class, the default Entity API entity controller class implements this interface.

So you only have to define your entity using the Entity API contrib module and use that class as controller (or your custom subclass of that class).

If you read the entity_export code you can see:

 if (in_array('EntityAPIControllerInterface', class_implements($info['controller class']))) {
    return entity_get_controller($entity_type)->export($entity, $prefix);
  }

The function checks if the entity controller implements EntityAPIControllerInterface interface; if yes the export method is called.


How do I change the output of theme_comment_submitted()?

Add a function in your template.php located in your theme's directory.

function phptemplate_comment_submitted($comment){
  return t('Submitted on @datetime by !username.',
    array(
      '!username' => theme('username', $comment),
      '@datetime' => format_date($comment->timestamp)
    ));
}


Code running in one theme but not the other

Themes are highly cached. That's a reason why you should avoid logic in them if only you can. And if you have to, put it in template.php, not .tpl files. Probable reason of query not executed is that template got cached and Drupal sees no reason to evaluate files again. You could force it to, probably, but it would be a huge performance killer.

Move your queries to contrib module, and query-based logic to template.php and you'll be good.


drush Invalid argument supplied for foreach() backend.inc:709

The cause of above error is that @sites is returning no sites.

Try drush sa @sites too, and see what it says.

Note, however, that @sites refers to all of the sites in a multisite install; it does not refer to all of the sites in your aliases.drushrc.php. If you rename your aliases file to foo.aliases.drushrc.php, then @foo will reference all of the aliases in that file.

Else check this as well: https://www.drupal.org/node/1031170

Reference:
https://www.drupal.org/node/161698


With Drupal 7, you do not need to do so!
Drupal file paths are stored using stream wrappers so you can simply change the folder path in Admin > Configuration > Media File System and move the existing files to new folder and you are ready to go!

You will see public://images/my.png like paths in files table and many other locations. These are the stream wrappers used in Drupal 7.

However if your content has links hardcoded, they will not change.
Try adding the following line right below the

RewriteEngine on
RewriteBase /

lines.

RewriteRule ^sites/default/files/(.*)$ http://www.example.com/files/$1 [R=301,L]


Change crop focus for specific styles on certain existing images

For my purposes, Manual Crop was the best solution.


Drupal provides a specific way to add JS to a page, to ensure that it is run whenever content is loaded into the DOM. This way, it will run after the document is loaded, but also after AJAX operations.

They're called Drupal behaviors.


how to `absolute` position an image over another image?

Well, there's a couple of things going on, and I don't want to approach re-designing how you've implemented your DOM for this page. Looking at your HTML in question:

which renders this:

You've wrapped your two inline IMG elements within an inline A element. Inline
elements are not meant to moved around in block-like fashion. One approach is
to redefine your anchors here as blocks. We'll also need to define a height
and width for the parent element, as the redefining of imgs to blocks,
absolutely positioned, will remove the parent elments ability to calculate
height and width. Position: absolute removes the object from the page's flow.
(I presume height 200px and width of 220px is accurate, if not, correct to
taste.)

Here's the key aspect: the parent DOM item must be "position: relative" which
you must explicitly declare. THEN the child elements may be positioned
absolutely, within where ever the parent element falls on the page.  The parent
div will move as it needs to on the page, moving the absolutely positioned
child imgs within it.  Otherwise, your css will traverse the DOM backwards to the
first position:relative element. Not finding one, it uses the HTML element for
positioning. The other thing to consider is that img is an inline element, not
a block element. So you must redefine it as a block.  Finally, notice the
z-index forcing the graphic callout to overlay the featured graphic.

This refactored code shows what you're looking for:

Which renders this:

Of course I wouldn't do this with in-line styles, I'm just being lazy to get my thoughts up quickly. Finally, I wouldn't use a table for that display element, I'd use an unordered list. But that's for a different discussion.


How to show custom error messages below text field?

You need go to your theme's template folder and edit page.tpl.php'

Look for <?php print $messages; ?> and move it below <?php print render($page['content']); ?>

Thanks for the note @Kevin. If you wish, you can add if statements around the <?php print $messages; ?> that check the page url and/or content type if you need to have them appear below only for certain pages.


Why does updating newly added field collection on hook_field_collection_item_insert fail?

You can only set the host entity while creating the field collection item (as your exception also states).

What you can do however is use $fc_wrapper->value()->updateHostEntity('node', $node); before you save the $fc_wrapper.
For that to work you will first have to load your host entity node of course (node_load() will suffice).

Hopefully this gets you on your way.


What's the difference between the 2 different Rules pages in admin?

Entity Rule is not alternate to Rules

It simply acts as component which is, it allows you to set certain conditions and action on it and then this component can be picked by rule to run on certain event.
It gives another interface for rules action on "Entities" so you do not have to have rule administration permission if you belong to a role who has administration permission for certain entities.

  When do I use one over the other (to send emails when nodes are
  added/edited)?

If you want a user role with administration permission of content, and you do not want to confuse or simply give them permission to see all rules on site but you still want them to configure their entity specific rule, use entity_rule module.
You can also it for sanity of configurations, as it will bundle rules specific to entity on entity page, keeping default rules page more cleaner.


Sorry for the confusion. Clarification:

Copying over the hashes from D7 to D8 works (I made a mistake with a backslash in the JSON output)!

So just copy over the D7 hashes (starting with $S$) from the D7.users.pass field to the D8.users_field_data.pass field. It will work. The first time, that the users logs in to the new D8 site, the password gets rehashed with the D8 algorithm (PhpassHashedPassword.check() and PhpassHashedPassword.needsRehash() are doing the magic).

Everything is fine :-) Thanks.

EDIT: Someone requested the code for this...

Here is my controller class that imports all the Drupal 7 users found in the file asde2.users.json:

  public function importAsde2Users() {
    // load asde2 user file
    $usersfile = $_SERVER['DOCUMENT_ROOT']."/".drupal_get_path('module', 'preosuser')."/asde2.users.json";
    PxLog::debug($this, "Loading asde2 users file ".$usersfile);
    // decode json array of objects
    $users = json_decode(file_get_contents($usersfile));
    PxLog::debug($this, "Found ".count($users)." Users in that file");
    $database = \Drupal::database();
    // import all of them
    foreach ($users as $user) {
      $newuser = \Drupal\user\Entity\User::create([
          'name' => $user->name,
          'pass' => $user->pass,
          'mail' => $user->mail,
          'status' => $user->status,
          'init' => $user->init,
          'created' => $user->created,
          'login' => $user->login,
          'access' => $user->access,
          'uid' => $user->uid,
        ]);
      $newuser->addRole("xx");
      $newuser->addRole("yy");
      $newuser->save();
      // dirty overwrite re-hashed hash
      $database->merge('users_field_data')
        ->fields(['pass' => $user->pass])
        ->keys(array('uid' => $user->uid))
        ->execute();
    }

    return ['#markup' => "Created ".count($users)." Users with that file", '#cache' => ['max-age' => 0]];
  }

Have fun.


By default, Drupal (and Webform) show the error message as Field_name is required, so if you want to show an error message that uses something other than field_name, you will have to override/write your own validation function.

The Webform Validation module may be of assistance here, particularly the code examples for custom validation hooks.

P.S. "本文メッセージ" is probably a mistranslation; it most likely should be flipped ("メッセージ本文", "message body").


That directory must be writable by the usre that runs the web server (apache, for example).

So you have to:

go to admin/config/media/file-system and check the path of public files (may be sites/default/files)
check which user runs web server (on Ubuntu could be "www-data", on centos/fedora/redhat could be "apache")
using a terminal go to the document root of drupal and set the owner of the directory:

  sudo chown -R www-data:www-data sites/default/files (or apache:apache)

if you couldn't use a terminal, use the ftp client or contact your hosting provider

PS: this instruction works on *nix servers


You can add user forms by creating a render array for the Form API and print render($form) in a custom template, but I would just use the Webforms module and include all elements in a Panel or View.


Problem displaying second level navigation in menu block

I don't sure if you are using only Drupal standard menu system or any menu modules. If not, check Menu Block module.

This module gives you lot of options to place menu in blocks, including just some parts of a certain menu as I think you want.

For example, you define a block that shows the second-level menu of the current fist-level active item.


How can I create a product with a single variation for a store?

The code in my example was fine.  In my product variation's display I was rendering the product entity, and in my product entity I was rendering my variant.  If anyone encounters multiple copies of their product rendered, check how the fields are rendered in the display.


How to retrieve a file or image from a content type?

Yes, this is an annoyance, no doubt.  Drupal stores the uri using a public:// streamwrapper. Thankfully, someone has written the code to resolve that into a full url that gets attached to the file object for you whenever one's loaded: https://www.drupal.org/project/full_url_file_info


How to combine values of same field in a single column of a chart created with Charts?

Edit: The module now shows individual values for each company and takes the company's latest published version's vales. So, if I made another entry for Company A and it's published, the chart will only show the latest version's values. I've also edited the body and included a picture of the final result.

It looks like building a custom module answered my own question. I had to code a module with the charts API and create a custom block to show the data (it was a huge pain writing the functions and retrieving the data).

Instead of adding all the values into one column, what I've done is take a company's values for each year, place it on the chart, and other company values stacked on the previous company values as shown here:

To anyone else now or in the future with the same problem as me, here's a code snippet that I used:

$chart = array(
 '#type' => 'chart',
 '#chart_type' => 'column',
 '#stacking' => TRUE,
);

Include the code ^above in your function that displays the block/module.

You will need to make your own functions and may be you'll need to implement some of the functions as shown in WD Tutorials for Drupal.

Also, for getting the field data, I made a function that shows all the years (in sequential order). I made several variables: holding a result of an array to store the years, counters (for an array counter, year counter, etc.), an offset for the current year, and a variable for a hard limit (having an arbitrary hard limit is bad). I made use of two while loops that checked to see if the data field (e.g. field_data_field_(insert name of field)) to check if it exists and to see that year contained any rows (indicating that having any values in the table shows that it exists).

As for the other functions, I made separate functions such as filtering duplicates, retrieving all node IDs that are Company content type, and getting each of the node's ID values.

For anyone that's stuck on Drupal's PHP syntax, I would suggest looking at PHP first and then comparing it to Drupal's PHP documentation (confused me at first).

Thanks to all that offered me help during the process. It got me thinking better.


You can try using module Field group views

Project page says

  Provides a view format for Field group.

  In other words, a field group can be displayed using a view. One
  possible usecase would be to generate a table using fields as columns.


Is there a way to style the main-container without it effecting ALL the site?

You can do it using the CSS. First on whichever node you want to do, find its specific class given when you create that node (How: right click on the page and Inspect element in the code ........., you will find the several class, one of which is specific for that node). Now take that class. Now suppose if you want to change the main-content with that node only and do not want to change other, use following selector in css,

.specific-page-node-class #main-content {your css code}

This will apply change to main content of that specified node only and do not change to other.

Credit: Link for detail question and answer which I asked on same topic on the Drupal answer, I have summaried above


How to add as exposed filter a product attribute in Commerce's orders view?

Product's attributes are set through the product variation. You need to add the Variations through a relationship and you will have attributes available there.

After that your attributes can be added as exposed filters.

Sorry I don´t have any English sites available but pay close attention to captures.


Adding multiple taxonomy terms to a node via code

The object orientated way would be to use appendItem() from FieldItemList:

$node->field_tags->appendItem([target_id => '1']);

But as the field object provides an array interface you can add items to the field the same way as in a php array:

$node->field_tags[] = '2';


After searching in the core files I found the pattern, see the example below:

use Drupal\Core\Url;
// The entity type can be 'node'.
$entity_type = 'taxonomy_term';

// Find the bundle entity type, e.g. 'node_type' or .
/** @var \Drupal\Core\Entity\EntityTypeManagerInterface $etm */
$etm = \Drupal::service('entity_type.manager');
$bundle_entity_type = $etm->getDefinition($entity_type)->getBundleEntityType();

if (NULL === $bundle_entity_type) {
  // Not clear what to do in this case.
  return NULL;
}

// The bundle can be 'article'.
$bundle = 'tags';
// The route, see that the $entity_type variable is used.
$route = "entity.entity_view_display.$entity_type.view_mode";
// The view mode can be 'teaser'.
$view_mode = 'full';
$a = Url::fromRoute($route, [$bundle_entity_type => $bundle, 'view_mode_name' => $view_mode])->toString();
// To use dpm() you need the Devel module.
dpm($a);


Is there a way to add content templates for blog

Go to Manage fields

Ex: /admin/structure/types/manage/article/fields

Then click on edit, for example, the body field. Look for Default Value and put whatever you want there.

Now when a user tries to add a new article, it will have the body pre-filled-out and they can change it if they wish.


How do I control what to publish as Facebook Instant Articles?

You can for example add a taxonomy to the articles and filter by that in the view.


Why does Drupal store each custom field in a separated table?

Because you can reuse the fields and attach them to more than one content type for example.

You actually get 2 tables for each field: one for storing the current version of the data (field_data_field_MACHINE_NAME), and the other one for storing the "historic" (if revisions are enabled) values (field_revision_field_MACHINE_NAME). Some content types can have enabled revisioning, meaning that shared fields need to be "flexible" enough to follow up with that, but at the same time store the values for content types with disabled revisioning.

If you had everything in one big table for content types (I think D5 did this), it would be a really big mess to manage, especially if you would share fields between entities (e.g. nodes and users).

Few suggestions:

See this answer by Clive for more information.
Inspect this on a clean install just to see how it works. Create 2 content types, add some fields (share some of them) and track what has been changed and how is the data stored in the database. You could probably dig some documentation page, but I think this is the best way to understand the schema.
Reuse the fields whenever you can in order to optimize the database more. Be aware that there might be some limitations (e.g. list options, file uploads, required or not, etc.) that will not let you customize fields for every instance, so you will have to create new ones.

I wrote this fairly quickly, but I hope I managed to explain it.


wysiwyg ckeditor inline styling not working

Verify the format used by the body field. If you are using Filtered HTML, filtering is done before rendering it on the page, where all inline styling is removed.

You could either set your format on Full HTML (which doesn't filter the body) or use the WYSIWYG Filter module which allows to enable certain inline styles on the Filtered HTML format.


How can I get the email address of a user who has just registered?

The docs on the core entities are really good. Here are the docs on the User class.

You should be able to get the email with:

$email = $account->getEmail();

And the created time with:

$created = $account->getCreatedTime();


Using Feeds importer to import separate urls to same content-type

If you don't find a direct solution to this issue, try set an unique field on the content type instead and use that instead of an UUID. Have a look at Support unique targets in mappers


Why cache form table gets new entries by anon page views?

Comment form is a form. All forms generate entries in form cache. Form engine uses cache as it's temporary data storage, not as the cache in usual definition of the word.

One thing it always store is a list of fields it actually displayed to a client, so it can compare it with a list of values that come back and prevent hijacking and other abuse - hence one entry per user session per form.


Prevent enabling module if private streamwrapper not set

The hook_requirements(), what do you need.

Implement it your own modules .install phase. Here is an example from one of my module: http://drupalcode.org/project/jquery_localscroll.git/blob/refs/heads/7.x-1.x:/jquery_localscroll.install#l20


How to get the current path, keeping the langcode?

You can try code:

$langcode ='en';
$node_url = $node->getTranslation($langcode)->toUrl('canonical', ['absolute' => TRUE])->toString();


I tested your code locally and the way you are adding the class did work for me. E.g.
function mymodule_preprocess_views_view_unformatted(&$variables) {
  $rows = $variables['rows'];

  foreach ($rows as $id => $row) {
    $variables['rows'][$id]['attributes']->addClass(['test-123', 'test-abc']);
  }
}

... worked fine for me. I'd say your var_dump() is not giving you the full picture.
Try this instead:
var_dump($variables['rows'][0]['attributes']->__toString());

When I var dump with toString() - I see the class indicated in the output - hopefully you will too
/var/www/mysite/docroot/modules/custom/my_module/my_module.module:149:string ' class="card test-123 test-abc"' (length=31)


Search order by publish date or custom field

I assume you are using the core Search module. For this kind of functionality I prefer using the excellent Search API module. There are other modules as well such as Solr but with increased complexity.

The core search module indexes only node title and body. Using the module not only allows you to index other fields but also to present the results in any fashion by creating a custom view with the Views module.

In order to use Search API, you need a backend such as the Search API DB module. This needs to be installed and activated along with Search API as well.

In order to create a custom page of results:

Create a search server in Search API configuration
Create an index with all relevant fields THAT you are going to use in the view (next) as well
Create a new view of type index
Add an exposed filter 'Fulltext Search' if you wish
Add any fields you wish to present, usually the rendered entity field (teaser)
Sort by any field you prefer to.


BOA installation caching does not refresh

Please make sure you are using latest BOA stable
Make sure you have configured custom Speed Booster TTL properly (INI or code)
Note that default is just 10 seconds, so there is no way it can cause such issues
Disable Purge+Expire modules, unless you are forcing long TTL
Check the docs at: https://omega8.cc/node/108 for working code examples
Make sure it is not some other caching layer (Views?) which adds confusion

I hope this helps.


No. Display Suite is not compatible with Commerce Products.

Commerce issue: https://www.drupal.org/node/2723689
Display suite issue: https://www.drupal.org/node/2725077


How to implement a jscript for displaying custom ads

Upload your .js file in your theme directory.
In your theme's .info file add
scripts[] = path/file_name.js  as follows.

This will include the .js file in each page of your site. Path of the .js file is relative to the .info file.


Programmatically set URL Alias when creating node in form plugin

The node widget currently only shows aliases that have the same langcode as the node. https://www.drupal.org/node/2511968 will change that and also display aliases without a specific language.

But if the alias also doesn't work on the site then that sounds like something else also isn't correct yet. Does it work in that block if you create an alias manually in the UI? If so, compare the two records in the url_alias table, do you see a difference?

You can create an alias as part of saving the node, there is a path pseudo/computed field. Try adding this to your array:

'path' => [
  'alias' => '/mypath/' . $title,
  'pathauto' => PathautoState::SKIP,
]

That should create the alias correctly as well.

And last, if your alias is so predictable, you should look at Pathauto. That allows you to set up rules for creating aliases. Among other things, it has a ton of logic to deal with special characters and duplicates, your code will have a problem if you have two nodes with the same title, for example.


How to add Parent and Child to a Views 3 table format using Groupping Field?

Starting from scratch with a dummy content type that contains just a title and a taxonomy term.

1) Create the simple taxonomy: Category_hierarchy {i.e. 1, 1.1, 1.2, 2, 3, 3.1};

2) Create the simple content type. {title, taxonomy [Category_hierarchy];

3) Create the view:

  Format: Table
   + Settings
  - Grouping field Nr.1: Category_hierarchy

  Fields
  + Content: Title
  + Content: Category_hierarchy
      -- Exclude from display.

  Sort criteria
  + Content: Title (asc)

  Relationships
  + Content: Taxonomy terms on node [1]
      -- Vocabulary: Category_hierarchy
      -- [custom] Identifier: Category_hierarchy_child

[1] This is the only taxonomy-type Relationship available.

Results show the node titles grouped by the child relationship as expected.

4) Revisiting the View now that we see what we can simply construct, we try to get the parent term added to the display. Now, under the Relationships section is a whole new list of options titled "Taxonomy term". So we add one more to get the missing relationship, parent.

  Relationships
  + Taxonomy term: Parent term
      -- Relationship: Category_hierarchy_child
      -- [custom] Identifier: Category_hierarchy_parent

If we peek into Table's settings, we would hope this might make the new relationship an available option under Grouping field Nr.1. But the grouping field options are still only Category_hierarchy and Title.

Just to be sure I added Grouping filed Nr.2 with Category_hierarchy to see if Views can do something magical and sort out the relationships automatically.

Nope. But it was worth a try. Its clear there must be some other way to populate that menu. Maybe Views has made some kind of magical field we can add from under Fields?

And that's just what has happened. We now have a new type of available field, 'Taxonomy term':

Taxonomy term: Name
 - The taxonomy term name.
Taxonomy term: Rendered Taxonomy term
 - The Taxonomy term of the current relationship rendered using a view mode.
Taxonomy term: Term description
 - The description associated with a taxonomy term.
Taxonomy term: Term edit link
 - Provide a simple link to edit the term.
Taxonomy term: Term ID
 - The tid of a taxonomy term.
Taxonomy term: Weight
 - The term weight field
Taxonomy vocabulary: Description
 -The taxonomy vocabulary description
Taxonomy vocabulary: Machine name
 - Machine-Name of the vocabulary a term is a member of. This will be the vocabulary that whichever term the "Taxonomy: Term" field is; and can similarly cause duplicates.
Taxonomy vocabulary: Name
 - Name of the vocabulary a term is a member of. This will be the vocabulary that whichever term the "Taxonomy: Term" field is; and can similarly cause duplicates.
Taxonomy vocabulary: Vocabulary ID
 - The taxonomy vocabulary ID

I've crossed out the unlikely candidates. And added each, in turn, to the Field section and looked for the field in Table's settings. Good gravy. They both worked!

I certainly don't expect tutorial answers. But I was already writing up a bug report for another problem I encountered so, my bug is your gain.


How to set up a view containing a list of events ordered by date

In the view, you may configure the fields you want to show (assuming you want a list of unformatted fields, for easier theming).

You just pick fields as title or date start/date end, so you have them available when the view is processed.

Having them available, the rest is up to you, your project requirements, and twig :)


Command entity-updates needs a higher bootstrap level to run

Same problem here.

In my case I discovered that drush uses native mysql commands, not php lib. Then I've installed by

  apt-get install mysql-client

and works great.

For windows users, I think must install mysql cli commands here.


node_access check against array of node ids

How about adding checking if the node has reference of current user while fetching related nodes.

So,

$related_nodes = <get_related_node>;

  // Might look Dumb
  function get_related_node($user=NULL) {
    if(is_null($user)) {
      global $user;
    }
    db_select('node','n')
     //Your existing joins
     // One more join for the user reference field, :O
     ->leftJoin('field_data_userreference','ur','ur.entity_id=n.nid')
     // your existing conditions for query.
     // One more condition for the current user as the value on the field.
     ->condition('ur.entity_id',$user->uid,'=')
    // And the execution continues.
  }

Fields mahcine names to be fixed as per the names provided. It should filter your reference nodes while fetching.


How to override other module function/hook from my custom module?

In general, if a module does not provide a hook, some other will do.
You could check if some hook in core fits to what you need to do.
Depending on what is the final result of your data change, you could perform it after a module generates the data to be changed, and before the data gets saved, for example.
By another hand if a module already uses the same hook you want to use it is still possible to rely on the weight of your module to be sure it will run afterwards.
By the description of your specific requirements (login a user and create a user) hook_user_login and hook_user_presave could be used.


grouped paragraphs by field not filtering to current language

Might've just found the answer to my own question.. there are TWO places that the language needed to be edited. At bottom of the center column in Views admin, there's another language option for the view itself. I had to set this "Rendering Language" to "Content language selected for page"
Then the other language paragraphs disappeared.


How to implement StackMiddleware for a redirection correctly?

I recently implemented this myself and had to do a fair bit of research and experimenting to get it to work. I too had many of the same questions you have so I've tried to answer them from what I've discovered.

Do I need both an EventSubcriber and StackMiddleware to accomplish this redirection and intercepting of page caching?

You will only need the "StackMiddleware" to intercept the page caching. It should replace "EventSubcriber" if that already exists.

Do I have to create a separate custom module to implement my StackMiddleware class?

This can be achieved in the same module.

How do I use my redirection code (which I know works) with this StackMiddleware class so I can intercept the page cache

The redirection function should be a called like so...

public function handle(...) {
  ...
  $this->checkForRedirection();
  ...
}

Have it run on every page(so it always checks to see if user is authenticated)?

In my case the user object wasn't available because the middleware runs prior to any user data being set. What I did have was the Drupal session cookie which I could check against. This cookie is set and unset depending if the user is authenticated or not. This may not be the most robust solution so others are welcome.

--
I found this article which was great for getting some of the foundations working:
https://chromatichq.com/blog/replacing-hookboot-and-hookinit-functionality-drupal-8


Download and install the Entity Reference module
In parent user fields, add a field with Entity Reference and a widget of Auto complete (tag style)

For example: I named mine lalala (click picture below to enlarge)

For Target Type, select User
Number of Values: Unlimited (as parent could have more than 1 child)

Then go to the parents account and start typing child's account user name, you will see the name in the drop down, select it and save.

Use a comma , to add other child account. (parent has more than 1 child)

In your view

contextual filter of User id (uid) (which uses the parent's id)
add a relationship of lalala Referenced Entity

If not, try Referencing entity, but if my memory is correct it's Referenced


Custom CCK Currency exposed filter for available currencies

function mymodule_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'views_exposed_form' && $form_state['view']->name == 'myview') {
    // Add our custom All buttons.
    $form['field_1hour_currency']['#type'] = 'select';
    $form['field_1hour_currency']['#options'] = array(
      '' => t('<Any>'),
      'USD' => 'USD',
      'EUR' => 'Euro'
    );
  }
}

The key is to ensure you include the empty option:

'' => t("<Any>")

See http://drupal.org/node/463990

You may want to post this solution on your issue on drupal.org too if it works for you: http://drupal.org/node/1155934 ;)


Deployment using Composer replacing old style install but issues with legacy Drush

As @Jaypan commented, globally you only need the Drush Launcher as phar file. And remove the old globally installed Drush version, this install method via composer global require is no longer supported. If you still need a legacy Drush version for other Drupal sites, download it the same way as phar file, see http://docs.drush.org/en/8.x/install. Which then can act as launcher by the way, so you don't need the Drush Launcher in this case.


Domain Access force node redirect to proper domain

There is a special module for that: https://www.drupal.org/project/domain_path_rewrite.

The idea is to check the request path before the page load and to make a redirect to the proper domain if needed. Something like:

/**
 * Implements hook_init().
 */
function domain_path_rewrite_init() {
  if ($domain_path = _domain_path_rewrite_domain_path(current_path())) {
    global $_domain;

    if (!($_domain['domain_id'] == $domain_path['domain_id'] && request_path() == $domain_path['path'])) {
      drupal_goto($domain_path['url'], array(), 301);
    }
  }
}


D8 services errors - No route found for the specified formats : */*

If you update to the next beta, You will have to use: "http://dev-d8go.pantheon.io/d8go/node/1?_format=json"


Feeds: How to import images using CSV Node Import?

I don't think it will work based on local files. The way I understand it, feeds is made to work off CSV data, with files that are already on the server.

It will take a bit of playing around on your part, but your best bet is to upload a single product/node with an image.  Find the path to that image. Once you find the folder where your image is being stored, upload your images to that folder.

Then give the direct path to the image on your server in your CSV file, in the image section. The path will probably look something like this, depending on the how you configured the image field. This example is from a Drupal Commerce site:

example.com/sites/default/files/styles/uc_product_big/public/image-you-want-to-use.jpg

If your server runs some sort of post processing (image-resizing, cropping, scaling), and then saves in multiple folders, I'm afraid you're out of luck with this method.


Sounds like you're looking for something like Time Period.

That one stores the interval in seconds, so if you need smaller values you will probably have to write your own field widget/formatter but the module might still serve as a base.. or maybe you could extend it to cover this use case as well and e.g. store microseconds.


If a search yields no results is it possible to show an alternative set of results?

It is possible: Under the "Advanced" panel of your view (collapsed to the right of the screen), add a new behaviour to the "No results behaviour", then add a "Global: view area" reaction. You can add any view there.


how to deploy from dev to staging and production?

Any deployment strategy can be broken down primarly into three main streams

Content(Node,taxonomies etc.)
Code
Configuration(Content types, Vocabularies etc.)

Content Deployment

I am assuming you are not targeting content deployment as part of your deployment. Its a complex peace based on your content strategy.

Configuration Deployment

Configuration Deployment, since content and configuration are kind of tightly coupled till Drupal 7, there is no way out of the box you can just keep the configurations in sync. But there are couple of modules which let you pull your configuration into code, features is definitely one and I believe most widely used module for deployment.
Sometime you can not get all the configurations just by features module, there is another helper module strongarm module which will let you exporting variable configurations by contributed module.

Just wanted to bring the keypoints for feature module.

Features module let you bring the configuration in code.
Either you update your feature or revert your feature based on if you want to get the configurations as in feature code and revert any manual override configuration we do feature revert, if you want to get the manual updated configuration in feature code we do feature update/recreate.
Feature module compares the configuration in code and configuration in database, based on it features allow to revert/update.

Code Deployment

For code any versioning tool will do the job.


How do I change the admin toolbar search input box to type=search?

The following hook works. I found it by text searching the project

function mytheme_preprocess_input(&$variables, $hook) {
 if ($hook == "input" && $variables['attributes']['id'] == "admin-toolbar-search-input") {
   $variables['attributes']['type']  = "search";
 }
}

It does not solve the icon problem in this case. The icon is in a different DOM element.

The fix to the search icon being over the text was

#admin-toolbar-search-tab input:focus + .icon.is-left {
 display: none;
}


How to discover the currently active twig template

With the help of Clive's comment, I managed to identify the active theme suggestion.  Code below.

function mymodule_preprocess_field(&$variables, $hook) {
  $theme_suggestions = mymodule_get_theme_suggestions($hook, $variables);

  $active_suggestion = mymodule_get_active_theme_suggestion($theme_suggestions);
}

function mymodule_get_theme_suggestions(String $base_hook, array $variables) {
  // Invoke hook_theme_suggestions_HOOK().
  $suggestions = \Drupal::moduleHandler()->invokeAll('theme_suggestions_' . $base_hook, [$variables]);

  // Invoke hook_theme_suggestions_alter().
  $hooks = [
    'theme_suggestions',
    'theme_suggestions_' . $base_hook,
  ];
  \Drupal::moduleHandler()->alter($hooks, $suggestions, $variables, $base_hook);

  array_unshift($suggestions, $base_hook);

  return $suggestions;
}

function mymodule_get_active_theme_suggestion($suggestions) {

  $theme_registry = theme_get_registry(FALSE);

  // Order by most specific first.
  $suggestions = array_reverse($suggestions);

  foreach ($suggestions as $candidate) {
    if ($theme_registry
      ->has($candidate)) {
      return $candidate;
    }
  }
}


Location to Call the function theme_uc_price($variables)

Since it's a theme function, based on DrupalContrib theme_uc_price it's called about 12 times within the Ubercart Suite.

As an example from one of the functions that calls the theme function which is uc_object_attributes_form.

theme('uc_price', array('price' => $option->price))

That's how Drupal uses theme functions.


Global variable, visible only inside the module

If you use the same global variable, its value is shared between all the enabled modules because global variables are globals by definition. Every PHP file that is loaded will see the same global variables, such as the global $user that is used from Drupal for the account of the currently logged-in user.

The same is true if you use constants defined with define(); they are global, and two modules cannot define the same constants. Try defining the REQUEST_TIME in Drupal 7, with define('REQUEST_TIME, 'test'): You will get an error, as the same constant is already defined from Drupal (see REQUEST_TIME).

The same is true for Drupal variables defined with variable_set(). Every module that is using variable_set($name, $value) (where $name has the same value for all the modules) is setting the same variable.

Even if you would be using &drupal_static($name, $value) in different modules, the modules will be altering the same static variable.

I would rather use a constant defined with define(), but every module needs to use a different constant.
See the Drupal coding standards about naming conventions.


I suppose you could use Views Bulk Operations (VBO) to achieve this. VBO lets you select various nodes in a list and then perform an action to all of them. VBO is highly customizable and extendible. VBO can be combined with other modules like mighty Rules and others. Bulk publishing and  unpublishing would (of course) also be possible.

ps: actually this could also be achived through the 'regular' content handling (/admin/content). Just set the content type filter to your content type and you can already bulk publish/unpublish. But I suppose you tried this already and would prefer to have the same nodes as you have in the view?


How to create invisible widget in Drupal

Install the Field Permissions module:

  The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

And the Computed Field module:

  Computed Field is a very powerful CCK field module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields, the current user, database tables, you name it.

You can then create a field for your value, hide it from the registration/profile form, and use Computed Field to set its value to whatever you need it to be automatically.


How to debug D8 library loading?
  ...Therefore I'd like to follow the process in which Drupal loads the library and integrates it into the page.

There some ways to attach a library (look here to see them), this make  a bit hard, the task to create a debug workflow following each process.

  ...which libraries Drupal is trying to load, and possibly, what goes wrong?
  ...Can someone add a general method of how to debug D8 library loading?

Well, there are some ways to see what are attached, I know two options to 'debug'.

Option 1 (check libraries)

Use a function to inspect which library was attached in your page.

function module_page_attachments_alter(&$page) {
  $array_libraries = $page['#attached']['library']; //Use a breakpoint at this line to see libraries.
}

Attention: It is not safe to see all libraries, remember, any other module or theme can use this function too (and you don't know which is called for last), said that, use this option just to check libraries of your own module/theme if they are included, if not, you messed up (misspell, attach at wrong place), you need to check your 'attach' code.

Option 2 (check for files attached in a library)

First, like pointed by @cilefen, you must turn off CSS and js aggregation in performance config tab.

Then you can check all CSS and js files at your browser.

For CSS is easier, they are organized in <head> tag:

All CSS files are grouped in by one <style> tag for each type of media. In this screen has three <style> group with media 'all', the first is base theme, the second is the core (admin bar stuff), and the last one is my theme. If you expand you will see all files:

For js, there two places, if you specified, you will find at <head> tag, if not they are all in end of your <body> tag.

Now,
 - if you miss a file, check your library if is really defined your file;
 - if not loaded (4xx, 5xx, responses to a file), check your file location;
 - and make sure that you cleared the cache.

To keep on track of my libraries I just follow some rules.

When theming, I usually avoid add things in preprocess or other function, and attach all libraries in twig template.

Using this code:

{{ attach_library('theme/library') }}

When creating a module, I just add essential code and always at end of build function and in a top level of $build var (just created a standard for me and always follow this rule).

This way is easier to find where is wrong.

Very important: Considering that you follow all rules of a .yml file and follow a schema for a library definition, sometimes its just tabs that your text edit insist to use, you indentation is wrong or you misspell something.


Override autocomplete provided by module to not suggest current user(self)

If you look at the code in Privatemsg module, the autocomplete callback function provides a hook hook_privatemsg_autocomplete_alter(). You can use this hook and unset the current logged in user from the $matches array.

I don't have Privatemsg module installed in any of my current projects, so I cannot test it, but the following code should do it:

function YOURMODULE_privatemsg_autocomplete_alter(&$matches, $names, $fragment) {
  global $user;
  unset($matches[$user->uid]);
}


How to set type="email" attribute on a Drupal form textfield

Elements which are input[type=email] are a builtin as of Drupal 8. They can be added (along with other HTML5 elements and markup) to Drupal 6 or 7 via the Elements module.

As of writing this answer, I found the Element-module docs quite scant; they don't explain that the method for getting an e-mail input-element is slightly different than how it's done in D8. For Drupal 7:

/**
 * Implements hook_form().
 * "For long-lasting relief you can count on!"
 *
 * hook_form() functions are passed a form-node,
 * plus extra state-info if present.
 *
 * At the end of the function, the form-node should
 * be returned to the caller.
 *
 */
function mymodule_form($node,&$form_state) {

    $node['primary_email'] = array(
        '#type' => 'emailfield',
        '#title' => t('Submitter'),
    ); // in Drupal 8, it's '#type' => 'email'

    return $node;
}

Be sure to have the Elements module enabled before you expect the above to work. Also, if you haven't already, you'll also want to make the form accessible by doing something like:

/**
 * Implements hook_menu().
 * "Money back guarantee!"
 */
function mymodule_menu() {

    // create primary menu-entry for module:
    $items['mymodule'] = array(
        'title' => 'My Very Own Module',
        'page callback' => 'mymodule_description',
        'access callback' => TRUE,
        'expanded' => TRUE,
    );

    // create menu-entry for form:
    $items['mymodule/myform'] = array(
        'title' => 'My Very Own Form',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('mymodule_form'),
        'access arguments' => array('Behold, the form.'),
        'file' => 'mymodule.module',
    );

    // ...[maybe add more stuff here]...

    return $items;

The other elements made available by Element are listed at cgit.drupalcode.org/elements/tree/elements.module#n7.


Drush command to uninstall from enabled...?

Another solution here if you don't want to take the alias route that Tony brought up is to use the && operator to do a one-liner:

drush dis -y my_module && drush pm-uninstall -y my_module


This module is very good for that: Custom Tokens.

  It gives the user the ability to create custom tokens for specific replacements that can improve other modules relying on the Drupal 7 token API or, for Drupal 6, the Token module.


How to wrap first word of page title in span in drupal 7

Not really a Drupal question, but you're setting the wrong variable

$title = implode(' ', $words);

should be

$variables['title'] = implode(' ', $words);

Or, change

$title = $variables['title'];

to

$title = &$variables['title'];

instead. Either will work


Rules condition: check for a product with particular value for a field in the cart

Not sure if this is the best way, but its the only way I can think of to do it.

You can do this by adding 3 different rules as well as adding a new field to "order" at admin/commerce/config/order/fields. We will call the field "Apply Fee" (apply_fee) and it is of the field type "integer"

Rule # 1,
Event: when product added to cart
Condition: Entity has field: Entity=order Field=Apply_Fee
Action: Set Data Value: (use the data selecter to slect the "apply_fee" field) add offset "1"

Rule # 2,
Event: when product removed from cart
Condition: Entity has field: Entity=order Field=Apply_Fee
Action: Set Data Value: (use the data selecter to slect the "apply_fee" field) add offset "-1"

Rule # 3,
Event: Apply fee to order
Condition: Entity has field: Entity=order Field=Apply Fee
Condition: Data Comparison: order's field Apply Fee is Greater than 0
Action: Apply a Fee to order


7 - Posting www links without http prefix

The issue is href="www.google.com" really is http://yourdomainandpath/www.google.com just as href="hello.htm" would be as well.


You can simply do following way, using hook_form_alter, paste following code in your template.php file, save and clear cache. Change the THEME with your themeName in code or if you are doing with costume module then with module name.

In your case the code will be,

function THEME_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'webform_141') {
    $form['#id'] = 'webform_en';
  }
}


Pass variables through AJAX callback and update MySQL database

I actually managed to do it! For anyone that may have a similar problem this is what I did.
First of all, I took the url parameters using parse_url and did the following

$parts =  parse_url($_path);
parse_str($parts['query'], $query);
$first = $query['first'];
$second = $query['second'];

,then put those variables as form default values, that I will hide using css:

$form['user_id'] = array (
         '#type' => 'textfield',
         '#title' => t('User id'),
         '#description' => t('user id'),
         '#default_value' => $first,
);

Then, on my callback function I take those variables, for example:

$_first = filter_xss($_values['first']);

and then I used db_update:

$num_updated = db_update('unsubscribed_users')
    ->fields(array(
        'reason' => $_reason,
      ))
    ->condition('first', $_first , '=')
    ->condition('second', $_second , '=')
    ->execute();


How to programmatically create a large taxonomy in Drupal 7?

Myself still learning how to properly write modules, I managed to come up with the following code for saving the terms into separate table named MODULENAME_data. It may not be perfect - but it apparently worked. I'm open to downvoting, but even more to suggestions on how to improve it.

// Make the table name a constant for easier coding
// We will store it's vid as system variable after we have created it
define("MODULENAME_VOCAB_MACHINE_NAME", "iso_639_3_codes_data");

function MODULENAME_enable(){
  // Create the vocabulary.
  $vocab = array(
    'name' => 'Vocabulary name',
    'machine_name' => MODULENAME_VOCAB_MACHINE_NAME,
    'description' => t('Vocabulary of iso 639-3 language codes'),
    'module' => 'taxonomy',
    'hierarchy' => 0,
    'module' => 'MODULENAME',
  );
  taxonomy_vocabulary_save( (object) $vocab);

  // Now that we've created the vocabulary, let's store its vid as a system variable
  $vocab = taxonomy_vocabulary_machine_name_load(MODULENAME_VOCAB_MACHINE_NAME);
  $vid = $vocab->vid;
  variable_set('MODULENAME_vocab_id', $vid);

  // Create custom field.
  $field = array(
    'field_name' => 'field_custom_field',
    'type' => 'text',
    'label' => t('Symbol') // where is that used? I dunno, but API says so ;-)
  );
  field_create_field($field);

  // Create field instance on the vocab
  $instance = array(
    'field_name' => 'field_custom_field',
    'entity_type' => 'taxonomy_term',
    'bundle' => MODULENAME_VOCAB_MACHINE_NAME,
    'label' => t('Custom field'),
    'description' => t('Description'),
    'required' => true,
    'widget' => array(
      'type' => 'text_textfield',
     )
  );
  field_create_instance($instance);

  // Here you would include an include file that provides row data
  // (probably an array) and then iterate over it to populate table
  // such as

      // Save terms.
      foreach ($items as $item) {
        taxonomy_term_save((object) array(
          'name' => $item[0],
          'vid' => $vid,
          'field_custom_field' => array(
            LANGUAGE_NONE => array(
              0 => array(
                'value' => $item[1] ,
              )
            )
          ),
        ));

}

function MODULENAME_disable(){
  // Some system cleanup.

  // Delete vocabulary. This deletes terms and field references too.
  taxonomy_vocabulary_delete(variable_get('MODULENAME_vocab_id'));

  // Delete variable from system.
  variable_del('MODULENAME_vocab_id');
}

Word of comment:

I'm still not sure whether the hook_disable() would be supposed to do what I put into it, but my understanding is that once a module is disabled, the features installed by it would be supposed to be unavailable too. I'm unsure about the field references - not only do they remain in the system in my code, but once we re-enable the module, the references will not be restored due to new IDs.
I'm also not sure how one would make the vocabulary i18n-savvy, meaning - when you would like to install the vocabulary along with translations - vocabularies provide several i18n modes and I'm not in the knowledge how to support them programatically.

This is something I would love to learn from someone.


Is there a way to make the comment module email the administrators when a comment needs approval?

Sounds like something Rules should be able to do.


How can i customize the display of private message module?

If as you say you only want to change the look/theme then you should create a custom theme and override it using custom css rules.

Doing this requires knowledge of css/html and creating a drupal subtheme as modifying an existing theme/module/core is not advisable

Here is tutorial of how to create a custom subtheme
https://www.drupal.org/docs/7/theming/howto/create-a-new-custom-theme-with-css-alone

NOT RECOMMENDED
If you still want to HACK core/module/theme then in your Chrome/Firefox/Opera/Safari browser just right click on the element that you want to change and use inspect/inspect element or something similar.  There you can see which css rules and in which file influence the display of each element. You can even adjust the visual properties (css rules) of each element and when you are satisfied with the result you should go and change the appropriate files.

Here is a tutorial of how to use the chrome inspector https://developer.chrome.com/devtools but inspectors of other browser should be very similar


Checking for an empty entity reference field in hook_node_validate

Take a look at entityreference_field_is_empty(), which at least will get you up a level by checking if target_id is empty on your behalf.


Get path to theme assets in Twig template

you can use {{ base_path ~ directory }} which will fix the absolute problem, no need to do any preprocessing, both of these variables are included by core.

For example

<img src="{{ base_path ~ directory }}/images/logo.png" alt="My Logo" />

PS. the ~ helper in twig is concatenate.

Edit: at least in the page*.html.twig templates base_path variable is included, possibly you will need to do preprocessing for other templates, you can easily check with {{ dump() }} if the variables are present

// File: THEMENAME.theme in your theme's root directory
function THEMENAME_preprocess(&$variables, $hook)
{
    $variables['base_path'] = base_path();
}


How to Display Unique Values from database using db_select in Drupal

Try

$query = db_select('webform_submitted_data', 'u');
$query->fields('u', array('sid','nid')); $query->condition('nid','49','=');
$results =$query->distinct()->execute();

Api info about unique


Is it possible to add custom entries to the language switcher pointing to the same language?

I think you can use the hook_language_switch_links_alter() to modify the output of the language switcher. I would try to create the needed entries there to maintain the functionality to switch languages properly.


How can I clear the Menu cache after saving some configuration?

Your form code would be helpful to see here to determine if you are using a system_settings_form() function (which seems likely since you are creating a module configuration form) or just a simple form. Regardless, the answer for both is to add a submit_handler to your form.

Basic Form with Submit Handler: https://www.drupal.org/node/717740

If you are not using system_settings_form, than you can add your post-submit actions to a function named after your form definition function, or

/**
 * Add a submit handler/function to the form.
 */
function my_form_submit($form, &$form_state) {
  <YOUR menu_rebuild STUFF HERE>
}

and Form API will automatically find it. If you are using system_settings_form() for your admin form, than you can add your submit handler by adding this before calling system_settings_form()

$form['#submit'][] = 'my_form_submit';


As seen in webform_example_handler

You need to add:

mymodule/mymodule.module

<?php

/**
 * @file
 * Provides a custom webform handler.
 */

/**
 * Implements hook_theme().
 */
function mymodule_theme() {
  return [
    'webform_handler_myform_form_handler_summary' => [
      'variables' => ['settings' => NULL, 'handler' => []],
    ],
  ];
}

mymodule/templates/webform-handler-myform-form-handler-summary.html.twig

{#
/**
 * @file
 * Default theme implementation for a summary of an example webform handler.
 *
 * Available variables:
 * - settings: The current configuration for this email handler:
 *   - message: The message.
 *   - debug: Debugging flag.
 * - handler: The handler information, including:
 *   - id: The handler plugin id.
 *   - handler_id: The handler id.
 *   - label: The handler label.
 *   - description: The handler description.
 *
 * @ingroup themeable
 */
#}
{% if settings.debug %}{{ 'Debugging is enabled'|t }}
{% endif %}
Message: {{ settings.message }}

Clear/flush the cache so your new hook & template file gets picked up.


How to use HTML entities in links in Drupal 8?

The cleanst solution for this is doing it in CSS:

.my_link_css_class::after {
  content: '\00a0\00bb';
}

(\00a0 is for a space, \00bb is for the »)


How to assign a specific color to each taxonomy term in a chart created with the Charts module?

As you must have noticed, creating charts using the Views UI of the Charts module, you can only select 1 color for each chart.

However, if you would rework your chart to a Combination chart, you could set a color for each of the charts. Here are some more details about how I'd create the combination chart (with 1 color for each taxonomy term):

Use your current chart display as the parent chart for 3 child charts to be added to it (as explained below). Adapt its chart settings where needed, so that it won't get in the way of the 3 child charts to be added to it. For that, I'd make it a "line chart", possibly with some other refinements like color and label of that chart also.
Add a 1st (child) chart display with a views filter that limits the values to only your 1st taxonomy term, and specify a 1st color in its chart settings. Use the chart in bullet "1." as its parent chart.
Add a 2nd (child) chart display with a views filter that limits the values to only your 2nd taxonomy term, and specify a 2nd color in its chart settings. Use the chart in bullet "1." as its parent chart.
Add a 3rd (child) chart display with a views filter that limits the values to only your 3rd taxonomy term, and specify a 3rd color** in its chart settings. Use the chart in bullet "1." as its parent chart.

Here is an example of a column chart created as a combination chart:

And this is a variation of it in the format of an area chart (for "total") with 2 line charts:

As both examples illustrate, for each chart in such combination chart, you can assign any combination of colors ... Which is what this question was about, no?

Note: Using this approach, the parent chart in bullet "1." above will avoid that you run into the issue about "holes" in your X-axis data. Refer to my answer to the question about "How to create a combination chart with the Charts module if some X-axis values are missing?" for more details on that.


Changing field instance display settings for view_mode

This took me so long to find. Account Settings -> Manage Display

admin/config/people/accounts/display/teaser


Title link doesn't change after the content type has been changed

For title, try putting Entertainment

  Thanks @No Sssweat.


Display the node edit form on a node view page

You could use Form Block module and place the block above your view block. Some details about it (from its project page):

  Enables the presentation of user registration, site wide contact, or node creation forms in blocks.

OR go with Clive's answer to this Q: Why doesn't loading a form in the view header work? and load the form in your View's header.


How to define specific page on hook_page_top?

You can use the request object to figure out what page you are on and what to do with it.

Fx

$uri = \Drupal::request()->getRequestUri();

Maybe you want to get the route name instead:

$route = \Drupal::routeMatch()->getRouteName();

From there it's just a matter of defining your conditions in the hook.


Send email notification for the new created survey using webform

Webforms does not work that way.  Webforms is for you or an administrator to receive an email when a user on your site fills out a form.

For example, if a customer wants you to send them a brochure in the mail, Webforms will let you know when they fill out your form.

If you want to notify multiple site users (not administrators) about a form being available, consider trying something like MailChimp, or one of the other popular mailing list programs.  The well-known ones (MailChimp, Constant Contact, etc.) all have modules that will allow you to integrate them with your Drupal web site.


Unable to add content in panelized page as administrator, how to overcome?

You might want to go to admin/user/permissions, and see if admin has access to add content.

You might want to see this page Permissions issue

It might be a drupal core issue because it works in drupal 7.5


Values from $node object in Views Contexual Filter

You can access the $node object by doing this in the filter:

$node = menu_get_object()


Describing an Entity Reference relationship

If you want to stick with Entity Reference, you'll need to have a field for each type of relationship. ER relationships don't have the capacity for meta data.

If you can change, check out the Relation module.

  Relation is an API module and storage model for both simple and the most complex relations between entities. The module can handle both directional and symmetrical relations very well.

  Relations are entities and can therefore have fields. This makes Relation the most flexible and powerful relation model out there. (Still, using Relation with anything but the default SQL storage will not work in most cases.)

(emphasis mine). You could, for example, attach a field to the relation entity type, that linked to a vocabulary containing the event role.


query to retrieve all translations and nodes of a language that has been removed from the system?

I ended executing this function to clean up the content:

function delete_non_existing_language_content() {
  // 1. Get enabled languages
  $languages = \Drupal::languageManager()->getLanguages();
  $lang_codes = array();
  foreach ($languages as $language) {
    $lang_codes[] = $language->getId();
  }
  // 2. Get all the nodes that have langcode not in the language list.
  $result = \Drupal::database()->select('node_field_data')
    ->fields('node_field_data')
    ->condition('langcode', $lang_codes, 'NOT IN')
    ->execute();

  // @todo think I can use fetchAllKeyed instead?
  $nids = array_keys($result->fetchAllAssoc('nid'));

  // 3.Delete all of them:
  // @todo Or possibly update them to language neutral code if possible:
  $storage_handler = \Drupal::entityTypeManager()->getStorage('node');
  $entities = $storage_handler->loadMultiple($nids);
  $storage_handler->delete($entities);

}

This worked for my use case, but I don't think it will be performant for large databases.


Trouble updating Modules in Drupal 7 with FTP

I had the same effect.

The instructions at http://bdhacker.wordpress.com/2011/11/26/update-drupal-modules-using-ftp-in-localhost/ have all the necessary details. Especially the vsftp config (/etc/vsftpd.conf) is important. Make sure the following options are set:

listen=YES
local_enable=YES
write_enable=YES
local_umask=022

Don't forget to restart vsftpd after config changes.


drupal_get_form not working when called inside a block

The third argument to your form is $account, and it doesn't have a default argument. You aren't passing that block in your argument, which is why it is crashing.


If you want a simple solution I can suggest what I did before is to redirect both domain.org and domain.net to domain.com using .htaccess redirect rule then all users will be reffered to domain.com first and then log in once there.

You need something like that in .htaccess (or simillar in your httpd configuration file):

RewriteCond %{HTTP_HOST} ^(www\.)?domain\.com [NC]
RewriteRule ^(.*)\.html$ http://domain.com/$1.html [R=301,L]

Or do you need more complex set up and have separate 3 domains with single sign on ?
Then try to use Domain Access module (http://drupal.org/project/domain).


Rules triggering rules - how to enforce or disable it

It will not trigger recursively, Rules has inbuilt mechanism to prevent this. if you check the function rules_element_invoke_component you can see this.

function rules_element_invoke_component($arguments, RulesPlugin $element) {
  ....
  // Handle recursion prevention.
  if ($state->isBlocked($component)) {
     return rules_log('Not evaluating @plugin %label to prevent recursion.',  $replacements, RulesLog::INFO, $component);
  }
  $state->block($component);
  ....
}


When you are using tfd7 you can use extensions, functions, etc. The easiest way to go is to create an own module for handling all the php-functions.

In your OWN_MODULE.module:

function OWN_MODULE_twig_function() {
  $functions = [];
  $functions['XYZ_unset_key'] = new TwigSimpleFunction('XYZ_unset_key', 'XYZ_unset_key_callable');

  ...

  return $functions;
}

function XYZ_unset_key_callable($key, $array) {
  unset($array[$key];
  return $array;
}

After that you can use the function XYZ_unset_key in your twig-files:

<div>
  {{ XYZ_unset_key('field_xyz', 'content') }}
</div>


How to add page content and webform as tab in a page?

There are two ways to do that :

Write a custom module and create a menu path "node/%node/enquiry" and return your enquiry form programmatically. In hook_menu you can set type = MENU_LOCAL_TASK that will display the path as tab.
You can create a view page that displays webform and select the menu Menu tab under menu setting. Path of page should be node/%/enquiry, so that It will create a tab on node/% page. Screenshot for the second method :


Compare date field columns to restrict difference in days between the two

The field validation module does what you want, the interface description can be confusing.

On your Manage fields screen click the validate action link for your relevant date field.
For your field you want to add a Date range2 validation rule.
Name your rule in Rule name to a memorable description.
For column select value2 to validate your end date.
For Cycle of date select global so you can validate against time relative to the start date.
For Maximum date set it to "+30 day" (or any strtotime() compatible relative string) so that the end date is, at most, 30 days from the start date.
Set your your Custom error message.
Click Save rule.


How to customise order cart customer information pane

You can achieve this using Ubercart Webform Integration module.

This module integrates two other modules: webform and ubercart. It allows you sell products directly from your webforms. It is particularly suited to be used as part of a registration system.

Using this module you can create additional field in check page.


How to apply Image Style with no effects and lazy load image?

It may be easiest to use Blazy or Image Lazyloader.

If neither of those suit your needs, I would create a new field formatter class. In your custom module create a new formatter src/Plugin/Field/FieldFormatter/LazyImageFormatter.php that extends Drupal\image\Plugin\Field\FieldFormatter\ImageFormatter.php.
 You'll need to use the same annotation that formatter has, but then you'll only need to implement the viewElements method. Begin the method by calling $elements = parent::viewElements($items, $langcode);. Traverse $elements afterward and update the render array similar to how you have done above. Make sure to return $elements; when you're done.

This will give you a formatter on the manage display screens that you can select on whichever image fields you want on any view mode of any entity. You can even get it to work with any image style selected via your new formatter.

If you've never extended a Drupal 8 plugin check out the plugin api. Once you know how to create and extend one plugin type it's very similar process to create or extend others and you'll quickly find that the world is yours.


Using Rules to send an email to all Simplenews subscribers

Assuming your question is about D7, and looking at the available integration of Simplenews with Rules, there is no out-of-the-box solution (at least not that I'm aware of). So as per your "... maybe a workaround for this?", below is a blueprint of how to get it to work anyhow ...

Create a custom rule in which you use Rules Event "A user has been subscribed", with a Rules Action to flag such user, using the Flag module, and by using a global flag. Label the flag something like "Subscribe to Blog posts Newsletter".
Create a similar custom rule in which you use Rules Event "A user has been unsubscribed", with a Rules Action to unflag such user (for the same flag as described above).
Use the Views module to create a list of all users flagged by the flag described above.
Use the Views Rules module to create an additional Views display in the view described above, of type "Rules".
Improve your existing rule by adding a Rules Action to load the list of all users included in the Rules display created as described above. That should be the list you're asking about in your "specific list of Simplenews subscribers".

True, 3 extra modules (Flag, Views and Views Rules) needed to get this to work. But zero custom code required ... (together with 2 extra rules, and a refinement of your existing rule).


How do you change what a function in a core module does?

This is actually pretty easy.

All you have to do is implement your own template_preprocess_node().  Then inside, it update the $variables that the RDF module made.  If you want to update the header additions that it did, then implement a hook_html_head_alter(), and update those elements.

If you do this from your theme, then these will run after the RDF module.  If you do it from a module, then you need to set the weight to be higher than the RDF module.


View filtering based on entity reference revisions (Paragraph) type

Go to the Advanced section of the view and add a relationship:

RELATIONSHIPS
field_paragraph: Paragraph

Then you can add filters for all paragraph fields including the field for the paragraph type.


Why is a page generated by views listening to block.tpl?

That block is the main content block.

It is provided by the system module and is the default content area block in the page template.

More information:

system_block_info ( delta is "main" )
system_block_view


Yes, you can use Rules to manage roles.

Rules need Event to react on, Condition to evaluate for truth, Action to perform.

Event: It is hard to tell from from your post what would be your Event. I don't use Ubercart, but I assume it provides some Rules Events like Commerce, e.g. 'After adding a product to the cart,' 'On checkout coompletion,' and so on. There's also 'Before saving a user account,' 'After saving a user account' and so on.

Condition: "User has role(s)"

Action: "Add user role", "Remove user role"

Very simple actually.

[ Note also that the current version of Rules (2.8) is BROKEN with Commerce 2 ... not sure if the problem also exists with Ubercart ... users of Commerce have to downgrade Rules to 2.7 ]


Alter the exposed filter value on change of other exposed filter value

The easiest way of solving this, would be to use JavaScript. You need to have all the options available, and with JavaScript you can alter the options based on what's selected. Something like this:

$("#field-1").change(function(){
  if ($(this).val() == 'option_1') {
    var options = '<option value="foo">bar</option>';
    $("#field-2).html(options);
  }
});

The above is merely example code but illustrates the approach. You might need to do some work, in order to get the different options that should be available.


How to track user view of nodes presented in a view?

I've worked out a solution based on the message module (https://drupal.org/project/message) and I think this will solve the problem well. Here's the basic approach:

Install message and create a new message type to capture a specific event (i.e. lesson viewed in my case).
Add an entity reference field to the message type created in #1 (messages are fieldable entities) in order to store a reference to the node that was viewed.
Write a function to create the message type created in #1. There is example code in a example module that comes along with the message module.
Hook the view that needs to trigger message creation and call the function created in #3.
Create a view that lists messages. Messages have good views support.
Add additional message types and logic to capture other kinds of activities (a user completing a video lesson, which in this case will mean working with the wistia api, since the videos are hosted on the wistia platform).

One question: I'm not sure where best to hook views to create a message when a user views a node through the view described in the original question . I'm currently using hook_views_post_render, which seems to work well, since the view provides access to the node id needed to create the message.

Overall, I think message will be a good solution for this problem and will provide a nice foundation for tracking other activities as needed. There's a good video overview of the message module here: https://vimeo.com/63919900


Display distance Coordinate vs Zip Code?

This tutorial helped me when i set my first proximity search.

It goes through eveything you need, and once done, is easily configurable.


I don't know of any modules that enable you to write db records in rules actions.

I guess you could write a custom rules action to write to your custom table and grab all the data in rules but it's just as easy to do something like below using  hook_commerce_checkout_complete:

The trickiest part is obtaining the SKU

<?php
  function hook_commerce_checkout_complete($order) {
    $ow = entity_metadata_wrapper('commerce_order', $order);

    foreach ($ow->commerce_line_items as $line_item) {
     $sku = $line_item->commerce_product->sku->value();

     $record = array(
      'uid' => $uid,
      'order_id' => $order->order_id,
      'order_numer' => $order->order_number,
      'sku' => $sku,
     );
     drupal_write_record('my_custom_table', $record);
    }
  }
?>

Hope this helps.


where to find the variables that can be changed through drush vset

Variables are saved in the variables table in the database. Every module can define its own variables. It is mostly common that the core and contributed modules save their configuration/settings as variables.

It is also mostly common that the modules add a prefix to their variables, so that you can look at the variables table in your database and search for the related module if they defined any variables.

Another approach would be looking in the source code of the configuration form for the related field. For example for file_temporary_path, you would see:

<input type="text" class="form-text" maxlength="255" size="60" value="/tmp"
name="file_temporary_path" id="edit-file-temporary-path">

Here is the name attribute hints that this configuration field will be saved in file_temporary_path variable.

Moreover, if you have Devel module installed, there is a Variable Editor under the path devel/variable, which lists all the variables defined in your site and gives you the possibility to edit or delete them.