Adding the following string to drushrc.php worked for me with Drush 5.4:

$options['variables']['language_default']->language = 'en';

In my setup I placed drushrc.php into sites/default/drushrc.php, for other possible locations see documentation in examples/example.drushrc.php in Drush installation directory.


you could use a hook_form_alter when a node is saved and check if the selected term has already been used. Then just show an error message.


add content page doesnot work for other users

you should include print render($page['content']); in your page.tpl.php file otherwise, it will not display content for the page.

content is default block which Drupal use to render content of a page.

If you do not want to use content region in your theme, then you can set View the administration theme permission for your user role.

Setting permission:

Go to  Administration -> People -> Permissions
Checked check-box of View the administration theme for your user role and save form.


Add a graphic element in content type without modifying the .tpl

You can modify it in a preprocess_page_hook, in template.php file... but I would recommend you to stick with the tpl file approach, as you've done it there.


How do I install core on Windows 10 with Nginx server?

You can use Laragon https://laragon.org it's a dead-simple configuration and you can install a blank drupal 8 projects (+ tons of other options).
If you are more advanced user you can use Docker or Vagrant. I would prefer Docker-based (Lando, Docksal...)


How can I change the node path shown to the user?

Assuming you're using Drupal 7, to manually set a name for a module, all you need to do is to login as admin and navigate to Configuration → URL aliases.  There you can create string aliases for nodes, so that node/2 is aliased to Services.

For the nicest URLs, you should also enable Clean URLs on you site.

If you do not want to do this yourself, but instead want want names to be assigned to node paths automatically (based on some set of rules), then you can install and enable the PathAuto module.


I went back to fpdi-1.6.2, and the error disappeared (the internal fpdi folder content has completely changed between the two versions).


Having duplicate entry error with Panelizer module

Looks like a known bug:  unable to edit nodes with default panelizer state.

Try the patches in the above issue.  Looks like it might be useful to chip in there with your issue also!


If I understand what you want correctly, you don't need a specific module at all to do this. You can just have embed code generated and add that to the source code for the block/page you want to add it to. You can have embed code generated here. Be sure to select "Show Posts" if that's what you want.

Edit: I just re-read your question and see that you mean to do this for the authorized user... in this case my answer may not be helpful.


Contextual Links not appearing in Panels

Please apply a patch from Impossible to set attributes on Panels panes on Drupal.org.

This is a patch to the module I believe will fix the problem you have.


How do I create a module that uses composer to manage a 3rd party library?

In order to have composer download a 3rd party library, you need (as you have already done) a composer.json file within your module. This file should contain the required 3rd party libraries. There are however quite strict guidelines for creating a proper composer.json file for Drupal in which you should at least define the following:

{
    "name": "drupal/example",
    "description": "This is an example composer.json for example module.",
    "type": "drupal-module",
    "license": "GPL-2.0+"
}

Running composer from the module root is indeed not recommended as this might become quite time consuming when installing many modules, not to mention updating all of them once in a while.

Luckily the Drupal guys have done some work, allowing composer to manage all Drupal dependencies, which is out of beta since a few weeks.

This allows you to use composer from the Drupal root to require modules as well. During the downloading of the module all dependenies of it will be resolved as well.

On a small sidenote;
Reading through that blog post again leads me to assume the following should also be included in your module's composer.json file (as of writing the first link also shows an outdated message):

    "repositories": {
        "drupal": {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        }
    }

As for your situation, it seems you should commit a file similar to this to Drupal.org:

{
    "name": "drupal/jquery_colorpicker",
    "description": "jquery_colorpicker module.",
    "type": "drupal-module",
    "license": "GPL-2.0+",
    "repositories": {
        "drupal": {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        }
    },
    "require": {
        ...
    }
}

And then run composer require drupal/jquery_colorpicker from your Drupal root.

UPDATE:
After reading that blog post for the fourth time, I came to conclude that the repositories part is with high probability only required for the root composer file and thus not required for individual modules.


RewriteCond %{HTTPS} !=on
# This checks to make sure the connection is not already HTTPS

RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
# This rule will redirect users from their original location, to the same location but using HTTPS.


Create a view to list contents according to taxonomy & content type

You can create views pages with next pathes:

"taxonomy/term/%/news"

"taxonomy/term/%/events"

"taxonomy/term/%/articles"

Install Pathauto module and add "[term:parent]/[term:name]" pattern for URL alias for your vocabulary, and install Sub-pathauto module that will apply aliases for URL like this 'taxonomy/term/1/news'


The UUID field is what you are looking for. It stands for Universal Unique ID.

  The UUID is guaranteed to be unique and can be used to identify an entity across multiple systems.

-- from Entity::uuid


What is Best Way to Retrieve Status Messages in Multiple Locations?

The solution was using Drupal cache pattern by storing messages in static space as following:

function get_messages(){
    $status_messages = &drupal_static(__FUNCTION__);

    if(!isset($status_messages)){
        //loop through each message type
        foreach (drupal_get_messages(null, true) as $type => $messages) {
               foreach($messages as $key => $message){
                   $status_messages[$type]['enabled'] = true;
                   $status_messages[$type]['messages'] = array(
                       'message' => $message
                   );
               }
        }
     }
     return $status_messages;
}

Here, we get the static reference first and then check if its already set. if not, we retrieve the messages and reset at the same time by calling Drupal API function drupal_get_messages with "true" parameter. As result, we reset the messages that solves our problem and, in addition, our performance is improved due to caching

I have also summarize it all at my blog post "Caching In Drupal"


How to toggle views filter when user click on tab?

You can define two displays in the View which both pull from the "Default" view and use the Tab option for the menu type. Then, override the exposed filters in each of the two displays. So on the display for Tab 1 have the Tab 1 related exposed filters, then on the Tab 2 display you can use your Tab 2 related exposed filters.


How to create a statistics dashboard of my users using Views?

Use the Charts module and its integration with the Views module. A straight forward cloning of the delivered views example would do what you are asking for. Have a look at this online example to get a first impression.

Some more examples of the Charts integration with Views, using data contained in "nodes" (so not using any Views aggregation facilities):

Single chart, not attached to a table, and without aggregation.
Table with attached charts, and without aggregation.
Combination chart without aggregation.

Disclosure: I'm a (co-)maintainer of Charts.


How do I print a taxonomy term in node.tpl.php? (D7)

This works for me:

<?php print render($content['field_tags']); ?>


Install.php not found after installing with Drustack

Please see Usage page of drustack-standard project at GitHub:

  Drupal will be installed in the web-directory.
  Autoloader is implemented to use the generated composer autoloader in vendor/autoload.php, instead of the one provided by Drupal
  (web/vendor/autoload.php).
  Modules (packages of type drupal-module) will be placed in web/modules/contrib/
  Theme (packages of type drupal-theme) will be placed in web/themes/contrib/
  Profiles (packages of type drupal-profile) will be placed in web/profiles/
  Creates default writable versions of settings.php and services.yml.
  Creates sites/default/files-directory.
  Latest version of drush is installed locally for use at vendor/bin/drush.
  Latest version of DrupalConsole is installed locally for use at vendor/bin/drupal.

Therefore setup your web server for DruStack if:

You are running with Apache2, point your DocumentRoot to the web folder
You are running with PHP internal web server, execute php -S 127.0.0.1:8080 -t web

Then access the core/install.php directly to kickstart the installation ;-)


hook_views_pre_render() to override results of a view

Per the first two comments here you should probably use hook_views_post_execute. If you have paged data this will cause issues.


drupal_add_js does not add javascript on after_build

#after_build is called every time the form it built. I've used this myself many times to add JS to forms. Most likely you have a flaw in the script or after build function itself, or you are using cached data when creating the script to display.

If you posted your code, we could provide a better answer.


fetchAllAssoc() is returning only first row

Maybe the reason?
"If the given key appears multiple times, later records will overwrite earlier ones."
https://api.drupal.org/api/drupal/includes!database!database.inc/function/DatabaseStatementInterface%3A%3AfetchAllAssoc/7


How to translate facet filter view search assertions/statements into Russian?

I think you can just import your own translations, creating a simple *.po file.
The structure of that file you can get from https://www.gnu.org/savannah-checkouts/gnu/gettext/manual/html_node/PO-Files.html (or just google the example).
Import your own translations available by uri [yoursite]/admin/config/regional/translate/import


Found it!: module Views Auto-Refresh, which used to be part of the Views Hacks module (but is now considered a "Graduated module", as mentioned on the project page). `Here are some details about it, i.e. a quote from its project page:

... to refresh a view after a specified time interval. Includes advanced options to avoid reloading the whole view, and to avoid causing a full Drupal bootstrap at each refresh.
Suitable for usage on liveblogs, activity streams, comment lists, and any other view where new items are frequently added.


So I found what caused my problem, a silly typo...

Basically, in my custom_commerce.services.yml I had written tads instead of tags.

I fixed it and it's now running as it should.


Ajax Forms created by Ajax Drupal 7 ERROR JAVASCRIPT

I found this way to resolve it. Creating another form whose submit return the form that i want. The code is:

function my_module_botton_create_form($form, &$form_state) {
    $form['create_form'] = array(
        '#type' => 'submit',
        '#value' => '',
        '#ajax' => array(
            'callback' => "my_module_to_create_form",
            'wrapper' => "new_acomp_form",
            'method' => 'replace',
            'effect' => 'fade',
          ),
    );

    return $form;
}

function my_module_to_create_form($form, &$form_state) {

    $form=drupal_get_form("my_module_acomp_form");

        $output = array(
            '#type' => 'ajax',
            '#commands' => array(
                array('command' => 'ajax_create_form_acomp', 'data' => drupal_render($form)),
            ),
        );

        return $output;
}

function my_module_acomp_form($form, &$form_state) {

    ...

    return $form;
}

The JS is

Drupal.ajax.prototype.commands.ajax_create_form_acomp = function (ajax, response, status) {
    $('#new_acomp_form').replaceWith(response.data+"

");
    //Drupal.behaviors.hcat_my_account.check_if_attendant_exits();
};


Views Usage Audit

From project page:

  This module can help you refactor a Drupal codebase by locating redundant views and displays or simply improving your understanding of what views are used where.
  It achieves this by logging where views get executed. You can then run reports from drush or through the UI


Sounds like a job for Field Collection:

  Provides a field-collection field, to which any number of fields can be attached.

and Field Collection Table:

  Provides a table formatter for the Field Collection module.


Conditional e-mails based on radio buttons Drupal Webform

Yes, you want to use hook_mail_alter() in a custom module. This will intercept the outgoing email from Drupal and allow you to add programming logic to the process. For example you could:

Load the webform in question and view its results.
alter the to value of the $message to meet your needs.

  'to': The address or addresses the message will be sent to. The
  formatting of this string will be validated with the PHP e-mail
  validation filter.


Your module can load and execute the view itself. You can get the results from the view without changing the display.

// Load the view
$myview = views_get_view('my_view');
// Set arguments if you need to
$myview->set_arguments(array($code));
// Execute the query
$myview->execute();
// Loop over the results
foreach ($myview->result as $row) {
  // The fields are properties of the row
  $x = $row->my_field;
}


One Drupal site affecting another cloned site

As beth, said in the comment, I am answering this, even after updating the question with answer.

The culprit was Memcached bin, since I am using memcahce_storage module for memcached, the bins of the main site and test site were same, hence, creating this confusion.

I edited the settings.php page of test site and changed the prefix for memcached for test-site as $conf['memcache_storage_key_prefix'] = 'test_site';, now everything is perfect !!!


Drupal 7 get user by Profile2 field value

Why not adding your helper function to query the database, something like below

function mydmoulename_get_user_by_prfoile2field($field_value) {
    $user = new stdClass();
    $user_id = db_select('field_data_field_uid_intranet', 'ui')
        ->fields('ui', array('entity_id'))
        ->condition('field_uid_intranet_value', $field_value, '=')
        ->execute()
        ->fetchAllKeyed(0,0);
    if (is_array($user_id) && count($user_id) > 0) {
        $user = user_load_multiple($user_id);
    }
    return $user;
}

NOTE:

When you add a field to profile, a custom table is created in database,so check your database and get the table name, in above example I am using table name as "field_data_field_uid_intranet". When you browse the table you will find column where it wil be storing the field value against the user who added the fied, you need to check the column name which is holding the field value in above exampe I am using "field_uid_intranet_value" as column name change it according to your requirement.

Once done, now you have your own function simply call it passing the field value as argument like

$user = mymodulename_get_user_by_prfoile2field(100);

you will get the complete user object as return value.


Since Fivestar actually appends its markup to the bottom of the node's content (instead of using Links, for example), its a bit more tricky.

Ideally you would create a seperate node template for your content type, ie: node-story.tpl.php or something like that (depends on your theme).

Once you have a node template you can safely edit, do the following at the top:

<?php
$my_node_content = $node->content['body']['#value'];
$my_fivestar_widget = $node->content['fivestar_widget']['#value'];
?>

Then, instead of <?php print $content; ?>, do: <?php print $my_node_content; ?>

This way, only your node's actual body content will be printed out.

Then, wherever you want, just print out the fivestar widget code!

Here's what it would look like using your markup:

  <?php print $my_node_content; ?>


How to disable the page title output of main content?

The title is probably listed in the content type's manage display list.

Edit the content type and hide the title field.


How can I copy block placements and settings between themes?

Drupal 8 block settings are in configuration files.  It is possible to transfer them but takes a bit of editing / file renaming.

You first have to do a complete export of the configuration files.  In this, the ones you are looking for have names like block.block....yml, e.g.: block.block.old_theme_main_menu.yml

First step is to rename these to block.block.new_theme...yml, e.g : block.block.new_theme_main_menu.yml.  Generally a quick bit of editing to create a script to do the renaming is the easiest.

Next, you need to change the internal theme references to the old theme to the new theme.  E.g. the old theme yml file will look like:

langcode: en
status: true
dependencies:
  config:
    - system.menu.main
  module:
    - block_class
    - system
  theme:
    - old_theme
third_party_settings:
  block_class:
    classes: ''
id: old_theme_main_menu
theme: old_theme
region: navigation_collapsible
weight: -34
provider: null
plugin: 'system_menu_block:main'
settings:
  id: 'system_menu_block:main'
  label: 'Main navigation'
  provider: system
  label_display: '0'
  level: 1
  depth: 2
visibility: {  }

A good editor should be able to do a replace in files to change old_theme to new_theme.  Double check that your theme names are unique in these files.

If the new theme does not have the same regions, then you will need to figure out how to change the region: setting to match your new theme.

In your new theme, create a config directory in the root and then an install directory under it.

Put all the yml files in the install directory.

Uninstall / re-install the new theme to import the settings here.

This assumes the same site with the same code / custom blocks.

If you are going to use this theme in a new site, you will have to make sure the site will provide the blocks defined in the yml config.  Generally, the install directory is used to place system level blocks (e.g main menu) that core provides.  But if you set up a system with a distro or manually to provide other blocks, this works as well.

There may be some minor gotcha's like visibility settings using the wrong node id and the like.


need to have image dragging option to position images in Gallery

This is solved by module called "Draggable Views"


Add different classes to the images that where uploaded with multi-upload

Go to admin/structure/file-types/manage/image/fields. Add a text field for the class.

Now the difficult part is how you are going to get the class as an attribute into the img tag, or into a wrapper div.

If you are using Views you can easily 'rewrite the output of this field' and do it in there.

If you want to render by view mode you can use Display Suite and a custom field template, or you can just forego Display Suite and implement your own custom template file for the file display : Displaying Media

And perhaps rethink your methodology. You can let your client use CKEditor and set the classes to the images right there where he has a proper preview of how it is going to display. You can add your own custom predefined styles that is selectable from a select list. It is also possible to right click on an image and set the classes on.


Views filterable by current logged in user that equals Entity Reference field?

Add your entity reference field as Contextual filter in your View advanced settings and then in the section "when the filter value is not in the url" set the "Provide the default value" to "User ID from logged in user".


Do I have to update to 8.3.0 first before I can update to latest stable release?

It depends on your modules. If you are using DisplaySuite there is an issue with updating because of the change from layout_plugin to the layout_discovery module. See this issue. And have a look at the 8.3.0 Release Notes for broken changes and affected modules.


Starting a site from scratch after running "drush sql-drop"

It looks like your settings.php file is still persisting after the command. Removing it should prompt you for installation on root request.

# Replace with location of settings.php file
settings_file=sites/default/settings.php
drush -y sql-drop && rm "$settings_file"


How to output just a page's contents in page.tpl.php in Drupal 7?

Somethings can be done in page.tpl.php & some in node.tpl.php

Like you said, you need to make title of the node appear before tabs. You can do this in your page.tpl.php. Find $title variable as well as $tabs & arrange accordingly in your page.tpl.php. Like --

<?php if ($title) : ?>

    <?php print $title; ?>

<?php endif; ?>
<?php if ($tabs): ?>

    <?php print render($tabs); ?>

<?php endif; ?>

After this you will have print render($page['content']);, where node.tpl.php comes into the scene, so arranging other things like node content, comment, links you will have to go to your node.tpl.php & arrange accordingly. More modification such as in comment & other TPLs will come into the scene like comment.tpl.php etc..


How to get the original value of a field that is inside a field collection?

Try comparing field_collection_ingredients field value of $node->field_collection_ingredients[LANGUAGE_NONE] and $node->original->field_collection_ingredients[LANGUAGE_NONE], this will give exactly which field collection was removed, you can then try loading that field collection (see note below) and then load $fc->field_ingredient[LANGUAGE_NONE][0]['target_id']; field value to update Node referenced in field_ingredient field.

Note: If your node does not has revision enabled, the removed field collection will be removed from Drupal database as well, which will cause the error when trying to load the Field Collection Entity. So you might need to enable revision for your main node, to make sure that if field collection is removed from field_collection_ingredients field, it will not get removed from Database.


Receive error message for radio buttons ."An illegal choice has been detected. Please contact the site administrator."

I somehow fixed the issue. Normally if it is not a required field we don't need to add the following code.

  '#required' => FALSE,

But adding this code fixed my issue. Please let me know if there is any better or correct way to fix this.


'invalid render array key' error when using an associated array for a twig variable

Twig doesn't understand what you put in the keys image_style and image_path. Twig can handle only arrays when the children are renderable. And this means, they have to contain a '#type' or '#theme' key with a valid render element or theme name. For image styles use the theme image_style:

$variables['photos'] = [];
foreach ($images as $image) {
  $variables['photos'][] = [
    '#theme' => 'image_style',
    '#style_name' => 'photos',
    '#uri' => $image->entity->getFileUri(),
  ];
}

Then Twig can render the images like their are supposed to be rendered without the need for custom php code.


Change user field value to value of another user field

Yes

Programmatically you have to create a custom form with submit button as the only field, now inside the submit handler it will be 2 step process something as below

following code I have written just to give an idea, and assuming field names in a way you can relate. You have to do the tweaks to make it work for you

/**
  * Form Builder
 */
function _my_module_reset_team_selection($form, &$form_state) {
  $form = array();
  $form['reset_options'] = array(
    '#type' => 'select',
    '#title' => 'Reset Options'
    '#options' => array(
      'both' => 'Reset Both Teams',
      'ft'   => 'Reset Friday Team',
      'tt'   => 'Reset Tuesday Team',
    )
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Reset',
  );
}

/**
 * Submit Handler for your custom form.
 * 2 step process 1. Find Users to Update. 2. Update :)
 */
function _my_module_reset_team_selection_submit($form, $form_state) {

  // Logic to decide if to reset both or any one
  // possible values as 'both'/'ft'/'tt'
  $reset = $form_state['input']['reset_options'];
  // Step1. Get All the Users who are part of any team.
  $users_to_reset = _my_module_get_users_to_reset($reset);
  if (is_array($users_to_reset) && count($reset)) {
    // Step2. Update to Reset.
    switch ($reset) {
      case 'both':
        foreach ($users_to_reset as $user_to_reset) {
          // For better performance you can use field_attach_api here**
          // I am using user_save() process
          $user = user_load($user_to_reset);
          $user->field_tuesday[$user->lang][0]['value'] = '';
          $user->field_friday[$user->lang][0]['value'] = '';
          user_save($user);
        }

        break;
      case 'ft':
        foreach ($users_to_reset as $user_to_reset) {
          // For better performance you can use field_attach_api here**
          // I am using user_save() process
          $user = user_load($user_to_reset);
          $user->field_friday[$user->lang][0]['value'] = '';
          user_save($user);
        }
        break;
      case 'tt':
        foreach ($users_to_reset as $user_to_reset) {
          // For better performance you can use field_attach_api here**
          // I am using user_save() process
          $user = user_load($user_to_reset);
          $user->field_tuesday[$user->lang][0]['value'] = '';
          user_save($user);
        }
        break;
    }
  }
}

/**
  *  Helper Function to get list of users to reset.
  *  Allows you to reset any of two Tuesday Team or Friday Team or both.
 */
function _my_module_get_users_to_reset($reset='both') {
  $get_tt_users = array();
  $get_ft_users = array();
  if($reset != 'ft') {
    $get_tt_users = db_select('field_tuesday_team','tt')
                 ->fields('tt',array(entity_id))
                 ->condition('tt.entity_type','user',"=")
                 ->execute()
  }               ->fetchCol();
  if($reset != 'tt') {
    $get_ft_users = db_select('field_friday_team','ft')
                 ->fields('tt',array(entity_id))
                 ->condition('tt.entity_type','user',"=")
                 ->execute()
                 ->fetchCol();
  }
  $users_to_reset = array_unique(array_merge($get_tt_users,$get_ft_users));
  return $users_to_reset;
}


The only solution I have found was to replace body with CCK field. The body in D6 is not CCK field, and it cannot be threated as CCK in many occasions


Show taxonomy children terms when searching parent term

Add these helper functions to your module
  - Call function get_all_nodes_belong_to_taxonomy_hierarchy(), with argument as parent term id, to get all nodes related to parent term
  and child terms both

/**
 * function to get all term ids inside a vocab in a flat array
 * No matter if vocab consists of hierarichal order of terms,you will get all term ids in a flat array.
 * @param
 *   $vocab_machine_name takes vocabulary machine name as parameter.
 * @return
 *   $tids return array of tids in a flat array format
 */
function get_taxonomy_term_ids_inside_vocab($vocab_machine_name) {
  $vocab = taxonomy_vocabulary_machine_name_load($vocab_machine_name);
  if (is_object($vocab)) {
    $term_tree = taxonomy_get_tree($vocab->vid);
    if (is_array($term_tree) && !empty($term_tree)) {
      foreach ($term_tree as $key => $value) {
        $tids[] = $value->tid;
      }
    } if (empty($term_tree)) {
      $tids = array();
    }
  } else
    return "No Vocab Found with the given name";

  return ($tids);
}

/**
 * function to get all the node ids directly mapped to the given taxonomy terms.
 * Returns Flat array of node ids belong to the given term ids.
 * @param
 *   $tid takes term id can be a single term or array of terms.
 * @return
 *   $nid/$nids returns node ids array or sinly node id directly mapped to the given taxonomy term.
 */
function get_nodes_directly_mapped_to_term($tid) {
  if (is_array($tid) && !empty($tid)) {
    foreach ($tid as $key => $value) {
      $nids[] = taxonomy_select_nodes($value);
      $flat_nids = multitosingle($nids);
    }
    return $flat_nids;
  }
  else {
    $nid = taxonomy_select_nodes($tid);
    return $nid;
  }
}

/**
 * function to convert mutlidimension arrays to flat arrays.
 * Returns Flat arrays.
 * @param
 *   $input takes input array as multudimension array.
 *   $output takes output array as paramter in the recursive call.
 * @return
 *   $output return flat array format for the input multidimenional array
 */
function multitosingle($input, $output = array()) {
  ksort($input);
  foreach ($input as $value) {
    $key = count($output);
    if (is_array($value)) {
      $output = multitosingle($value, $output);
    }
    else {
      $output[$key] = $value;
    }
  }
  return $output;
}

/**
 * function to get array/single nids which are attached with any of the taxonomy term of the given vocab.
 * Returns Flat array of nids.
 * @param
 *   $vocab_machine_name takes the machine name for the vocabulary.
 * @return
 *   $nids_inside_vocab returns array of nids/single nid attached to any taxonomy term under the given vocab.
 */
function get_nodes_belong_to_vocab($vocab_machine_name) {
  $vocab_tids = get_taxonomy_term_ids_inside_vocab($vocab_machine_name);
  if (is_array($vocab_tids) && count($vocab_tids) > 0) {
    $nids_inside_vocab = get_nodes_directly_mapped_to_term($vocab_tids);
    return $nids_inside_vocab;
  }
  elseif (is_array($vocab_tids) && count($vocab_tids) == 0) {
    return array();
  }
  else {
    return "There is no vocab found with the given machine name";
  }
}

/**
 * function to get array/single nids inside a single taxonomy term/array of taxonomy terms
 * function to get all node ids recursively inside a taxonomy term.
 * if parent term is passed as parameter then the function returns nid belongs to the parent term and nids related to its child terms.
 * Returns Flat array of nids.
 * @param
 *   $tids takes array/single tids for which you need nids recursively.
 * @return
 *   $nids flat array of nids
 */
function get_all_nodes_belong_to_taxonomy_hierarchy($tids) {
  if (is_array($tids)) {
    foreach ($tids as $key => $value) {
      if ($value <= 0) {
        return "Please Enter a valid taxonomy term id set";
      }
    }
  }
  if (is_array($tids) && !empty($tids)) {
    foreach ($tids as $key => $value) {
      $term = taxonomy_term_load($value);
      $hierarchical_terms_object[] = taxonomy_get_tree($term->vid, $term->tid);
    }
    $flat_terms_object = multitosingle($hierarchical_terms_object);
    if (is_array($flat_terms_object) && !empty($flat_terms_object)) {
      foreach ($flat_terms_object as $key => $value) {
        $flat_tids[] = $value->tid;
      }
      $flat_tids[] = $tids;
      return array_unique(get_nodes_directly_mapped_to_term($flat_tids));
    }
    else {
      $flat_tids = $tids;
      return array_unique(get_nodes_directly_mapped_to_term($flat_tids));
    }
  }
  elseif (!is_array($tids) && $tids > 0) {
    $flat_tids = $tids;
    get_all_nodes_belong_to_taxonomy_hierarchy(array($flat_tids));
  }
  else {
    return "Please Enter a valid term id";
  }
}


Register an anonymous user when entity form is submitted with rules

I thought the field validation module should have been able to do this but I couldn't make it validate against the user mail field. Maybe you could try that and have better luck.

The other option which definitely works and requires no coding is to use the Views Bulk Operations (VBO) module and use rules conditions to check the number of results for that email address.

a. VBO Mail Check View

Create a new view page to display users.
Add the "Bulk operations: User" field (no changes needed).
Add the contextual filter, "User: Email" and provide the default, "Raw value from Url, path component 2".
Test with the preview using a valid email address and make sure one result shows before proceeding.

b. New rule condition in your main rule for when the entity form is saved.

"Check number of results returned by a VBO View"
Choose the view and page display you created above.
Send the text field from the entity form as an argument. (This will be path component 2 in the VBO view above)
Set the minimum value to 1.
Negate the condition.

This will make the rule fire if the VBO view returns zero results ie. no email.

c. Create a new rule to show an error if the mail exists.

Same condition as above.
I don't really know why this works but anyways. Add an AND above the condition, negate it and indent the condition which is also negated. (move it to the right like it's a child). It will look like

Entity has field

NOT AND

      NOT Check number of results returned by a VBO View

Action: Display site message and tell the user that the email is already in use.

It looks a bit convoluted but should only take a few minutes to get working. Good luck!


How to reuse the same custom template in Ajax callback

The replacement for theme() is a build array with a '#theme' key, as you already have for the page.

In Drupal 8 pass this or the other build array from your question unrendered to an ajax html command, because render() in custom code should be avoided if possible:

$build = [
  '#type' => 'container',
  '#attributes' => [
    'class' => ['my_top_message'],
  ],
];

$build['content'] = \Drupal::entityTypeManager()
  ->getViewBuilder('node')
  ->viewMultiple($nodes, 'full');

$response = new AjaxResponse();
$response->addCommand(
  new HtmlCommand('.result_message', $build)
);
return $response;


How programmatically create custom field type with some base fields?

What you want to do is create a field type with multiple properties. This is indeed more efficient than a field collection, because a property only needs one more column in the field table, while a field collection is a complete new entity in the database.

This is the documentation how to build a custom field type from scratch in a custom module:

https://www.drupal.org/docs/8/creating-custom-modules/create-a-custom-field-type

As you want to add a property to an existing field type use this tutorial

https://www.lullabot.com/articles/extending-a-field-type-in-drupal-8

and extend the class ImageItem for the new field type. You also need to extend ImageFormatter to display and ImageWidget to provide a form field for the new property.


User account and Commerce addressfield bug

I modified the user.tokens.inc file by changing $user['name'] to $user['login-name'] and commented out a line and this seemed to fix the problem of the tokens, as the token isn't modified by the username value in $account.

case 'login-name':
//$name = format_username($account);
$replacements[$original] = $sanitize ? check_plain($name) : $name;
break;

However, as you can see, I still haven't solved the problem of the the username field in $account is being modified by commerce shipping and billing. The result is the same whether I set the field to "Full name" or "First name" and "Last name". Inspecting the addressfield module, I can't find the part where it modifies the $account username.


Getting WSOD, can't view any errors even after editing index.php

I figured it out!

The .htaccess file in sites/defaults/files/  CAN NOT include Deny from all

The tutorial I referenced earlier mentioned that /temp/.htaccess should have this included, but it didn't say that if you included it in other files that it would crash your site.

As a side note: It would be great if there was a basic tutorial out there for .htaccess files so that I can get an understanding of everything that's going on here without having to spend months/years learning everything else associated with hosting a drupal website completely inside and out.


nodeapi with op = load being ran multiple times

You need to use view $op

function hook_nodeapi(&$node, $op, $teaser, $page){
  if($node->type=='page' && $op =='view'){
    if ($teaser) {
      drupal_set_message("I am viewing page content type teaser");
      //the rest of my code goes here
    }
    if ($page) {
      drupal_set_message("I am viewing page content type full node view");
      //the rest of my code goes here
    }

  }
}

  view: The node content is being assembled before rendering. The
  module may add elements $node->content prior to rendering. This hook
  will be called after hook_view(). The format of $node->content is the
  same as used by Forms API.

And you need to check for teaser view or full node view using $a3 or $a4 respectively.

Check how many nodes you are rendering in a page. For example if you are in a view where view is displaying 10 nodes then 10 times message will appear.

Hope it answers your issue !


How can I print $submitted in a region template?

The region template has no concept of the page context, so it doesn't know about the node by default.

You can give it that context by implementing hook_preprocess_region() in your theme's template.php file (or a module file), and seeing if there's a node available there:

function MYTHEME_preprocess_region(&$vars) {
  if ($vars['region'] == 'region_name') {
    $node = menu_get_object();

    if ($node) {
      // Adapted from template_preprocess_node().
      $vars['submitted'] = t('Submitted by !username on !datetime', array('!username' => $node->name, '!datetime' => format_date($node->created)));
    }
  }
}

After you clear the caches, your region template on node pages should have the $submitted var available to it. Obviously that might need a bit of tweaking to suit your needs.


How to change Read more option in the front page of drupal 7?

function MODULE_node_view_alter(&$build){
  if( isset($build['links']['node']['#links']['node-readmore']['title']) )
    $build['links']['node']['#links']['node-readmore']['title'] = t('More');
}

You can apply more checks in order to change the link title for some special scenario or for some specific content type.


How to return a specific value when using entity_load?

OK, here's what I did, after discovering Entity Metadata Wrappers:

//FORMATS ARRAY TO SOMETHING EASIER TO HANDLE
$entity_wrapper = entity_metadata_wrapper('paragraphs_item', reset($entity));
//RETURN THE VALUE OF THE IMAGE ARRAY
$image = $entity_wrapper->field_image->value();
//RETURN THE (FULL) URL OF THE IMAGE
$file_url = file_create_url($image['uri']);


How can I add an entity reference to a list entity refences of a node with rules?

You didn't post your setup and where you want to trigger the rule, but you would do this with PHP code added as a rule action:

$node = node_load(YOUR_NODE_ID);
$node->field_you_want_to_save[]['target_id'] = NEW_ENTITY_REFERENCE_ID;
$node->save();


though the solution looks temporary but i see no bugs in it. The solution is to comment the line:

CKEDITOR.instances[textarea_id].destroy(true);

under ckeditor.utils.js

More better option would be to put a condition to skip the destruction of ckeditor instance


Error programmaticaly adding image to node using file_copy

You can try this code:

//$filepath = drupal_realpath('misc/image.jpeg');
 [**UPDATED ANSWER**:]
 $filepath =  $_SERVER['DOCUMENT_ROOT'].base_path() .drupal_get_path('module','payment_details').'/MDSO_20.jpg';

$file = (object) array(
       'uid' => 1,
       'uri' => $filepath,
       'filemime' => file_get_mimetype($filepath),
       'status' => 1,
  );
  $file = file_copy($file, 'public://');
  $node->field_image[LANGUAGE_NONE][0] = (array)$file;
  node_save($node);

Hope this works for you :)

For me it created a node as you below :)


How to redirect user to previous page after form submit?

You want drupal_get_destination(). This function creates a 'destination' query parameter suitable for use in l() that will redirect the user back to the page they came from after submitting the form. So, when you create your link to add a new node, use the l() function along with drupal_get_destination(). For example...

l('Add new foto', 'path/to/add/a/foto', array('query' => drupal_get_destination()))

That should do it.


It looks like you're using path auto to create these urls but the problem is that the transliterated version of your title in the url is too long. Couple easy answers are to either use the shorten module as jimajamma suggests (which is probably the best answer since it helps users with these long, complicated URLs) or you can update your automated alias settings to remove the title and use something else (ex. article/[[nid]]).

However, if you really want to keep the long title, you're going to need to truncate it when used by pathauto. I ran into a similar problem with custom breadcrumbs and long titles so I created a quick token hook to truncate the title. Here's how you could do that:

In your site module (if you don't have one you can create one and name it whatever you like), add the following (this code below was for 6.x) to register a new token to the token list:

function MYMODULE_token_list($type = 'all') {
  $tokens = array();

  if ($type == 'node' || $type == 'all') {
        $tokens['node']['MYMODULENAME-truncate-title'] = t("A truncated title token.");
  }

  return $tokens;
}

Next, add a processing function to tell token what to do with this new token value:

/**
 * Implementation of hook_token_values().
 */
function MYMODULE_token_values($type, $object = NULL, $options = array()) {
  $values = array();

  switch ($type) {
    case 'node':
      $values['MYMODULE-truncate-title']  = _MYMODULE_truncate_title($object->title);
  }
  return $values;
}

Finally, we can add a function to do the operation:

function _MYMODULE_truncate_title($title) {

   if (strlen($title) > 30) {
       $title = drupal_substr($title,0,30)."...";
   }

   return $title;
}

Now, in your automated alias settings you can use this new token instead of the default title token, ex:

article/[[MYMODULE-truncate-title]]

A little more involved than the other options (again, checkout shorten) but thought this code might be of use to others with similar issues.


How to show hidden fields when using Display Suite module to manage display?

You need to enable Extra Fields, which allows Display Suite to manage module-created fields.


You can use the Node Revision Restrict module for this.

  The Node Revision Restrict module allows you to restrict revisions of node for each content type. This module has an admin interface to specify node revision threshold for each content type available. The possible settings include node type, the number of count provided on configuration form for each content type and more. Users with specific permissions can delete any unwanted revisions. Note that this module does not and cannot delete the current revisions of a node.

You could either use the module, or incorporate some of its code. It is a short module. Most of the code relevant to your task can be found in the node_revision_restrict_node_presave function:

/**
 * Implements of hook_presave().
 */
function node_revision_restrict_node_presave($node) {
  $node_type = $node->type;
  $nid = $node->nid;
  $node_data = db_query('SELECT * FROM {node} WHERE nid = :nid', array(':nid' => $nid));
  foreach ($node_data as $node) {
    $revision_data = node_revision_list($node);
    foreach ($revision_data as $revision) {
      $revision_ids[] = $revision->vid;
    }
    $count_to_restrict_set_value = variable_get('restrict_node_revision_number_for_' . $node_type);
    if (isset($count_to_restrict_set_value)) {
      $node_to_restrict = array_slice($revision_ids, $count_to_restrict_set_value, count($revision_ids));
      foreach ($node_to_restrict as $revision_id) {
        node_revision_delete($revision_id);
      }
    }
  }
}

In general, I prefer using a contributed module, if it provides the functionality needed, over maintaining my own code, because I won't have to worry as much about security updates, and other debugging issues, down the road.


Why do all my products (in Ubercart) get taxes applied after upgrading my Rules module?

Your comment about Rules version 7.x-2.3 rings a bell: I'm about sure that that is actually causing your problem. Refer to these issues for some more details:

Upgrading Rules from 2.3 to 2.6 brings white screen.
<7.x-2.4 breaks site with "Fatal error: Class 'RulesEventHandlerEntityBundle' not found".

I've hit a similar issue some months ago (in an "old D7 site where Rules wasn't upgraded yet from a pre-7.x-2.3 version). After I upgraded to the most recent Rules version (7.x-2.9) my site was broken also. I don't remember what the actual error was, but I narrowed it down to this Rules upgrade issue.

The way I got around it was like so:

Uninstall the 7.x-2.9 version of Rules (that I had ust upgraded to).
Re-install (from scratch) the 7.x-2.9 version of Rules.

That solved "my" issue. And I'm pretty sure it will also solve yours ... wanna try it? Attention: backup any of your custom rules first. E.g via an "export" of those custom rules (before uninstall), and "import" again afterwards (after you upgraded).

PS: just in case anybody else ever looks at this answer before upgrading from a pre-7.x-2.4 version of Rules, you can avoid the above surprises when upgrading Rules to something like 7.x-2.9 by:

first uninstalling the old version (after export of custom rules),
and then installing the newest Rules version (and then import of custom rules).


What hook for installing a large list of field options?

I would probably use the List field predefined options module.


Select list ajax callback fire only once to update textfield

Quickly tested your code and it works.

The only thing that looks a bit odd in your hook implementation, is the name of the function. It seems you are writing your custom code as if your module was named 'field_collection'. There is already a contrib module called that, and you may have already installed it. It would be better to place your function into your custom module's "namespace". Event better would be to also use the hook_form_FORM_ID_alter hook, since it's more efficient.

In any case, with those two small rewrites, the code ran as expected and I was able to get multiple ajax updates of the text_for_test field.

/**
 * Implements hook_form_FORM_ID_alter().
 */
function YOUR_CUSTOM_MODULE_form_employee_performance_node_form_alter (&$form, &$form_state) {
  $form['field_my_weight_select'][LANGUAGE_NONE]['#ajax'] = array(
    'callback' => 'custom_test_entity_callback',
    'wrapper' => 'custom_test_entity_wrapper',
    'method' => 'replace',
    'effect' => 'fade',
    'event' => 'change',
  );

  $form['field_text_for_test']['#prefix'] = '
';
  $form['field_text_for_test']['#suffix'] = '
';

  if (isset($form_state['values']['field_my_weight_select'])) {
    $content_type = $form_state['values']['field_my_weight_select'][LANGUAGE_NONE][0]['value'];
    $form["field_text_for_test"][LANGUAGE_NONE][0]['value']['#value'] = $content_type;
  }
  else {
    $form["field_text_for_test"][LANGUAGE_NONE][0]['value']['#value'] = 1;
  }
}

/**
 * Ajax callback for updating field_text_for_test.
 */
function custom_test_entity_callback($form, $form_state) {
  $form['field_text_for_test']['#prefix'] = '
';
  $form['field_text_for_test']['#suffix'] = '
';
  return $form['field_text_for_test'];
}

Update: If you want to make sure, your form alter hook is called last (in relation to other modules):

/**
 * Implements hook_module_implements_alter().
 */
function CUSTOM_MODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook != 'form_employee_performance_node_form_alter') {
    return;
  }
  $module = 'CUSTOM_MODULE';
  $group = array($module => $implementations[$module]);
  unset($implementations[$module]);

  $implementations = $group + $implementations; //You want your implementation to run last.
}

Good luck!


How to change Display modes per node (view modes)?

That's a task for hook_entity_view_mode_alter.

  Change the view mode of an entity that is being displayed.

See the following working sample that automatically lets node 123 be rendered in the teaser view mode when accessed as full page. You could simply add your own logic (type, user, datetime etc.) as well.

/**
 * Implements hook_entity_view_mode_alter().
 */
function MYMODULE_entity_view_mode_alter(&$view_mode, Drupal\Core\Entity\EntityInterface $entity, $context) {

  // Change the view mode to teaser on full page view for node ID 123.
  if ($entity->getEntityTypeId() == 'node' && $entity->id() == '123' && $view_mode == 'full') {
    $view_mode = 'teaser';
  }
}

As you can maybe imagine, from $entity you can get any field value of a node. So you could add some select list field or taxonomy reference to your content type and then adjust that value node-wise. Finally you can use above code snippet to switch the view mode depending on these values. Mission accomplished.


How do I change the ajax loading behaviour in Views?

If you don't mind using a little jquery you could always do something like:

$('#view-id').ajaxStart(function(){
   $('#view-filters-id').fadeTo(300, 0.5);
});
$('#view-id').ajaxSuccess(function(){
   $('#view-filters-id').fadeTo(300, 1.0);
});


You don't want to modify the $form array in the _submit function. Rather, you should modify the $form_state['values'] array, as that's where all submitted values are stored. So:

function custom_login_form_submit(&$form, &$form_state) {
  if (isset($form_state['input']) && !empty($form_state['input']['username']) && !empty($form_state['input']['hidden_id'])) {
    $form_state['values']['username_hidden_id'] = $form_state['values']['username'] . '-' . $form_state['values']['hidden_id'];
  }
}

Note that you can also do all of the above in the _validate function, and $form_state['values']['username_hidden_id'] will then be available in the _submit function.

Why do you need it to act like a submitted field, though? I would just save it as a variable and use it as needed, like so:

function custom_login_form_submit(&$form, &$form_state) {
  if (isset($form_state['input']) && !empty($form_state['input']['username']) && !empty($form_state['input']['hidden_id'])) {
    $username_hidden_id = $form_state['values']['username'] . '-' . $form_state['values']['hidden_id'];
  }
  // Do something with $username_hidden_id here.
}


Perform actions on field collection insert or update

A Field Collection Item is an entity, so the equivalents of the node hooks are hook_entity_insert()

  Act on entities when inserted.

And hook_entity_update()

  Act on entities when updated.


Hierarchical Select - with "hs_menu" submodule this module allow built "hierarchical" select of parent for menu.


how to depricate repeated field values from my view?

You can apply GROUP BY or DISTINCT by enabling views aggregation
  settings to remove duplicate records.

  Go and edit your view
  In Advanced » OTHER section by enabling Use aggregation: Yes
  In FIELDS or FILTER CRITERIA section, select and apply Aggregation settings for which fields you want to group by or distinct.

source: https://www.drupal.org/node/1704962


How to disable stripping tags for View header?

Please got to the view you have created and follow the below steps :

Header > Add > Type "Text area" in Search
Select Text area > Add and configure header
Under the content insert

    Filters
    <select><option value="Select filter" disabled default">Select filter</option></select>

Dont forget to change the Text format  to Full HTML and click on save


Permissions issue. That simple. And I wasn't noticing it.

setting.php file has read only permissions (444) by default. So I changed to 644 permissions and that's it.


Cannot create custom translated path alias for /user/login

You can try this module: https://www.drupal.org/project/rename_admin_paths
Should do the job... Good luck!


How to print a field content link in the views-view-field template in Drupal 7?

I'm not an expert and this may not be the absolute best way, but it works for me in D7 view-view-field templates.

Include something like this in your template file

<a href="<?php print base_path().drupal_get_path_alias("node/{$row->nid}") ?>">...


How do I disable a core installation profile?

In Drupal 7, a install profile is like a module, but a special one, with two major exceptions:

Any module required by a install profile can be disabled --as you have found-- except the ones required by drupal core (field, filter, node, system, user). See module_disable() function for details, where the dependency on the install profile is explicitly discarded.
The profile used to install a site is also a required module. This is hardcoded in drupal_required_modules().

So a profile can't be uninstalled, because it is a required module.

You can set status to 0 in system table, but you shouldn't, since:

Drupal expects the install profile to be enabled, and rely on that for some operations, none if them critical afaik.
it is a module, it may implement any hook (in its .profile file), or declare any function required by a profile's submodule. Disabling it the hard way may produce misfunction or a php fatal error in those scenarios.

Btw, the install profile used to install the site is stored in the install_profile variable

# drush vget install_profile
install_profile: 'minimal'

You can, if you find it useful for some reason, change the install profile by setting install_profile to any other profile name and enabling it in the system table.


"InvalidArgumentException: Field field_participant_email is unknown" although it exists

The syntax for the field condition(s) is missing a column name (and potentially an operator)

$query->condition('field_participant_email.value', $email, '=');

Here is a useful tutorial on Entity Queries for Drupal 8 I always refer to:

The Drupal 8 version of EntityFieldQuery


How do I get the name and URL alias of a vocabulary using only  the vid?

You can use taxonomy_vocabulary_load() to obtain the machine name of a specific vid.

Example usage:

$vocabulary = taxonomy_vocabulary_load($vid);
$machine_name = $vocabulary->machine_name;
$name = $vocabulary->name;

Vocabularies aren't exposed to the user like terms are, so they don't really have an url-alias. The name which is presented in the vocabulary list is $name in the above code.


Views doesn't split content into seprates list items

Assuming all of these images are in a multi-value field:

Make sure your view is showing "Fields" instead of "Teaser" or some other display setting
Add your multi-value image field through the Fields section "Add" button
Configure the field by clicking on it. You should see a pop-up window with collapsible sections at the bottom - the top section is "Multiple Field Settings". Open that section. Turn on the setting "Display all values in the same row"; when you click that, it'll open the "Display Type" options, for which you'll pick either "Ordered list" or "Unordered list" (assuming unordered list, since you use  in the question's code).


How does the events dispatcher map to map_save to a callback function?

This event is fired by \Drupal\migrate\Plugin\migrate\id_map\Sql::saveIdMapping().

$this->eventDispatcher->dispatch(MigrateEvents::MAP_SAVE, new MigrateMapSaveEvent($this, $keys + $fields));

To listen and react to this event you need to add a new service that implements \Symfony\Component\EventDispatcher\EventSubscriberInterface and tag it with 'event_subscriber'.

This is what you find in content_translation.services.yml.

content_translation.updates_manager:
  class: Drupal\content_translation\ContentTranslationUpdatesManager
    arguments: ['@entity.manager', '@entity.definition_update_manager']
    tags:
      - { name: event_subscriber }

This tells the event dispatcher the ContentTranslationUpdatesManager class subscribes to events.

When you look at \Drupal\content_translation\ContentTranslationUpdatesManager::getSubscribedEvents() you can see that it subscribes to the \Drupal\Core\Config\ConfigEvents::IMPORT event and when this event fires, the \Drupal\content_translation\ContentTranslationUpdatesManager::onConfigImporterImport() method should fire, with a priority of 60. Note that priority works in reverse to the typical Drupal weight: This listener goes before those with a lower priority and after those with a higher priority.

You can read about the generic event dispatcher in the symfony documentation.

The Drupal relevant bit here is the event_subscriber tag, which is processed in a compiler pass by \Drupal\Core\DependencyInjection\Compiler\RegisterEventSubscribersPass::process(), taking care of the registering of listeners automatically, based on the presence of that tag.


How can I see a log of emails that Drupal has sent?

Drupal doesn't keep hold of that information, so your server mail logs are the place to look.

Some email operations are recorded to the watchdog, but not all. You can get a look at a few of those ops with a simple query like this

SELECT * FROM watchdog WHERE message LIKE '%email%'

That'll get you false positives, but also should show you what operations are actually recorded (welcome message sent, new password sent, etc.).

For future reference, you can use either of these modules to log outgoing mail:

Mail Log
Email Log


How to create a RSS feed of certain content type ( without affecting the front end layout )?

Views will allow you to do it.  But when you make changes to the view you must select "over ride for this view" or it will change all views associated with the RSS feed.


After a small fight I managed to have it solved. There are few issues to have in mind like caching or preventing infinite recursion (you don't want to change the queries that you use inside the query altering function).

The code is based on TAC module.

function mymodule_query_term_access_alter($query) {
    static $mymodule_recursion_flag = FALSE;

    //prevent infinite recursion altering db_queries inside of this function
    if($mymodule_recursion_flag) return;

    // Take no action if there is no term table in the query.
    $alias = '';
    $tables =& $query->getTables();
    foreach ($tables as $i => $table) {
        if (strpos($table['table'], 'taxonomy_term_') === 0) {
            $alias = $table['alias'];
        }
    }
    if (empty($alias)) {
        return;
    }

    //store once obtained results
    static $mymodule_tids = null;
    if($mymodule_tids == null){
        //set the recursion flag
        $mymodule_recursion_flag = TRUE;
        // Fetch a list of all terms the user should not see
        $mymodule_tids = mymodule_get_taxonomy_black_list();
        //unset the recursion flag
        $mymodule_recursion_flag = FALSE;
    }
    // No restrictions - user can list all terms
    if (empty($mymodule_tids)) {
        return;
    }
    // Otherwise, filter the terms
    else {
        $query->condition($alias . ".tid", $mymodule_tids, "NOT IN");
    }
}


Data export import failed to import into Drupal 7

It is possible you can't since this module wasn't created for 6-7 migration. (It's too bad, too.)
From the Data Export Import project page:

NB - This module has primarily been developed to move data between the same versions of Drupal - to move data between a live site and a development/beta site.
It may be possible that the taxonomy terms and users data files exported from Drupal 6 can be imported into a Drupal 7 site (or the other way around). This has not been tested yet and any feedback would be gratefully received.

You could try contacting the maintainer through the issue queue, see if it's a small thing they can fix, but since the project is currently looking for a new maintainer I wouldn't expect a quick response.


Sometimes, if I need to differentiate between different debug items, I'll use something like the following:

kpr(array(
  'node' => $node,
  'comments' => $comments,
  'links' => $links,
));

Or, if debug items are split in different places, just simply:

kpr(array('user' => $user));


Using regex path pattern on Themekey module

This should do it:

node-alias ~ /\/organize$/


Overwrite Taxonomy Term page display settings with custom URL's

You can set the patterns used for Taxonomy URL aliases.

http://drupal.org/node/120631

Sounds like you want to use: [term:vocabulary]/[term:name]

If you have it enabled, you should be able to see the patterns here:
www.yoursite.com/admin/config/search/path/patterns


A contributed module without an issue tracker on Drupal.org?

It seems that within the edit section of any project page (which is available to e.g. the project maintainer), inside the Issues tab, there is a checkbox with label Enable issue tracker.

By default, this checkbox is enabled. But if you disable it, the block (column right) with title "Issues for moduleX" is not shown anymore.

And if you re-enable that checkbox again, the block is also shown again ... And the issues that existed before the block is disabled, seem to still exist. So unchecking that checkbox does not delete all existing issues (as it should be I think).


Search a content type fields based on user inputs

If you want result from a specific content type then user views with expose filter for search and filter it with the specific content type.
Why do you need single table for all the fields, Either you can use join to fetch data from all the table. You should not write custom code for this kind of functionality best option is to alter the search query or user views with expose filter to provide this functionality.


Is it helpful to improve performance by mysql table indexing?

The cache_default table already has an index by CID (as well as indexes by creation and expiry date that allow old entries to be discarded).
Since almost all queries to the table are by CID there's not really any need for other indexes and it's not clear what benefit you would hope to see.
Adding extra indexes to tables does not result in cost-free performance enhancement. Every additional index makes write operations to the table more expensive, so you should not add any new index to a table until you have clear evidence of slow queries resulting from its absence.


How to programatically convert nodes from draft to saved

You can change Workflow status for all nodes using Views Bulk Operations module
Here is a little manual how to accomplish this task:

Download and install Views Bulk Operations module
Create a view that will show content of necessary content type in table format.

Add in this view next fields: Content: Title, Workflow history: New state name, Workflow history: Old state name and Bulk operations: Content.

Open created view page, select all nodes, choose "Change workflow state of post to new state" operation and click on the "Execute" button

Choose new node state and click on the "Next" button

On the next page press on the "Confirm" button


How restrict Anonymous users from creating accounts

Go to sitename.com/admin/config/people/accounts

Scroll down to find REGISTRATION AND CANCELLATION

Select appropriate option in Who can register accounts? field


Node hits getting cached for anonymous user

Ok i have resolved this using a database query and a custom block. Pre-req: Installing visitors module.
Then having this query in the custom clock
public function build() {
  $node = \Drupal::request()->attributes->get('node');
  $uidValue = $node->getOwnerId();
  $urlValue = $node->toUrl()->toString();
  $database = \Drupal::database();
  **$query = $database->query("SELECT COUNT(visitors_path) AS visitors_path FROM
(visitors) WHERE visitors_path='$urlValue' ");**
  $result = $query->fetchAll();
  $nodecounthit = $result{0}->visitors_path;
  echo "Viewed ".$nodecounthit." times";
//$nodeCount=MyBlock::test();
      }

this function ensured results were not cached.
 public function getCacheMaxAge()
  {
    return 0;
  }


Difference between $this->config and \Drupal::config in ConfigFormBase

In a configuration form use $this->config() and not \Drupal::config().

The difference between both is that the configuration form uses immutable configuration.

When Drupal 8 was in beta, the immutable configuration was introduced to avoid bleeding of overridden values into configuration when saved to the database. See the change record:

Configuration objects by default are immutable

This is the code executed by $this->config() of a configuration form, in a static version:

\Drupal::configFactory()->getEditable('system.site')->set('name', 'My fantastic site')->save();

For Drupal 8.7 it is discussed to display a warning for overridden values:

  This form contains values that have been overridden. Changes to these
  values can still be saved, but the overridden values will take
  precedence. Overrides are as follows ...

See the issue:

There is no indication on configuration forms if there are overridden values


How to display taxonomy terms of a particular vocabulary in views

Answer revised
Create a view of type Node
Add a display of type block or page according to your need
Add your desired fields(CCK) along with a field Taxonomy: Term
Add a filter Taxonomy: Vocabulary and select is one of operator and choose the particular vocabulary name.

This solution will include taxonomy terms associated with content node but filter according to the defined vocabulary in filter.


How to update custom user field on form submit

Use field_attach_form in your page with the field name and user object. You can use field_attach_form_validate and field_attach_submit
to validate and submit the values.


In drupal 7. You can use the "field permissions" module + profile2 module.
In order to disable some fields for anonymous user, you just edit the fields with custom permissions.
You can see the demo of configuration page from here :

Currently to disable some fields from profile2 for register form, I just set permissions that don't allow the anonymous user to see that fields.


Some time ago (D6) I was facing the same problem but then I could not find a solution. I ended up creating database views in my original db looking to the tables of the second db. This way, I was joining tables in default drupal db, which is easy. I dont know the exact changes in the api from d6 -> d7, but this might be an easy solution for you if you cannot solve it other way.


Add an boolean attribute to a text field?

You can write your own field type and widget form. A good example can be either filefield or imagefield.

Or try Field collection module.

So you can create a new type of field in field_collection UI.

Here are tutorials: https://drupal.org/node/1353926


User organic groups for paid elearning courses?

You can set Organic Groups to be visible only to users of certain roles. And with the uc_roles module in Ubercart, you can create products which grant users a certain role.

There's also a module that makes it possible to sell Organic Group membership to one or more groups when a user purchases a particular product: UC OG Subscribe

Depending on what exactly the course learning system would be about, the og could be a good fit. Even without it, though, you can always restrict access to content through core roles, or ACL and the likes.


Same module with different versions in several places

If each copy of the module in the directory structure is in fact a different version (the module's .info file must specify a version number), you can inspect the version listing either via Drush or on the modules listing (install) page.

Version Listing from the Modules Listing page

Navigate to /admin/modules
Find module "xyz" and expand the
description section to reveal which version is being
detected/loaded.
Refer to the example screenshot below, where
Activity Tracker has been expanded.

Version Listing via Drush

Run 'drush pm-list --no-core --status Enabled' to show a list of all modules other than those included with Drupal Core.
Scroll through the list to find your custom module and note the version number in the right column.
Refer to example screenshot below.

What if there are no version numbers, or they are all the same version?

Temporarily modify the version number in the info file.
Push the updated code to your server (if not a local copy of the site).
Flush Drupal Cache, rebuild the registry.
Follow the instructions above to detect which one is used.
Reset the version number and push the updated code to your server (if not a local copy of the site).

Drupal Multisite Note:

If you are running Drupal Multisite, each site with the custom module enabled may be referencing it from a different path (depending on where the module was located at the time the site was being built).

In this situation, check the versions on each site using the instructions above.
Find the most updated version being used so that you can consolidate all the other sites to use the same version/instance.

Consolidating duplicate instances of the module

Since this is a custom module, be sure to check that the functionality provided between versions is in fact the same and that there is an upgrade path between them before consolidating. Sometimes, lesser experienced developers will copy a custom module and completely overhaul its functionality for use on a similar or different site without understanding best practices.

Backup your code and databases, just in case you need to rollback.
Remove older versions/unused copies, ideally keeping/moving your one copy of the module in /web/modules/custom/.
Push the updated codebase to your server.
Clear caches and rebuild the registry.
Run update.php or drush updatedb to ensure any update hooks for the module are applied.
Test the functionality the module provides on each site (for some custom modules, you may need to edit/resave the configuration settings for the module to properly function).
If all is working, it's recommended to create a new restore point backup; otherwise troubleshoot until you get it working or rollback.


How do you output and modify the Content:Path variable using field:PHP global?

To get the content id path data I had to get it from the $view variable:

$view->style_plugin->render_tokens[0]['path']

As seen below the $row->path data is NULL for some reason. Same goes for $data variable as that doesn't have any data at all.


hook_init() is not invoked for cached pages, so you could be opening yourself up to a world of pain if you do that.

Constants outside of a class that need to be accessed by several functions are global by nature, so just put them in the global namespace. It's the best way to ensure they're consistently available when you expect them to be.


Custom simpltest does not run successfully

afaik there's any content-type in the testing site. You need to create it first. For example date module creates one in DateFieldBasic::setUp (surely there're more examples in core, but I've got that one at hand).


Automated login with LDAP always returns error

Perhaps not a direct answer to you question about the LDAP module but I managed to enable SSO in a Windows domain environment with the Webserver authentication (https://www.drupal.org/project/webserver_auth) module.

You need to force Windows Authentication in your IIS site and disable Anonymous authentication. The Webserver authentication module is also capable of creating accounts when a Windows Domain user is visiting your site and is not registered in Drupal.


You should try using the node reference (References) module and create a field on your content type. The node reference will ask you to specify a content type that allows users to select from a list of previously created content. You can also create a view which you can select as the source for the select list.

https://drupal.org/project/references


Fixed time per questions in quiz modules

Made a similar functionality for their tasks.

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


Development without pulling production DB to your local machine

Install Config Ignore and configure it to ignore those config objects from which you think they are going to be changed in production.

  Ever experienced that your site's configuration was overridden, by the
  configuration on the filesystem, when doing a drush cim?

  Not anymore!

  This module is a tool to let you keep the configuration you want, in
  place.

  Lets say that you do would like the system.site configuration (which
  contains that sites name, slogan, email, etc) to remain untouched, on
  your live site, no matter what the configuration, in the config
  folder, says.

  Or maybe you are getting tired of having the devel.settings changed
  every time you import configuration?

  Then this module is what you are looking for.


How to pass Views contextual filter via URL?

Contextual filters aren't passed in separate variables, they are part of the path. If your view path is xxx/yyy then to have a filter value of nn the path would be xxx/yyy/nn.


How to add a flag link to a view that contains only fields with relationships

Quote from your own comment:

  I removed the flag, and re-added it, and suddenly the relationship field is available in the flag. The funny thing is that the flag was already present when I changed the view to only contain related entities, and when I tried to edit the flag relation properties, it did not give a field to add a relationship. Removing and readding the flag did help.

So it seems that "removing and readding the flag" is the solution to answer your question.

Credits: Yuri and Niall Murphy.


How can I sort Views output by whether or not field content matches a string?

Consider two different approaches here:

Add a single view with multiple sort criteria:

Create two views:

The first view should include a filter criteria with operator "is one of" for the textfield value you want to use (ex. "text") and a sort criteria based on date.
The second view should include a filter criteria for "is none of" for the textfield value used in the first view (ex. text).
Within the second view, add a field "Global: View area" within the view header selecting the first view created.

The second option requires additional configuration, but should give you more control over the sorting of the different groups. In addition, using multiple sort criteria for text fields occasionally causes duplicates to appear and the multi-view approach avoids this problem.

Update

Check out Views Argument Extras. This module provides a method to sort based on argument criteria (such as arbitrary fields) without using weights. Here's my configuration:

The above configuration will be too simplified for your 'sort by day, then text field, then time configuration', but it's a good start. To sort by day, then text field, then time you'll need to use the date module and limit the elements that it sorts by (checkboxes).

If this is something you plan to apply globally, consider adding the Weight module and sort based on that instead of Views Argument Extras.


Does your password contain a #? Try this test:

<?php

function test_url($url) {
    $message = (parse_url($url) === false)?"parse_url unable to parse url:
{$url}\n":print_r(parse_url($url),true);
    echo  $message;
}

test_url("mysql://user:password@site/database_name");
test_url("mysql://user:C0mPl3XP4ss@site/database_name");
test_url("mysql://user:Ci)(*$!@@site/database_name");
test_url("mysql://user:pass#word@site/database_name");
?>

The last URL example fails to be parsed. This appears to be coming from

vendor/drush/drush/src/Sql/SqlBase.php:dbSpecFromDbUrl().

I hit the same issue and traced it to a '#' in my MySQL user password. Changed the password to remove the '#' and everything is working.


How do I make the administrative UI feel like Joomla?

You were going in the right direction with:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  $form['revision_information']['#type'] = 'hidden';
}

However, you have a bug in that code. The code above will modify every form. Instead, use hook_form_FORM_ID_alter to target the specific form.


What is the Views 3 equivalent of the MySQL Limit 1 in order to return just the latest record

To get the query in your question you would use a pager:

Select 'Use pager' in the admin UI
Select 'Display a specified number of items'
Click 'Apply'
Enter '1' for "Items per page" on the settings screen.
Save

I suspect you might be talking more about grouping, though, and that the SQL you've got isn't representative of the query you actually want to run.

If that's the case, you should be able to accomplish what you need buy turning on aggregation, and then setting appropriate values for each field's grouping options.


Show only comments from users with the same role

Disclaimer: I have not had need for this myself, nor do I posses a database where I could perform suitable testing for this. Despite this, I feel confident I understand the problem enough to provide a useful solution.

While I've been writing this answer, I've been struck by the complexity of it.
I've tried to take a step back, and consider if there are other options, but none other come to mind. Perhaps someone else will be able to offer an easier suggestion.

The standard Drupal answer will be use a View, and that is most likely the way I would go about this myself. Even if you require more flexibility than that, the SQL generated by Views would serve as an excellent boilerplate for your own code. It's important to understand, that in my example below, you are required to be able to pass in a "role-id", into the View. This in turn likely requires you to understand and use Page manager + Panels. PM+P can be considered daunting at first, but is a great tool every Drupal site-builder should be familiar with. Tutorial here.

Basic steps to creating such a View:

Create a View. It's important to note the "Show" dropdown on the views/add page. It should be set to comments, not content, that is the default.
By default, Views should create a relationship between the comments, and the content they are posted on. If it's missing, add it. (Comment: content).
We also want information about the posting users group, we need to add a second relationship, (Comment: Author).
Last, we must create a "contextual filter", a filter that asks the currently viewing user "Which role do you have?". Add (User: roles), as a contextual filter. The default settings in on the contextual filter, will likely have the "Relationship" configured to use "Content" for getting the role, but that will give us wrong data, so this needs to be changed to "author" instead.

Done!
Test it out by giving the preview a rold-id as argument, and see what results you get back.

Query below, ready to be pasted into a db_query()-call. This query could also more readily be adapted to take a user-id and "WHERE IN()", the users roles, if necessary.

SELECT comment.subject AS comment_subject, comment.cid AS cid, comment.nid AS comment_nid, comment.created AS comment_created
FROM {comment} comment
INNER JOIN {node} node_comment ON comment.nid = node_comment.nid
LEFT JOIN {users} users_comment ON comment.uid = users_comment.uid
INNER JOIN {users_roles} users_comment__users_roles ON users_comment.uid = users_comment__users_roles.uid
WHERE (( (comment.status <> '0') AND (node_comment.status = '1') AND (users_comment__users_roles.rid = '1') ))
ORDER BY comment_created DESC
LIMIT 10 OFFSET 0

Below follows a full export of my View:

$view = new view;
$view->name = 'rolebasedcomments';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'comment';
$view->human_name = 'tmp';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['query_comment'] = FALSE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: Comment: Content */
$handler->display->display_options['relationships']['nid']['id'] = 'nid';
$handler->display->display_options['relationships']['nid']['table'] = 'comment';
$handler->display->display_options['relationships']['nid']['field'] = 'nid';
$handler->display->display_options['relationships']['nid']['required'] = 1;
/* Relationship: Comment: Author */
$handler->display->display_options['relationships']['uid']['id'] = 'uid';
$handler->display->display_options['relationships']['uid']['table'] = 'comment';
$handler->display->display_options['relationships']['uid']['field'] = 'uid';
$handler->display->display_options['relationships']['uid']['required'] = 0;
/* Field: Comment: Title */
$handler->display->display_options['fields']['subject']['id'] = 'subject';
$handler->display->display_options['fields']['subject']['table'] = 'comment';
$handler->display->display_options['fields']['subject']['field'] = 'subject';
$handler->display->display_options['fields']['subject']['label'] = '';
$handler->display->display_options['fields']['subject']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['subject']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['subject']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['subject']['alter']['word_boundary'] = 0;
$handler->display->display_options['fields']['subject']['alter']['ellipsis'] = 0;
$handler->display->display_options['fields']['subject']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['subject']['alter']['trim'] = 0;
$handler->display->display_options['fields']['subject']['alter']['html'] = 0;
$handler->display->display_options['fields']['subject']['hide_empty'] = 0;
$handler->display->display_options['fields']['subject']['empty_zero'] = 0;
$handler->display->display_options['fields']['subject']['link_to_comment'] = 1;
/* Sort criterion: Comment: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'comment';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Contextual filter: User: Roles */
$handler->display->display_options['arguments']['rid']['id'] = 'rid';
$handler->display->display_options['arguments']['rid']['table'] = 'users_roles';
$handler->display->display_options['arguments']['rid']['field'] = 'rid';
$handler->display->display_options['arguments']['rid']['relationship'] = 'uid';
$handler->display->display_options['arguments']['rid']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['rid']['default_argument_skip_url'] = 0;
$handler->display->display_options['arguments']['rid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['rid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['rid']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['arguments']['rid']['break_phrase'] = 0;
$handler->display->display_options['arguments']['rid']['add_table'] = 0;
$handler->display->display_options['arguments']['rid']['require_value'] = 0;
$handler->display->display_options['arguments']['rid']['reduce_duplicates'] = 0;
/* Filter criterion: Comment: Approved */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'comment';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 0;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status_node']['id'] = 'status_node';
$handler->display->display_options['filters']['status_node']['table'] = 'node';
$handler->display->display_options['filters']['status_node']['field'] = 'status';
$handler->display->display_options['filters']['status_node']['relationship'] = 'nid';
$handler->display->display_options['filters']['status_node']['value'] = 1;
$handler->display->display_options['filters']['status_node']['group'] = 0;
$handler->display->display_options['filters']['status_node']['expose']['operator'] = FALSE;


Can a content type have default input in fields

Yes almost all fields have a section to add default content.
Go to "Structure" > "Content Types" > Your content type > "Manage Fields" then select edit on the field that you want to add the default text to


View exposed filter with month and remove year

Using CSS and jQuery you can achieve your requirement.

Step 1: Using jQuery, on change() event of month select list assign current year to year select list.

$(".date-month").change(function(){
    //write code to set current year to year select list.
});

Step 2: Now using CSS, hide year select list.

.date-year {
    display: none;
}

  Note: You can also achieve the same functionality using Drupal custom hooks.


How To Display Node Tokens/Keys/Content Fields In Twig Template

With Drupal 8 you now have two ways to access to the data of a given node/entity.

The first is with the {{ content.* }} this will return the content that went through the display plugins/system (everything which you configure in the "Display mode" of the content type).

You also can access to the raw data with {{ node.*.value }}

It's preferably that you use the way {{ content.* }} as much as possible in order to be able to use the power of Drupal to quickly change the things with display mode.


Statistics module doesn't show the "Enable access log" checkbox

I'm not sure what you are looking for exactly. That's the only thing that statistics.module is doing in 8.x.

Anything else was removed. Maybe there will be or already are contrib modules providing what statistics module did in 7.x. But tools like Google analytics or Piwik provide a lot better data anyway.


DIV covering over the login buttons in commons-origins theme

The following is a work around.

#block-search-form  .block-inner {
    height: 30px;
}


How to treat textfield as integer field while adding sorting in views?

Solved it by adding a custom handler and used CAST Functions of mysql and changing the query to :

$this->query->add_orderby(NULL, 'CAST(' . $this->real_field . ' AS SIGNED)', $this->options['order']);


Field in custom node tpl - Simple issue that this newb can't figure out

Arpitr was correct but I was also referencing the wrong variable.

The foreach loops states
        foreach ($a_field_collection_item as $a_field_collection_item_object ) {

I guess I just wasnt paying attention. I used this:

    print render($a_field_collection_item->field_service);

but I should have used this:

    print render($a_field_collection_item_object ->field_service);

Final solution for how to theme a field collection in a node template

My content is called opportunities. So in my node--opportunities.tpl.php I put:

    if (!empty($content['MY_FIELD_COLLECTION'])) {
      hide($content['MY_FIELD_COLLECTION']);

      print '
';

      foreach ($content['MY_FIELD_COLLECTION']['#items'] as $entity_uri) {

        $a_field_collection_item = entity_load('field_collection_item', $entity_uri);

            foreach ($a_field_collection_item as $a_field_collection_item_object ) {

                print $a_field_collection_item_object->field_service['und'][0]['entity']->title;
                print $a_field_collection_item_object->field_service_multiplier['und'][0]['value'];
                print $a_field_collection_item_object->field_extend_service_total['und'][0]['value'];

            }
    }
   print '
' . "\n";
   }


Pass custom variable to an entity reference templete

Create two view separate modes for your entity reference, one for each boolean value. In preprocessing, modify the view mode of the entity reference depending on the value of the boolean field.

This is a code example I'm using for paragraphs to change the view mode of a referenced media entity:

function mytheme_preprocess_paragraph__image(array &$variables) {
  $paragraph = $variables['paragraph'];

  if ($paragraph->hasField('field_imageratio')) {
    $imageViewMode = str_replace('media.', '', $paragraph->field_imageratio->target_id);
    if (isset($variables['content']['field_image']['0']['#view_mode'])) {
      $variables['content']['field_image']['0']['#view_mode'] = $imageViewMode;
    }
  }
}

I think you can largely reuse the logic above, field_imageratio should be replaced by your boolean field, field_image should be replaced by your entity reference field.


Pathauto module fits in exactly to serve your requirements.

  The Pathauto module automatically generates URL/path aliases for various kinds of content (nodes, taxonomy terms, users) without requiring the user to manually specify the path alias. This allows you to have URL aliases like /category/my-node-title instead of /node/123. The aliases are based upon a "pattern" system that uses tokens which the administrator can change.


What is the best practice for having a global collection or set number?

A field would be better if the collection number must be unique. If so you can activate the Unique Field module to enforce it, then go ahead and import your existing data.

If it does not have to be unique, either will work, but I would still recommend using a text field rather than a taxonomy.


Is it possible not to have $_GET values in views' exposed filters?

You can enable Ajax and extra stuff will not be added to the URL.
If the problem is too long URLs, do a google search and see how short the URL is. However you can clean up the URL (that means you will use $_GET values) by setting a shorter URL parameter identifier.

Click on the exposed filter and expand the exposed filter settings. You will see a text field to enter the parameter string for this filter. Give a meaningful but tiny string.

For example, default URL would be  like:
path/to/view?field_my_weird_field=drupal

You can change it to:
path/to/view?text=drupal


Module for requiring some authors' texts to be approved by admin

I suggest the Workbench module. You will need to dig deeper to have a revision show up while the next one is being moderated, but I'm sure it can be done with hook_menu_alter.


Modify the node title with the node ID before saving it

Never tried entity_buildres but you could probably use the old and tried way of adding a submit handler

function MODULENAME_form_alter(&$form, &$form_state, $form_id) {
  // this is the create form id, edit form would be node_article_edit_form
  if($form_id == 'node_article_form') {
    $form['actions']['submit']['#submit'][] = 'MODULENAME_change_title';
  }
}

function MODULENAME_change_title($form, $form_state) {
  $node = $form_state->getFormObject()->getEntity();
  $node->setTitle('Custom Title - ' . $node->id());
  $node->save();
}


Custom block: How to know you're in an admin context?

Looks like I just need to call path_is_admin

if (!path_is_admin(current_path())) {
  drupal_not_found();
  drupal_exit(); // This is needed if we call drupal_not_found() from hook_block_view()
}


Use the following snippet to get the user image.

$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
$picture = $user->get('user_picture')->entity->url();

If you want to get the default image when the user account doesn't have an image associated, use the following code.

$field = \Drupal\field\Entity\FieldConfig::loadByName('user', 'user', 'user_picture');
$default_image = $field->getSetting('default_image');
$file = \Drupal::entityManager()->loadEntityByUuid('file', $default_image['uuid']);
$picture = file_create_url($file->getFileUri());


Fatal Error Call to undefined function SearchApiViewsQuery():placeholder

Have you tried using the Realname module on your site? I'd suggest doing it on a copy of the site to test first as it affects quite a lot of things, but if you're doing searches for names it may help, sounds like search api is getting confused trying to join the two fields, so perhaps a different approach may help.

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

HTH

Steve


How to add a custom field to views block

Views is used to pull in existing data/content from other nodes so that you can customise and display it either in new a page or block. There is no body field on the blocks page for a views block is because the contents of that block is controlled by the view and can change dynamically. So if you want to change the body text displayed in the view you can edit the body field of one of the  content nodes your view is collecting from.

When I want to add extra custom text to a view I usually add a random field to the view and then inside that fields settings enable rewriting to allow rewrite the fields output with custom values, if you want to go a bit deeper you can use the module Views Custom Fields as another alternative: https://www.drupal.org/project/views_customfield, but as far as I know editing the body of a views block directly from the blocks admin page is not possible without writing some custom programming.


How to programmatically assign/add new groups to the OG in Drupal Commons 6.25

I am the author of og_massadd (which is quite buggy as it is now, unfortunately), but that module is only for adding users to an OG. But if I understand you correctly, you want to create the actual organic groups?

Doing this through PhpMyAdmin will probably be very cumbersome. You would need to add records to node, revisions, any CCK-tables (if your group nodes have CCK fields), og, og_uid (for group memberships) as a minimum. For addding content to your groups, you would need to add to node, revisions (CCK-tables if necessary) and og_ancestry.

It is a bit easier creating a group programmatically:

$groupnode = new stdClass();
$groupnode->type = 'gruppe'; // Group node type
$groupnode->status = 1;
$groupnode->uid = $owner_uid;
$groupnode->title = $title;
$groupnode->body = $body;
$groupnode->og_selective = $group_acces_level;
$groupnode->og_register = OG_REGISTRATION_NEVER;
$groupnode->og_directory = OG_DIRECTORY_CHOOSE_FALSE;
$groupnode->og_private = variable_get('og_private_groups', OG_PRIVATE_GROUPS_CHOOSE_FALSE);
$groupnode->{_integration_cGroupType}[0]['value'] = $cGroupType_content; // CCK field

node_save($groupnode);

if ($groupnode->nid) {
  og_insert_group($groupnode);

  // Set space (if spaces_og is used)
  //$ogspace = spaces_load('og', $groupnode->nid, TRUE);
  //$ogspace->controllers->variable->set('spaces_preset_og', $spacepreset);

  og_save_subscription($groupnode->nid, $owner_uid, array('is_active' => 1, 'is_admin' => 1));
} else {
  dpm('OG creation failed :(');
}


How do I create a block for my heartbeat activity?

heartbeat has views integration. Just built a view and add it to a block.


Adding conditions to the template file of a view

To add a variable in template files you first need to create it in your template.php of the theme folder using template_preprocess_node function.

/**
* Implements template_preprocess_node.
*/
function theme_preprocess_node(&$variables){
  foreach($variables['field_taxonomy_field'] as $values){  //field_taxonomy_field is the machine name of the taxonomy term field of your content type.
    if($values['tid'] == $term_id){  //$term_id if the id of the term you want to compare.
      $variables['compare_products'] = l("Compare Button", 'node/compare');
      //@todo your stuff here.
    }
  }
}

This will create a variable named $compare_products which you can use in the template file as a variable.

In node--product.tpl.php you can add <?php print $compare_products; ?> and the data from the variable will be shown whenever the variable is available.


Subtheming -  what happens with parent theme's style.css

You can choose which files you want to override in the parent theme... its as simple as including a copy of the files using the same name ex style.css just drop that anywhere inside your sub theme and tweak away.

Any file with the same exact names as files in the parent-theme will now default to the file that is in your sub_theme. So... if you still want the original style.css to load, do not add it to your sub-theme at all & instead create a custom.css and any similarly named style codes will default to the copy in your sub-themes css files first then if needed the original.

To add from your comment below, do not remove the style.css in the main theme unless you are going to bring in all of its code into your custom file.  What would be easiest for light edits would be to create a custom.css file in your sub-theme and only copy over the codes you need to tweak, if your going hog-wild just copy over the whole contents style.css

Hope that helps :)


Webform stores all these files in sites/default/files/webform you can download them with FTP.


Different checkout form based on user or role

i think something along the lines of this should work.  If you have a whole load of these I'd put them in custom module. Otherwise template.php

/***
* Implements hook_form_FORM_ID_alter
*/

function myform_form_theformid_form_alter(&$form, &$form_state, $form_id){
  global $user;
  if (in_array('teller', $user->roles)) {
  unset($form['account_information']);
  }
 }


what json structure does simple oauth expect?

It will depend if the backend can receive a JSON format.

In my case, I am working with the Drupal 8 Module simple Oauth. and the The format for OAuth 2.0 Bearer tokens is actually described in a separate spec, RFC 6750.

More concrete here

  The entity-body follows the encoding requirements of the
  "application/x-www-form-urlencoded" content-type as defined by HTML
  4.01 [W3C.REC-html401-19991224].

So, In my particular case, I will try to send a form-data from angular.